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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
20 * Static field for all the contribution information that we can potentially import
24 public static $_importableFields = NULL;
27 * Static field for all the contribution information that we can potentially export
31 public static $_exportableFields = NULL;
34 * Static field to hold financial trxn id's.
38 public static $_trxnIDs = NULL;
41 * Field for all the objects related to this contribution
43 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
45 public $_relatedObjects = [];
48 * Field for the component - either 'event' (participant) or 'contribute'
49 * (any item related to a contribution page e.g. membership, pledge, contribution)
50 * This is used for composing messages because they have dependency on the
51 * contribution_page or event page - although over time we may eliminate that
53 * @var "contribution"\"event"
55 public $_component = NULL;
58 * Possibly obsolete variable.
60 * If you use it please explain why it is set in the create function here.
64 public $trxn_result_code;
69 public function __construct() {
70 parent
::__construct();
74 * Takes an associative array and creates a contribution object.
76 * the function extract all the params it needs to initialize the create a
77 * contribution object. the params array could contain additional unused name/value
80 * @param array $params
81 * (reference ) an assoc array of name/value pairs.
83 * The array that holds all the db ids.
85 * @return \CRM_Contribute_BAO_Contribution
86 * @throws \CRM_Core_Exception
87 * @throws \CiviCRM_API3_Exception
89 public static function add(&$params, $ids = []) {
94 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be passed into Contribution.add');
96 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
97 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
98 $action = $contributionID ?
'edit' : 'create';
100 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
101 $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)]);
102 throw new CRM_Core_Exception($message);
105 // first clean up all the money fields
110 'non_deductible_amount',
113 //if priceset is used, no need to cleanup money
114 if (!empty($params['skipCleanMoney'])) {
118 // @todo put a deprecated here - this should be done in the form layer.
119 $params['skipCleanMoney'] = FALSE;
120 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
123 foreach ($moneyFields as $field) {
124 if (isset($params[$field])) {
125 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
129 //set defaults in create mode
130 if (!$contributionID) {
131 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
133 if (empty($params['invoice_number'])) {
134 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
135 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
139 //if contribution is created with cancelled or refunded status, add credit note id
140 // do the same for chargeback - this entered the code 'accidentally' but moving it to here
141 // as part of cleanup maintains consistency.
142 if (self
::isContributionStatusNegative(CRM_Utils_Array
::value('contribution_status_id', $params))) {
143 if (empty($params['creditnote_id'])) {
144 $params['creditnote_id'] = self
::createCreditNoteId();
147 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
148 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
149 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
151 if (!$contributionStatusID) {
152 // Since the fee amount is expecting this (later on) ensure it is always set.
153 // It would only not be set for an update where it is unchanged.
154 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
155 'id' => $contributionID,
156 'return' => 'contribution_status_id',
159 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
162 && CRM_Utils_Array
::value('membership_id', $params)
163 && Civi
::settings()->get('deferred_revenue_enabled')
165 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
166 if ($memberStartDate) {
167 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
170 self
::calculateMissingAmountParams($params, $contributionID);
172 if (!empty($params['payment_instrument_id'])) {
173 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
174 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
175 $params['check_number'] = 'null';
179 $setPrevContribution = TRUE;
180 // CRM-13964 partial payment
181 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
182 $partialAmtTotal = $params['partial_payment_total'];
183 $partialAmtPay = $params['partial_amount_to_pay'];
184 $params['total_amount'] = $partialAmtTotal;
185 if ($partialAmtPay < $partialAmtTotal) {
186 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
187 $params['is_pay_later'] = 0;
188 $setPrevContribution = FALSE;
191 if ($contributionID && $setPrevContribution) {
192 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
194 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
196 if ($contributionID && !empty($params['revenue_recognition_date'])
197 && !($previousContributionStatus === 'Pending')
198 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
200 unset($params['revenue_recognition_date']);
203 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
204 isset($params['financial_type_id']))) {
205 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
208 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
210 $contribution = new CRM_Contribute_BAO_Contribution();
211 $contribution->copyValues($params);
213 $contribution->id
= $contributionID;
215 if (empty($contribution->id
)) {
216 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
217 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
218 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
222 $result = $contribution->save();
224 // Add financial_trxn details as part of fix for CRM-4724
225 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
226 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
228 //add Account details
229 $params['contribution'] = $contribution;
230 if (empty($params['is_post_payment_create'])) {
231 // If this is being called from the Payment.create api/ BAO then that Entity
232 // takes responsibility for the financial transactions. In fact calling Payment.create
233 // to add payments & having it call completetransaction and / or contribution.create
234 // to update related entities is the preferred flow.
235 // Note that leveraging this parameter for any other code flow is not supported and
236 // is likely to break in future and / or cause serious problems in your data.
237 // https://github.com/civicrm/civicrm-core/pull/14673
238 self
::recordFinancialAccounts($params);
241 if (self
::isUpdateToRecurringContribution($params)) {
242 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
243 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
245 CRM_Utils_Array
::value('receive_date', $params)
249 $params['contribution_id'] = $contribution->id
;
251 if (!empty($params['custom']) &&
252 is_array($params['custom'])
254 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
257 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
259 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
264 * Is this contribution updating an existing recurring contribution.
266 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
267 * pending payment is being confirmed (or failing).
269 * @param array $params
273 public static function isUpdateToRecurringContribution($params) {
274 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
277 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
280 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
283 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
284 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
291 * Get defaults for new entity.
295 public static function getDefaults() {
297 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
298 FALSE, FALSE, FALSE, 'AND is_default = 1')
300 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
301 'receive_date' => date('Y-m-d H:i:s'),
306 * Fetch the object and store the values in the values array.
308 * @param array $params
309 * Input parameters to find object.
310 * @param array $values
311 * Output values of the object.
313 * The array that holds all the db ids.
315 * @return CRM_Contribute_BAO_Contribution|null
316 * The found object or null
318 public static function getValues($params, &$values = [], &$ids = []) {
319 if (empty($params)) {
322 $contribution = new CRM_Contribute_BAO_Contribution();
324 $contribution->copyValues($params);
326 if ($contribution->find(TRUE)) {
327 $ids['contribution'] = $contribution->id
;
329 CRM_Core_DAO
::storeValues($contribution, $values);
331 return $contribution;
333 // return by reference
339 * Get the values and resolve the most common mappings.
341 * Since contribution status is resolved in almost every function that calls getValues it makes
342 * sense to have an extra function to resolve it rather than repeat the code.
344 * Think carefully before adding more mappings to be resolved as there could be performance implications
345 * if this function starts to be called from more iterative functions.
347 * @param array $params
348 * Input parameters to find object.
351 * Array of the found contribution.
352 * @throws CRM_Core_Exception
354 public static function getValuesWithMappings($params) {
356 $contribution = self
::getValues($params, $values, $ids);
357 if (is_null($contribution)) {
358 throw new CRM_Core_Exception('No contribution found');
360 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
365 * Calculate net_amount & fee_amount if they are not set.
367 * Net amount should be total - fee.
368 * This should only be called for new contributions.
370 * @param array $params
371 * Params for a new contribution before they are saved.
372 * @param int|null $contributionID
373 * Contribution ID if we are dealing with an update.
375 * @throws \CiviCRM_API3_Exception
377 public static function calculateMissingAmountParams(&$params, $contributionID) {
378 if (!$contributionID && !isset($params['fee_amount'])) {
379 if (isset($params['total_amount']) && isset($params['net_amount'])) {
380 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
383 $params['fee_amount'] = 0;
386 if (!isset($params['net_amount'])) {
387 if (!$contributionID) {
388 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
391 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
392 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
393 // net_amount may need adjusting.
394 $contribution = civicrm_api3('Contribution', 'getsingle', [
395 'id' => $contributionID,
396 'return' => ['total_amount', 'net_amount', 'fee_amount'],
398 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
399 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
400 $params['net_amount'] = $totalAmount - $feeAmount;
408 * @param $billingLocationTypeID
412 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
413 $hasBillingField = FALSE;
422 //build address array
424 $addressParams['location_type_id'] = $billingLocationTypeID;
425 $addressParams['is_billing'] = 1;
427 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
428 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
429 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
430 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
432 foreach ($billingFields as $value) {
433 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
434 if (!empty($addressParams[$value])) {
435 $hasBillingField = TRUE;
438 return [$hasBillingField, $addressParams];
442 * Get address params ready to be passed to the payment processor.
444 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
445 * To create an address we need state_province_id.
447 * @param array $params
448 * @param int $billingLocationTypeID
452 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
453 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
454 foreach ($addressParams as $name => $field) {
455 if (substr($name, 0, 8) == 'billing_') {
456 $addressParams[substr($name, 9)] = $addressParams[$field];
459 return [$hasBillingField, $addressParams];
463 * Get the number of terms for this contribution for a given membership type
464 * based on querying the line item table and relevant price field values
465 * Note that any one contribution should only be able to have one line item relating to a particular membership
468 * @param int $membershipTypeID
470 * @param int $contributionID
474 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
475 $numTerms = CRM_Core_DAO
::singleValueQuery("
476 SELECT membership_num_terms FROM civicrm_line_item li
477 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
478 WHERE contribution_id = %1 AND membership_type_id = %2",
479 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
481 // default of 1 is precautionary
482 return empty($numTerms) ?
1 : $numTerms;
486 * Takes an associative array and creates a contribution object.
488 * @param array $params
489 * (reference ) an assoc array of name/value pairs.
491 * The array that holds all the db ids.
493 * @return CRM_Contribute_BAO_Contribution
495 * @throws \CRM_Core_Exception
496 * @throws \CiviCRM_API3_Exception
498 public static function create(&$params, $ids = []) {
504 'revenue_recognition_date',
506 foreach ($dateFields as $df) {
507 if (isset($params[$df])) {
508 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
512 $transaction = new CRM_Core_Transaction();
515 if (!isset($params['id']) && isset($ids['contribution'])) {
516 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be used for contribution create');
517 $params['id'] = $ids['contribution'];
519 $contribution = self
::add($params);
521 catch (CRM_Core_Exception
$e) {
522 $transaction->rollback();
526 $params['contribution_id'] = $contribution->id
;
527 $session = CRM_Core_Session
::singleton();
529 if (!empty($params['note'])) {
531 'entity_table' => 'civicrm_contribution',
532 'note' => $params['note'],
533 'entity_id' => $contribution->id
,
534 'contact_id' => $session->get('userID'),
535 'modified_date' => date('Ymd'),
537 if (!$noteParams['contact_id']) {
538 $noteParams['contact_id'] = $params['contact_id'];
540 CRM_Core_BAO_Note
::add($noteParams);
543 // make entry in batch entity batch table
544 if (!empty($params['batch_id'])) {
545 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
552 $retrieveRequired = 0;
553 foreach ($titleFields as $titleField) {
554 if (!isset($contribution->$titleField)) {
555 $retrieveRequired = 1;
559 if ($retrieveRequired == 1) {
560 $contribution->find(TRUE);
564 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
566 $transaction->commit();
568 $activity = civicrm_api3('Activity', 'get', [
569 'source_record_id' => $contribution->id
,
570 'options' => ['limit' => 1],
572 'activity_type_id' => 'Contribution',
573 'return' => ['id', 'campaign'],
576 //CRM-18406: Update activity when edit contribution.
577 if ($activity['count']) {
578 // CRM-13237 : if activity record found, update it with campaign id of contribution
579 // @todo compare campaign ids first.
580 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
581 $contribution->activity_id
= $activity['id'];
584 if (empty($contribution->contact_id
)) {
585 $contribution->find(TRUE);
587 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
589 // do not add to recent items for import, CRM-4399
590 if (empty($params['skipRecentView'])) {
591 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
592 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
594 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
601 $retrieveRequired = 0;
602 foreach ($titleFields as $titleField) {
603 if (!isset($contribution->$titleField)) {
604 $retrieveRequired = 1;
608 if ($retrieveRequired == 1) {
609 $contribution->find(TRUE);
611 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
612 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
615 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
616 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
617 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
621 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
622 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
623 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
627 // add the recently created Contribution
628 CRM_Utils_Recent
::add($title,
632 $contribution->contact_id
,
638 return $contribution;
642 * Get the values for pseudoconstants for name->value and reverse.
644 * @param array $defaults
645 * (reference) the default values, some of which need to be resolved.
646 * @param bool $reverse
647 * True if we want to resolve the values in the reverse direction (value -> name).
649 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
650 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
651 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
652 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
653 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
657 * Convert associative array names to values and vice-versa.
659 * This function is used by both the web form layer and the api. Note that
660 * the api needs the name => value conversion, also the view layer typically
661 * requires value => name conversion
663 * @param array $defaults
664 * @param string $property
665 * @param array $lookup
666 * @param bool $reverse
670 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
671 $id = $property . '_id';
673 $src = $reverse ?
$property : $id;
674 $dst = $reverse ?
$id : $property;
676 if (!array_key_exists($src, $defaults)) {
680 $look = $reverse ?
array_flip($lookup) : $lookup;
682 if (is_array($look)) {
683 if (!array_key_exists($defaults[$src], $look)) {
687 $defaults[$dst] = $look[$defaults[$src]];
692 * Retrieve DB object based on input parameters.
694 * It also stores all the retrieved values in the default array.
696 * @param array $params
697 * (reference ) an assoc array of name/value pairs.
698 * @param array $defaults
699 * (reference ) an assoc array to hold the name / value pairs.
700 * in a hierarchical manner
702 * (reference) the array that holds all the db ids.
704 * @return CRM_Contribute_BAO_Contribution
706 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
707 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
708 return $contribution;
712 * Combine all the importable fields from the lower levels object.
714 * The ordering is important, since currently we do not have a weight
715 * scheme. Adding weight is super important and should be done in the
716 * next week or so, before this can be called complete.
718 * @param string $contactType
719 * @param bool $status
722 * array of importable Fields
724 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
725 if (!self
::$_importableFields) {
726 if (!self
::$_importableFields) {
727 self
::$_importableFields = [];
731 $fields = ['' => ['title' => ts('- do not import -')]];
734 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
737 $note = CRM_Core_DAO_Note
::import();
738 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
739 unset($tmpFields['option_value']);
740 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
741 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
743 // Using new Dedupe rule.
745 'contact_type' => $contactType,
746 'used' => 'Unsupervised',
748 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
749 $tmpContactField = [];
750 if (is_array($fieldsArray)) {
751 foreach ($fieldsArray as $value) {
752 //skip if there is no dupe rule
753 if ($value == 'none') {
756 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
761 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
762 $tmpContactField[trim($value)] = $contactFields[trim($value)];
764 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
767 $title = $tmpContactField[trim($value)]['title'];
769 $tmpContactField[trim($value)]['title'] = $title;
773 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
774 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
775 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
776 $fields = array_merge($fields, $tmpContactField);
777 $fields = array_merge($fields, $tmpFields);
778 $fields = array_merge($fields, $note);
779 $fields = array_merge($fields, $optionFields);
780 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
781 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
782 self
::$_importableFields = $fields;
784 return self
::$_importableFields;
788 * Combine all the exportable fields from the lower level objects.
790 * @param bool $checkPermission
793 * array of exportable Fields
795 public static function &exportableFields($checkPermission = TRUE) {
796 if (!self
::$_exportableFields) {
797 if (!self
::$_exportableFields) {
798 self
::$_exportableFields = [];
801 $fields = CRM_Contribute_DAO_Contribution
::export();
802 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
803 $fields = array_merge(
805 CRM_Contribute_DAO_Product
::export(),
806 CRM_Contribute_DAO_ContributionProduct
::export(),
807 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
809 'contribution_product_id' => [
810 'title' => ts('Premium'),
811 'name' => 'contribution_product_id',
812 'where' => 'civicrm_product.id',
813 'data_type' => CRM_Utils_Type
::T_INT
,
819 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
821 $contributionPage = [
822 'contribution_page' => [
823 'title' => ts('Contribution Page'),
824 'name' => 'contribution_page',
825 'where' => 'civicrm_contribution_page.title',
826 'data_type' => CRM_Utils_Type
::T_STRING
,
830 $contributionNote = [
831 'contribution_note' => [
832 'title' => ts('Contribution Note'),
833 'name' => 'contribution_note',
834 'data_type' => CRM_Utils_Type
::T_TEXT
,
839 'contribution_batch' => [
840 'title' => ts('Batch Name'),
846 'contribution_campaign_title' => [
847 'title' => ts('Campaign Title'),
848 'name' => 'campaign_title',
849 'where' => 'civicrm_campaign.title',
850 'data_type' => CRM_Utils_Type
::T_STRING
,
853 $softCreditFields = [
854 'contribution_soft_credit_name' => [
855 'name' => 'contribution_soft_credit_name',
856 'title' => ts('Soft Credit For'),
857 'where' => 'civicrm_contact_d.display_name',
858 'data_type' => CRM_Utils_Type
::T_STRING
,
860 'contribution_soft_credit_amount' => [
861 'name' => 'contribution_soft_credit_amount',
862 'title' => ts('Soft Credit Amount'),
863 'where' => 'civicrm_contribution_soft.amount',
864 'data_type' => CRM_Utils_Type
::T_MONEY
,
866 'contribution_soft_credit_type' => [
867 'name' => 'contribution_soft_credit_type',
868 'title' => ts('Soft Credit Type'),
869 'where' => 'contribution_softcredit_type.label',
870 'data_type' => CRM_Utils_Type
::T_STRING
,
872 'contribution_soft_credit_contribution_id' => [
873 'name' => 'contribution_soft_credit_contribution_id',
874 'title' => ts('Soft Credit For Contribution ID'),
875 'where' => 'civicrm_contribution_soft.contribution_id',
876 'data_type' => CRM_Utils_Type
::T_INT
,
878 'contribution_soft_credit_contact_id' => [
879 'name' => 'contribution_soft_credit_contact_id',
880 'title' => ts('Soft Credit For Contact ID'),
881 'where' => 'civicrm_contact_d.id',
882 'data_type' => CRM_Utils_Type
::T_INT
,
886 $fields = array_merge($fields, $contributionPage,
887 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
888 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
891 self
::$_exportableFields = $fields;
894 return self
::$_exportableFields;
898 * Record an activity when a payment is received.
900 * @todo this is intended to be moved to payment BAO class as a protected function
901 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
902 * merit it's own function as it makes the code less rather than more readable.
904 * @param int $contributionId
905 * @param int $participantId
906 * @param string $totalAmount
907 * @param string $currency
908 * @param string $trxnDate
910 * @throws \CRM_Core_Exception
911 * @throws \CiviCRM_API3_Exception
913 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
914 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
916 if ($participantId) {
917 $inputParams['id'] = $participantId;
920 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
921 $entityObj = $entityObj[$participantId];
922 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
925 $entityObj = new CRM_Contribute_BAO_Contribution();
926 $entityObj->id
= $contributionId;
927 $entityObj->find(TRUE);
928 $title = ts('Contribution');
930 // @todo per block above this is not a logical splitting off of functionality.
931 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
935 * Get the value for the To Financial Account.
937 * @param $contribution
942 public static function getToFinancialAccount($contribution, $params) {
943 if (!empty($params['payment_processor_id'])) {
944 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
946 if (!empty($params['payment_instrument_id'])) {
947 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
950 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
951 $queryParams = [1 => [$relationTypeId, 'Integer']];
952 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
957 * Get memberships related to the contribution.
959 * @param int $contributionID
963 protected static function getRelatedMemberships($contributionID) {
964 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
965 'return' => 'membership_id',
966 'contribution_id' => (int) $contributionID,
969 foreach ($membershipPayments as $membershipPayment) {
970 $membershipIDs[] = $membershipPayment['membership_id'];
972 if (empty($membershipIDs)) {
975 // We could combine this with the MembershipPayment.get - we'd
976 // need to re-wrangle the params (here or in the calling function)
977 // as they would then me membership.contact_id, membership.is_test etc
978 return civicrm_api3('Membership', 'get', [
979 'id' => ['IN' => $membershipIDs],
980 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
985 * Cancel contribution.
987 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
989 * @param $processContributionObject
990 * @param $memberships
991 * @param $contributionId
992 * @param $membershipStatuses
993 * @param $updateResult
994 * @param $participant
996 * @param $pledgePayment
998 * @param $pledgePaymentIDs
999 * @param $contributionStatusId
1003 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
1004 // @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
1005 $processContribution = FALSE;
1006 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1007 if (is_array($memberships)) {
1008 foreach ($memberships as $membership) {
1010 //Update Membership status if there is no other completed contribution associated with the membership.
1011 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1012 foreach ($relatedContributions as $contriId) {
1013 if ($contriId == $contributionId) {
1016 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1017 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1021 if ($membership && $update) {
1022 $newStatus = array_search('Cancelled', $membershipStatuses);
1025 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1027 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1028 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1029 'target_contact_id' => $membership->contact_id
,
1030 'source_record_id' => $membership->id
,
1031 'activity_type_id' => 'Change Membership Status',
1032 'status_id' => 'Completed',
1033 'priority_id' => 'Normal',
1034 'activity_date_time' => 'now',
1037 $membership->status_id
= $newStatus;
1038 $membership->is_override
= TRUE;
1039 $membership->status_override_end_date
= 'null';
1040 $membership->save();
1041 civicrm_api3('activity', 'create', $activityParam);
1043 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1044 if ($processContributionObject) {
1045 $processContribution = TRUE;
1052 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1053 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1055 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1056 if ($processContributionObject) {
1057 $processContribution = TRUE;
1061 if ($pledgePayment) {
1062 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1064 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1065 if ($processContributionObject) {
1066 $processContribution = TRUE;
1069 return [$updateResult, $processContribution];
1073 * Do any accounting updates required as a result of a contribution status change.
1075 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1076 * this may attempt to add a payment. We need to resolve that....
1078 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1079 * then updates the contribution but this process should not also record another financial trxn.
1080 * Currently we have weak detection fot that scenario & where it is detected the first returned
1081 * value is FALSE - meaning 'do not continue'.
1083 * We should also look at the fact that the calling function - updateFinancialAccounts
1084 * bunches together some disparate processes rather than having separate appropriate
1087 * @param array $params
1090 * Return indicates whether the updateFinancialAccounts function should continue.
1092 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1093 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1094 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1096 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1097 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1098 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1099 // why it is here or where it is handled instead.
1100 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1101 && $currentContributionStatus == 'Partially paid'))
1106 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1107 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1108 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1110 elseif (($previousContributionStatus == 'Pending'
1111 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1113 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1114 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1116 if ($currentContributionStatus == 'Cancelled') {
1117 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1118 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1119 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1122 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1123 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1127 if (($previousContributionStatus == 'Pending'
1128 ||
$previousContributionStatus == 'In Progress')
1129 && ($currentContributionStatus == 'Completed')
1131 if (empty($params['line_item'])) {
1133 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1134 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1135 // & this can be removed
1138 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1139 // This is an update so original currency if none passed in.
1140 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1142 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1143 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1144 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1145 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1147 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1150 'entity_table' => 'civicrm_financial_item',
1152 foreach ($params['line_item'] as $fieldId => $fields) {
1153 foreach ($fields as $fieldValueId => $lineItemDetails) {
1154 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1156 1 => [$lineItemDetails['id'], 'Integer'],
1158 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1159 while ($financialItem->fetch()) {
1160 $entityParams['entity_id'] = $financialItem->id
;
1161 $entityParams['amount'] = $financialItem->amount
;
1162 foreach (self
::$_trxnIDs as $tID) {
1163 $entityParams['financial_trxn_id'] = $tID;
1164 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1175 * It is possible to override the membership id that is updated from the payment processor.
1177 * Historically Paypal does this & it still does if it determines data is messed up - see
1178 * https://lab.civicrm.org/dev/membership/issues/13
1180 * Read the comment block on repeattransaction for more information
1181 * about how things should work.
1183 * @param int $contributionID
1184 * @param array $input
1186 * @throws \CiviCRM_API3_Exception
1188 protected static function handleMembershipIDOverride($contributionID, $input) {
1189 if (!empty($input['membership_id'])) {
1190 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1191 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1196 * Update all financial items related to the line item tto have a status of paid.
1198 * @param int $lineItemID
1200 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1203 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1206 2 => [$lineItemID, 'Integer'],
1208 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1209 CRM_Core_DAO
::executeQuery($query, $fparams);
1213 * Create the financial items for the line.
1215 * @param array $params
1216 * @param string $context
1217 * @param array $fields
1218 * @param array $previousLineItems
1219 * @param array $inputParams
1220 * @param bool $isARefund
1221 * @param array $trxnIds
1222 * @param int $fieldId
1226 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1227 foreach ($fields as $fieldValueId => $lineItemDetails) {
1228 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1229 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1230 if ($params['contribution']->receive_date
) {
1231 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1234 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1236 $currency = $params['prevContribution']->currency
;
1237 if ($params['contribution']->currency
) {
1238 $currency = $params['contribution']->currency
;
1240 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1242 'transaction_date' => $receiveDate,
1243 'contact_id' => $params['prevContribution']->contact_id
,
1244 'currency' => $currency,
1245 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1246 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
1247 'status_id' => $prevFinancialItem['status_id'],
1248 'financial_account_id' => $financialAccount,
1249 'entity_table' => 'civicrm_line_item',
1250 'entity_id' => $lineItemDetails['id'],
1252 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1253 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1254 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1256 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1257 $taxAmount = (float) $lineItemDetails['tax_amount'];
1258 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1259 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1260 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1262 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1263 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1265 if ($taxAmount != 0) {
1266 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1267 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1268 if ($lineItemDetails['financial_type_id']) {
1269 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1271 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1279 * Does this contributtion status update represent a refund.
1281 * @param int $previousContributionStatusID
1282 * @param int $currentContributionStatusID
1286 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1287 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1290 return self
::isContributionStatusNegative($currentContributionStatusID);
1296 public function addSelectWhereClause() {
1297 $whereClauses = parent
::addSelectWhereClause();
1298 if ($whereClauses !== []) {
1299 // In this case permisssions have been applied & we assume the
1300 // financialaclreport is applying these
1301 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1302 return $whereClauses;
1305 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1306 return $whereClauses;
1308 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1309 if (empty($types)) {
1310 $whereClauses['financial_type_id'] = 'IN (0)';
1313 $whereClauses['financial_type_id'] = [
1314 'IN (' . implode(',', array_keys($types)) . ')',
1317 return $whereClauses;
1321 * @param null $status
1322 * @param null $startDate
1323 * @param null $endDate
1325 * @return array|null
1327 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1331 $where[] = 'contribution_status_id = 1';
1335 $where[] = 'contribution_status_id = 3';
1340 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1343 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1345 $financialTypeACLJoin = '';
1346 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1347 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1348 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1349 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1350 if ($financialTypes) {
1351 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1352 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1355 $where[] = "c.financial_type_id IN (0)";
1359 $whereCond = implode(' AND ', $where);
1362 SELECT sum( total_amount ) as total_amount,
1363 count( c.id ) as total_count,
1365 FROM civicrm_contribution c
1366 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1367 $financialTypeACLJoin
1369 AND ( is_test = 0 OR is_test IS NULL )
1370 AND contact.is_deleted = 0
1374 $dao = CRM_Core_DAO
::executeQuery($query);
1377 while ($dao->fetch()) {
1378 $count +
= $dao->total_count
;
1379 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1383 'amount' => implode(', ', $amount),
1391 * Delete the indirect records associated with this contribution first.
1395 * @return mixed|null
1396 * $results no of deleted Contribution on success, false otherwise
1398 public static function deleteContribution($id) {
1399 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1401 $transaction = new CRM_Core_Transaction();
1404 //delete activity record
1406 'source_record_id' => $id,
1407 // activity type id for contribution
1408 'activity_type_id' => 6,
1411 CRM_Activity_BAO_Activity
::deleteActivity($params);
1413 //delete billing address if exists for this contribution.
1414 self
::deleteAddress($id);
1416 //update pledge and pledge payment, CRM-3961
1417 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1419 // remove entry from civicrm_price_set_entity, CRM-5095
1420 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1421 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1423 // cleanup line items.
1424 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1426 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1427 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1429 if ($participantId) {
1430 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1433 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1437 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1438 $noteId = key($note);
1440 CRM_Core_BAO_Note
::del($noteId, FALSE);
1443 $dao = new CRM_Contribute_DAO_Contribution();
1446 $results = $dao->delete();
1448 $transaction->commit();
1450 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1452 // delete the recently created Contribution
1453 $contributionRecent = [
1455 'type' => 'Contribution',
1457 CRM_Utils_Recent
::del($contributionRecent);
1463 * React to a financial transaction (payment) failure.
1465 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1466 * payments is important for forensic and outreach reasons.
1468 * @param int $contributionID
1469 * @param int $contactID
1470 * @param string $message
1472 * @throws \CiviCRM_API3_Exception
1474 public static function failPayment($contributionID, $contactID, $message) {
1475 civicrm_api3('activity', 'create', [
1476 'activity_type_id' => 'Failed Payment',
1477 'details' => $message,
1478 'subject' => ts('Payment failed at payment processor'),
1479 'source_record_id' => $contributionID,
1480 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1483 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1484 civicrm_api3('contribution', 'create', [
1485 'id' => $contributionID,
1486 'contribution_status_id' => 'Failed',
1491 * Check if there is a contribution with the same trxn_id or invoice_id.
1493 * @param array $input
1494 * An assoc array of name/value pairs.
1495 * @param array $duplicates
1496 * (reference) store ids of duplicate contribs.
1500 * true if duplicate, false otherwise
1502 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1504 $id = CRM_Utils_Array
::value('id', $input);
1506 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1507 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1513 $clause[] = "trxn_id = %1";
1514 $input[1] = [$trxn_id, 'String'];
1518 $clause[] = "invoice_id = %2";
1519 $input[2] = [$invoice_id, 'String'];
1522 if (empty($clause)) {
1526 $clause = implode(' OR ', $clause);
1528 $clause = "( $clause ) AND id != %3";
1529 $input[3] = [$id, 'Integer'];
1532 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1533 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1535 while ($dao->fetch()) {
1536 $duplicates[] = $dao->id
;
1543 * Takes an associative array and creates a contribution_product object.
1545 * the function extract all the params it needs to initialize the create a
1546 * contribution_product object. the params array could contain additional unused name/value
1549 * @param array $params
1550 * (reference) an assoc array of name/value pairs.
1552 * @return CRM_Contribute_DAO_ContributionProduct
1554 public static function addPremium(&$params) {
1555 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1556 $contributionProduct->copyValues($params);
1557 return $contributionProduct->save();
1561 * Get list of contribution fields for profile.
1562 * For now we only allow custom contribution fields to be in
1565 * @param bool $addExtraFields
1566 * True if special fields needs to be added.
1569 * the list of contribution fields
1571 public static function getContributionFields($addExtraFields = TRUE) {
1572 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1573 // @todo remove this - this line was added because payment_instrument_id was not
1574 // set to exportable - but now it is.
1575 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1577 if ($addExtraFields) {
1578 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1581 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1583 foreach ($contributionFields as $key => $var) {
1584 if ($key == 'contribution_contact_id') {
1587 elseif ($key == 'contribution_campaign_id') {
1588 $var['title'] = ts('Campaign');
1590 $fields[$key] = $var;
1593 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1598 * Add extra fields specific to contribution.
1600 public static function getSpecialContributionFields() {
1602 'contribution_soft_credit_name' => [
1603 'name' => 'contribution_soft_credit_name',
1604 'title' => ts('Soft Credit Name'),
1605 'headerPattern' => '/^soft_credit_name$/i',
1606 'where' => 'civicrm_contact_d.display_name',
1608 'contribution_soft_credit_email' => [
1609 'name' => 'contribution_soft_credit_email',
1610 'title' => ts('Soft Credit Email'),
1611 'headerPattern' => '/^soft_credit_email$/i',
1612 'where' => 'soft_email.email',
1614 'contribution_soft_credit_phone' => [
1615 'name' => 'contribution_soft_credit_phone',
1616 'title' => ts('Soft Credit Phone'),
1617 'headerPattern' => '/^soft_credit_phone$/i',
1618 'where' => 'soft_phone.phone',
1620 'contribution_soft_credit_contact_id' => [
1621 'name' => 'contribution_soft_credit_contact_id',
1622 'title' => ts('Soft Credit Contact ID'),
1623 'headerPattern' => '/^soft_credit_contact_id$/i',
1624 'where' => 'civicrm_contribution_soft.contact_id',
1626 'contribution_pcp_title' => [
1627 'name' => 'contribution_pcp_title',
1628 'title' => ts('Personal Campaign Page Title'),
1629 'headerPattern' => '/^contribution_pcp_title$/i',
1630 'where' => 'contribution_pcp.title',
1634 return $extraFields;
1638 * @param int $pageID
1642 public static function getCurrentandGoalAmount($pageID) {
1644 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1645 FROM civicrm_contribution_page p,
1646 civicrm_contribution c
1647 WHERE p.id = c.contribution_page_id
1649 AND c.cancel_date is null
1653 $config = CRM_Core_Config
::singleton();
1654 $params = [1 => [$pageID, 'Integer']];
1655 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1657 if ($dao->fetch()) {
1658 return [$dao->goal
, $dao->total
];
1661 return [NULL, NULL];
1666 * Get list of contributions which credit the passed in contact ID.
1668 * The returned array provides details about the original contribution & donor.
1670 * @param int $honorId
1671 * In Honor of Contact ID.
1674 * list of contribution fields
1675 * @todo - this is a confusing function called from one place. It has a test. It would be
1676 * nice to deprecate it.
1679 public static function getHonorContacts($honorId) {
1681 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1682 $honorDAO->contact_id
= $honorId;
1685 $type = CRM_Contribute_PseudoConstant
::financialType();
1687 while ($honorDAO->fetch()) {
1688 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1689 $contributionDAO->id
= $honorDAO->contribution_id
;
1691 if ($contributionDAO->find(TRUE)) {
1692 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1693 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1694 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1695 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1696 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1697 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1698 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1699 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1700 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1708 * Get the sort name of a contact for a particular contribution.
1711 * Id of the contribution.
1713 * @return null|string
1714 * sort name of the contact if found
1716 public static function sortName($id) {
1717 $id = CRM_Utils_Type
::escape($id, 'Integer');
1720 SELECT civicrm_contact.sort_name
1721 FROM civicrm_contribution, civicrm_contact
1722 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1723 AND civicrm_contribution.id = {$id}
1725 return CRM_Core_DAO
::singleValueQuery($query);
1729 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1731 * @param int|array $contactIDs
1735 public static function annual($contactIDs) {
1736 if (!is_array($contactIDs)) {
1737 // In practice I can't fine any evidence that this function is ever called with
1738 // anything other than a single contact id, but left like this due to .... fear.
1739 $contactIDs = explode(',', $contactIDs);
1742 $query = self
::getAnnualQuery($contactIDs);
1743 $dao = CRM_Core_DAO
::executeQuery($query);
1745 $amount = $average = [];
1746 while ($dao->fetch()) {
1747 if ($dao->count
> 0 && $dao->amount
> 0) {
1748 $count +
= $dao->count
;
1749 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1750 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1756 implode(', ', $amount),
1757 implode(', ', $average),
1764 * Check if there is a contribution with the params passed in.
1766 * Used for trxn_id,invoice_id and contribution_id
1768 * @param array $params
1769 * An assoc array of name/value pairs.
1772 * contribution id if success else NULL
1774 public static function checkDuplicateIds($params) {
1775 $dao = new CRM_Contribute_DAO_Contribution();
1779 foreach ($params as $k => $v) {
1781 $clause[] = "$k = '$v'";
1784 $clause = implode(' AND ', $clause);
1785 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1786 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1788 while ($dao->fetch()) {
1796 * Get the contribution details for component export.
1798 * @param int $exportMode
1800 * @param array $componentIds
1806 public static function getContributionDetails($exportMode, $componentIds) {
1807 $paymentDetails = [];
1808 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1810 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1811 $componentSelect = " civicrm_participant_payment.participant_id id";
1812 $additionalClause = "
1813 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1814 AND civicrm_participant_payment.participant_id {$componentClause} )
1817 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1818 $componentSelect = " civicrm_membership_payment.membership_id id";
1819 $additionalClause = "
1820 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1821 AND civicrm_membership_payment.membership_id {$componentClause} )
1824 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1825 $componentSelect = " civicrm_pledge_payment.id id";
1826 $additionalClause = "
1827 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1828 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1832 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1833 trxn_id, {$componentSelect}
1834 FROM civicrm_contribution
1835 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1836 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1837 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1838 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1839 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1840 AND option_group_contribution_status.id = contribution_status.option_group_id )
1844 $dao = CRM_Core_DAO
::executeQuery($query);
1846 while ($dao->fetch()) {
1847 $paymentDetails[$dao->id
] = [
1848 'total_amount' => $dao->total_amount
,
1849 'contribution_status' => $dao->status
,
1850 'receive_date' => $dao->receive_date
,
1851 'pay_instru' => $dao->payment_instrument
,
1852 'trxn_id' => $dao->trxn_id
,
1856 return $paymentDetails;
1860 * Create address associated with contribution record.
1862 * As long as there is one or more billing field in the parameters we will create the address.
1864 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1867 * @param array $params
1868 * @param int $billingLocationTypeID
1873 public static function createAddress($params, $billingLocationTypeID) {
1874 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1875 if ($hasBillingField) {
1876 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1877 return $address->id
;
1884 * Delete billing address record related contribution.
1886 * @param int $contributionId
1887 * @param int $contactId
1889 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1891 $contactJoin = NULL;
1893 if ($contributionId) {
1894 $clauses[] = "cc.id = {$contributionId}";
1898 $clauses[] = "cco.id = {$contactId}";
1899 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1902 if (empty($clauses)) {
1903 CRM_Core_Error
::fatal();
1906 $condition = implode(' OR ', $clauses);
1910 FROM civicrm_address ca
1911 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1915 $dao = CRM_Core_DAO
::executeQuery($query);
1917 while ($dao->fetch()) {
1918 $params = ['id' => $dao->id
];
1919 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1924 * This function check online pending contribution associated w/
1925 * Online Event Registration or Online Membership signup.
1927 * @param int $componentId
1928 * Participant/membership id.
1929 * @param string $componentName
1933 * pending contribution id.
1935 public static function checkOnlinePendingContribution($componentId, $componentName) {
1936 $contributionId = NULL;
1937 if (!$componentId ||
1938 !in_array($componentName, ['Event', 'Membership'])
1940 return $contributionId;
1943 if ($componentName == 'Event') {
1944 $idName = 'participant_id';
1945 $componentTable = 'civicrm_participant';
1946 $paymentTable = 'civicrm_participant_payment';
1947 $source = ts('Online Event Registration');
1950 if ($componentName == 'Membership') {
1951 $idName = 'membership_id';
1952 $componentTable = 'civicrm_membership';
1953 $paymentTable = 'civicrm_membership_payment';
1954 $source = ts('Online Contribution');
1957 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1960 SELECT component.id as {$idName},
1961 componentPayment.contribution_id as contribution_id,
1962 contribution.source source,
1963 contribution.contribution_status_id as contribution_status_id,
1964 contribution.is_pay_later as is_pay_later
1965 FROM $componentTable component
1966 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1967 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1968 WHERE component.id = {$componentId}";
1970 $dao = CRM_Core_DAO
::executeQuery($query);
1972 while ($dao->fetch()) {
1973 if ($dao->contribution_id
&&
1974 $dao->is_pay_later
&&
1975 $dao->contribution_status_id
== $pendingStatusId &&
1976 strpos($dao->source
, $source) !== FALSE
1978 $contributionId = $dao->contribution_id
;
1982 return $contributionId;
1986 * Update contribution as well as related objects.
1988 * This function by-passes hooks - to address this - don't use this function.
1990 * @param array $params
1991 * @param bool $processContributionObject
1995 * @throws CRM_Core_Exception
1996 * @throws \CiviCRM_API3_Exception
1999 * Use api contribute.completetransaction
2000 * For failures use failPayment (preferably exposing by api in the process).
2003 public static function transitionComponents($params, $processContributionObject = FALSE) {
2004 // get minimum required values.
2005 $contactId = CRM_Utils_Array
::value('contact_id', $params);
2006 $componentId = CRM_Utils_Array
::value('component_id', $params);
2007 $componentName = CRM_Utils_Array
::value('componentName', $params);
2008 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
2009 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
2011 // if we already processed contribution object pass previous status id.
2012 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
2016 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2018 // we process only ( Completed, Cancelled, or Failed ) contributions.
2019 if (!$contributionId ||
2020 !in_array($contributionStatusId, [
2021 array_search('Completed', $contributionStatuses),
2022 array_search('Cancelled', $contributionStatuses),
2023 array_search('Failed', $contributionStatuses),
2026 return $updateResult;
2029 if (!$componentName ||
!$componentId) {
2030 // get the related component details.
2031 $componentDetails = self
::getComponentDetails($contributionId);
2034 $componentDetails['contact_id'] = $contactId;
2035 $componentDetails['component'] = $componentName;
2037 if ($componentName == 'event') {
2038 $componentDetails['participant'] = $componentId;
2041 $componentDetails['membership'] = $componentId;
2045 if (!empty($componentDetails['contact_id'])) {
2046 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2052 // do check for required ids.
2053 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2054 return $updateResult;
2057 //now we are ready w/ required ids, start processing.
2059 $baseIPN = new CRM_Core_Payment_BaseIPN();
2061 $input = $ids = $objects = [];
2063 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
2064 $ids['contribution'] = $contributionId;
2065 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
2066 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
2067 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
2068 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
2069 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
2070 $ids['contributionRecur'] = NULL;
2071 $ids['contributionPage'] = NULL;
2073 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2074 CRM_Core_Error
::fatal();
2077 $memberships = &$objects['membership'];
2078 $participant = &$objects['participant'];
2079 $pledgePayment = &$objects['pledge_payment'];
2080 $contribution = &$objects['contribution'];
2081 $pledgeID = $oldStatus = NULL;
2082 $pledgePaymentIDs = [];
2083 if ($pledgePayment) {
2084 foreach ($pledgePayment as $key => $object) {
2085 $pledgePaymentIDs[] = $object->id
;
2087 $pledgeID = $pledgePayment[0]->pledge_id
;
2090 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2093 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2094 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2099 // we might want to process contribution object.
2100 $processContribution = FALSE;
2101 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2102 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2103 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2105 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2106 if (is_array($memberships)) {
2107 foreach ($memberships as $membership) {
2109 //Update Membership status if there is no other completed contribution associated with the membership.
2110 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2111 foreach ($relatedContributions as $contriId) {
2112 if ($contriId == $contributionId) {
2115 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2116 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2120 if ($membership && $update) {
2121 $membership->status_id
= array_search('Expired', $membershipStatuses);
2122 $membership->is_override
= TRUE;
2123 $membership->status_override_end_date
= 'null';
2124 $membership->save();
2126 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2127 if ($processContributionObject) {
2128 $processContribution = TRUE;
2134 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2135 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2137 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2138 if ($processContributionObject) {
2139 $processContribution = TRUE;
2143 if ($pledgePayment) {
2144 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2146 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2147 if ($processContributionObject) {
2148 $processContribution = TRUE;
2152 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2154 // only pending contribution related object processed.
2155 if ($previousContriStatusId &&
2156 !in_array($contributionStatuses[$previousContriStatusId], [
2161 // this is case when we already processed contribution object.
2162 return $updateResult;
2164 elseif (!$previousContriStatusId &&
2165 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2170 // this is case when we are going to process contribution object later.
2171 return $updateResult;
2174 if (is_array($memberships)) {
2175 foreach ($memberships as $membership) {
2180 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2181 $membership->membership_type_id
,
2182 $membership->is_test
, $membership->id
2185 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2186 // this picks up membership type changes during renewals
2188 SELECT membership_type_id
2189 FROM civicrm_membership_log
2190 WHERE membership_id=$membership->id
2193 $dao = new CRM_Core_DAO();
2195 if ($dao->fetch()) {
2196 if (!empty($dao->membership_type_id
)) {
2197 $membership->membership_type_id
= $dao->membership_type_id
;
2198 $membership->save();
2201 // else fall back to using current membership type
2202 // Figure out number of terms
2204 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2205 foreach ($lineitems as $lineitem) {
2206 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2207 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2209 // in case membership_num_terms comes through as null or zero
2210 $numterms = $numterms >= 1 ?
$numterms : 1;
2215 // CRM-15735-to update the membership status as per the contribution receive date
2217 $oldStatus = $membership->status_id
;
2218 if (!empty($params['receive_date'])) {
2219 $joinDate = $params['receive_date'];
2220 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2221 $membership->end_date
,
2222 $membership->join_date
,
2223 $params['receive_date'],
2225 $membership->membership_type_id
,
2228 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2229 $membership->save();
2232 if ($currentMembership) {
2233 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2234 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2235 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2238 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2241 //get the status for membership.
2242 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2244 $dates['join_date'],
2247 $membership->membership_type_id
,
2251 $formattedParams = [
2252 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2253 array_search('Current', $membershipStatuses)
2255 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2256 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2257 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2260 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2262 $membership->copyValues($formattedParams);
2263 $membership->save();
2265 //updating the membership log
2266 $membershipLog = [];
2267 $membershipLog = $formattedParams;
2268 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2269 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2271 $membershipLog['start_date'] = $logStartDate;
2272 $membershipLog['membership_id'] = $membership->id
;
2273 $membershipLog['modified_id'] = $membership->contact_id
;
2274 $membershipLog['modified_date'] = date('Ymd');
2275 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2277 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2279 //update related Memberships.
2280 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2282 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2283 $scheduledActivityID = CRM_Utils_Array
::value('id',
2284 civicrm_api3('Activity', 'Get',
2286 'source_record_id' => $membership->id
,
2287 'activity_type_id' => $activityType,
2288 'status_id' => 'Scheduled',
2291 'sort' => 'id DESC',
2296 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2297 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2298 if ($scheduledActivityID) {
2299 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2304 // track membership status change if any
2305 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2306 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2307 CRM_Activity_BAO_Activity
::addActivity($membership,
2308 'Change Membership Status',
2311 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2312 'source_contact_id' => $membershipLog['modified_id'],
2313 'priority_id' => 'Normal',
2318 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2319 if ($processContributionObject) {
2320 $processContribution = TRUE;
2323 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2329 $updatedStatusId = array_search('Registered', $participantStatuses);
2330 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2332 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2333 if ($processContributionObject) {
2334 $processContribution = TRUE;
2338 if ($pledgePayment) {
2339 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2341 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2342 if ($processContributionObject) {
2343 $processContribution = TRUE;
2348 // process contribution object.
2349 if ($processContribution) {
2350 $contributionParams = [];
2357 'payment_instrument_id',
2360 'financial_type_id',
2361 'contribution_status_id',
2362 'non_deductible_amount',
2366 foreach ($fields as $field) {
2367 if (empty($params[$field])) {
2370 $contributionParams[$field] = $params[$field];
2373 $contributionParams['id'] = $contributionId;
2374 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2377 return $updateResult;
2381 * Returns all contribution related object ids.
2383 * @param $contributionId
2387 public static function getComponentDetails($contributionId) {
2388 $componentDetails = $pledgePayment = [];
2389 if (!$contributionId) {
2390 return $componentDetails;
2394 SELECT c.id as contribution_id,
2395 c.contact_id as contact_id,
2396 c.contribution_recur_id,
2397 mp.membership_id as membership_id,
2398 m.membership_type_id as membership_type_id,
2399 pp.participant_id as participant_id,
2400 p.event_id as event_id,
2401 pgp.id as pledge_payment_id
2402 FROM civicrm_contribution c
2403 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2404 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2405 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2406 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2407 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2408 WHERE c.id = $contributionId";
2410 $dao = CRM_Core_DAO
::executeQuery($query);
2411 $componentDetails = [];
2413 while ($dao->fetch()) {
2414 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2415 $componentDetails['contact_id'] = $dao->contact_id
;
2416 if ($dao->event_id
) {
2417 $componentDetails['event'] = $dao->event_id
;
2419 if ($dao->participant_id
) {
2420 $componentDetails['participant'] = $dao->participant_id
;
2422 if ($dao->membership_id
) {
2423 if (!isset($componentDetails['membership'])) {
2424 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2426 $componentDetails['membership'][] = $dao->membership_id
;
2427 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2429 if ($dao->pledge_payment_id
) {
2430 $pledgePayment[] = $dao->pledge_payment_id
;
2432 if ($dao->contribution_recur_id
) {
2433 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2437 if ($pledgePayment) {
2438 $componentDetails['pledge_payment'] = $pledgePayment;
2441 return $componentDetails;
2445 * @param int $contactId
2446 * @param bool $includeSoftCredit
2448 * @return null|string
2450 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2454 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2455 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2456 $liWhere = " AND i.financial_type_id IN (0)";
2457 if (!empty($financialTypes)) {
2458 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2459 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2461 $contactContributionsSQL = "
2462 SELECT contribution.id AS id
2463 FROM civicrm_contribution contribution
2464 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2465 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2469 $contactSoftCreditContributionsSQL = "
2470 SELECT contribution.id
2471 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2472 ON ( contribution.id = softContribution.contribution_id )
2473 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2474 $query = "SELECT count( x.id ) count FROM ( ";
2475 $query .= $contactContributionsSQL;
2477 if ($includeSoftCredit) {
2478 $query .= " UNION ";
2479 $query .= $contactSoftCreditContributionsSQL;
2484 return CRM_Core_DAO
::singleValueQuery($query);
2488 * Repeat a transaction as part of a recurring series.
2491 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2492 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2493 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2494 * and associated entities.
2495 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2496 * which updates the various entities and sends appropriate emails.
2498 * Gaps in the above (@todo)
2499 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2500 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2501 * 3) Repeat transaction duplicates rather than calls Order.create
2502 * 4) Use of payment.create still limited - completetransaction is more common.
2503 * 5) the template transaction is tricky - historically we used the first contribution
2504 * linked to a recurring contribution. More recently that was changed to be the most recent.
2505 * Ideally it would be an actual template - not a contribution used as a template which
2506 * would give more appropriate flexibility. Note line_items have an entity so that table
2507 * could be used for the line item template - the difficulty is the custom fields...
2508 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2509 * to load the membership(s) referred to via line items in the template transactions. Any other
2510 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2511 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2512 * - membership_payment record
2513 * - civicrm_membership.contribution_recur_id
2515 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2516 * of historical processors since this has been handled 'forever' - specifically for paypal.
2517 * albeit by an even nastier mechanism than the current input override.
2518 * The count is out on how correct related entities wind up in this case.
2520 * @param CRM_Contribute_BAO_Contribution $contribution
2521 * @param array $input
2522 * @param array $contributionParams
2523 * @param int $paymentProcessorID
2526 * @throws CiviCRM_API3_Exception
2528 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2529 if (!empty($contribution->id
)) {
2532 if (empty($contribution->id
)) {
2533 // Unclear why this would only be set for repeats.
2534 if (!empty($input['amount'])) {
2535 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2538 if (!empty($contributionParams['contribution_recur_id'])) {
2539 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2540 'id' => $contributionParams['contribution_recur_id'],
2542 if (!empty($recurringContribution['campaign_id'])) {
2543 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2544 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2546 if (!empty($recurringContribution['financial_type_id'])) {
2547 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2548 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2551 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2552 $contributionParams['contribution_recur_id'],
2553 array_intersect_key($contributionParams, [
2554 'total_amount' => TRUE,
2555 'financial_type_id' => TRUE,
2558 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2560 $contributionParams['status_id'] = 'Pending';
2561 if (isset($contributionParams['financial_type_id'])) {
2562 // Give precedence to passed in type.
2563 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2566 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2568 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2569 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2571 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2572 //do not create CC or BCC emails or profile notifications.
2573 //The if is just to be safe. Not sure if we can ever arrive with this unset
2574 // but per CRM-19478 it seems it can be 'null'
2575 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2576 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2578 if (!empty($contribution->tax_amount
)) {
2579 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2582 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2583 $contribution->id
= $createContribution['id'];
2584 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2585 self
::handleMembershipIDOverride($contribution->id
, $input);
2591 * Get individual id for onbehalf contribution.
2593 * @param int $contributionId
2595 * @param int $contributorId
2599 * containing organization id and individual id
2601 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2605 if (!$contributionId) {
2609 // fetch contributor id if null
2610 if (!$contributorId) {
2611 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2612 $contributionId, 'contact_id'
2616 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2617 $activityTypeId = array_search('Contribution', $activityTypeIds);
2619 if ($activityTypeId && $contributorId) {
2621 SELECT civicrm_activity_contact.contact_id
2622 FROM civicrm_activity_contact
2623 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2624 WHERE civicrm_activity.activity_type_id = %1
2625 AND civicrm_activity.source_record_id = %2
2626 AND civicrm_activity_contact.record_type_id = %3
2629 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2630 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2633 1 => [$activityTypeId, 'Integer'],
2634 2 => [$contributionId, 'Integer'],
2635 3 => [$sourceID, 'Integer'],
2638 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2640 // for on behalf contribution source is individual and contributor is organization
2641 if ($sourceContactId && $sourceContactId != $contributorId) {
2642 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2643 // get rel type id for employee of relation
2644 foreach ($relationshipTypeIds as $id => $typeVals) {
2645 if ($typeVals['name_a_b'] == 'Employee of') {
2646 $relationshipTypeId = $id;
2651 $rel = new CRM_Contact_DAO_Relationship();
2652 $rel->relationship_type_id
= $relationshipTypeId;
2653 $rel->contact_id_a
= $sourceContactId;
2654 $rel->contact_id_b
= $contributorId;
2655 if ($rel->find(TRUE)) {
2656 $ids['individual_id'] = $rel->contact_id_a
;
2657 $ids['organization_id'] = $rel->contact_id_b
;
2668 public static function getContributionDates() {
2669 $config = CRM_Core_Config
::singleton();
2670 $currentMonth = date('m');
2671 $currentDay = date('d');
2672 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2673 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2674 (int ) $config->fiscalYearStart
['d'] > $currentDay
2677 $year = date('Y') - 1;
2682 $year = ['Y' => $year];
2683 $yearDate = $config->fiscalYearStart
;
2684 $yearDate = array_merge($year, $yearDate);
2685 $yearDate = CRM_Utils_Date
::format($yearDate);
2687 $monthDate = date('Ym') . '01';
2693 'yearDate' => $yearDate,
2694 'monthDate' => $monthDate,
2699 * Load objects relations to contribution object.
2700 * Objects are stored in the $_relatedObjects property
2701 * In the first instance we are just moving functionality from BASEIpn -
2703 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2705 * Note that the unit test for the BaseIPN class tests this function
2707 * @param array $input
2708 * Input as delivered from Payment Processor.
2710 * Ids as Loaded by Payment Processor.
2711 * @param bool $loadAll
2712 * Load all related objects - even where id not passed in? (allows API to call this).
2717 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2718 // @todo deprecate this function - the steps should be
2719 // 1) add additional functions like 'getRelatedMemberships'
2720 // 2) switch all calls that refer to ->_relatedObjects to
2721 // using the helper functions
2722 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2723 // 4) make ->_relatedObjects protected
2724 // 5) hone up the individual functions to not use rely on this having been called
2725 // 6) deprecate like mad
2727 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2728 if (empty($ids['contact']) && isset($this->contact_id
)) {
2729 $ids['contact'] = $this->contact_id
;
2732 if (empty($this->_component
)) {
2733 if (!empty($ids['event'])) {
2734 $this->_component
= 'event';
2737 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2741 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2742 // refactoring than anything else, and has unit test coverage.
2743 if (empty($this->financial_type_id
)) {
2747 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2752 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2753 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2754 $this->contribution_page_id
,
2757 if ($paymentProcessorID) {
2758 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2762 $ids['contributionType'] = $this->financial_type_id
;
2763 $ids['financialType'] = $this->financial_type_id
;
2764 if ($this->contribution_page_id
) {
2765 $ids['contributionPage'] = $this->contribution_page_id
;
2768 $this->loadRelatedEntitiesByID($ids);
2770 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2771 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2774 if (!empty($ids['pledge_payment'])) {
2775 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2776 if (empty($paymentID)) {
2779 $payment = new CRM_Pledge_BAO_PledgePayment();
2780 $payment->id
= $paymentID;
2781 if (!$payment->find(TRUE)) {
2782 throw new Exception("Could not find pledge payment record: " . $paymentID);
2784 $this->_relatedObjects
['pledge_payment'][] = $payment;
2788 // These are probably no longer accessed from anywhere
2789 // @todo remove this line, after ensuring not used.
2790 $ids = $this->loadRelatedMembershipObjects($ids);
2792 if ($this->_component
!= 'contribute') {
2793 // we are in event mode
2794 // make sure event exists and is valid
2795 $event = new CRM_Event_BAO_Event();
2796 $event->id
= $ids['event'];
2797 if ($ids['event'] &&
2800 throw new Exception("Could not find event: " . $ids['event']);
2803 $this->_relatedObjects
['event'] = &$event;
2805 $participant = new CRM_Event_BAO_Participant();
2806 $participant->id
= $ids['participant'];
2807 if ($ids['participant'] &&
2808 !$participant->find(TRUE)
2810 throw new Exception("Could not find participant: " . $ids['participant']);
2812 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2814 $this->_relatedObjects
['participant'] = &$participant;
2816 // get the payment processor id from event - this is inaccurate see CRM-16923
2817 // in future we should look at throwing an exception here rather than an dubious guess.
2818 if (!$paymentProcessorID) {
2819 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2820 if ($paymentProcessorID) {
2821 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2826 if ($paymentProcessorID) {
2827 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2828 $this->is_test ?
'test' : 'live'
2830 $ids['paymentProcessor'] = $paymentProcessorID;
2831 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2834 // Add contribution id to $ids. CRM-20401
2835 $ids['contribution'] = $this->id
;
2840 * Create array of message information - ie. return html version, txt version, to field
2842 * @param array $input
2843 * Incoming information.
2844 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2845 * just check presence of recur object but maintaining legacy approach
2848 * IDs of related objects.
2849 * @param array $values
2850 * Any values that may have already been compiled by calling process.
2851 * This is augmented by values 'gathered' by gatherMessageValues
2852 * @param bool $returnMessageText
2853 * Distinguishes between whether to send message or return.
2854 * message text. We are working towards this function ALWAYS returning message text & calling
2855 * function doing emails / pdfs with it
2861 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2862 $this->loadRelatedObjects($input, $ids);
2864 if (empty($this->_component
)) {
2865 $this->_component
= CRM_Utils_Array
::value('component', $input);
2868 //not really sure what params might be passed in but lets merge em into values
2869 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2870 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2871 if (!empty($input['receipt_date'])) {
2872 $values['receipt_date'] = $input['receipt_date'];
2875 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2876 //what does recur 'mean here - to do with payment processor return functionality but
2877 // what is the importance
2878 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2879 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2881 $entityID = $entity = NULL;
2882 if (isset($ids['contribution'])) {
2883 $entity = 'contribution';
2884 $entityID = $ids['contribution'];
2886 if (!empty($ids['membership'])) {
2887 //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
2888 // 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
2889 // line having loaded an array
2890 $ids['membership'] = (array) $ids['membership'];
2891 $entity = 'membership';
2892 $entityID = $ids['membership'][0];
2895 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2896 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2897 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2899 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2900 //direct mode showing billing block, so use directIPN for temporary
2901 $template->assign('contributeMode', 'directIPN');
2904 // todo remove strtolower - check consistency
2905 if (strtolower($this->_component
) == 'event') {
2906 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2907 $values['event'] = [];
2909 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2911 //get location details
2913 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2914 'entity_table' => 'civicrm_event',
2916 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2919 'entity_table' => 'civicrm_event',
2920 'entity_id' => $ids['event'],
2921 'module' => 'CiviEvent',
2924 list($custom_pre_id,
2926 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2928 $values['custom_pre_id'] = $custom_pre_id;
2929 $values['custom_post_id'] = $custom_post_ids;
2930 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2931 //and cases involving status updation through ipn
2932 // whatever that means!
2933 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2934 // perhaps we should throw an e-notice if amount is set & force total_amount?
2935 if (!empty($input['amount'])) {
2936 $values['totalAmount'] = $input['amount'];
2938 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2939 if ($values['event']['is_email_confirm']) {
2940 $values['is_email_receipt'] = 1;
2943 if (!empty($ids['contribution'])) {
2944 $values['contributionId'] = $ids['contribution'];
2947 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2948 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2952 $values['contribution_id'] = $this->id
;
2953 if (!empty($ids['related_contact'])) {
2954 $values['related_contact'] = $ids['related_contact'];
2955 if (isset($ids['onbehalf_dupe_alert'])) {
2956 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2959 'contact_id' => $ids['contact'],
2960 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2961 'Home', 'id', 'name'
2964 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2965 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2968 if ($this->is_test
) {
2971 if (!empty($this->_relatedObjects
['membership'])) {
2972 foreach ($this->_relatedObjects
['membership'] as $membership) {
2973 if ($membership->id
) {
2974 $values['membership_id'] = $membership->id
;
2975 $values['isMembership'] = TRUE;
2976 $values['membership_assign'] = TRUE;
2978 // need to set the membership values here
2979 $template->assign('membership_name',
2980 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2982 $template->assign('mem_start_date', $membership->start_date
);
2983 $template->assign('mem_join_date', $membership->join_date
);
2984 $template->assign('mem_end_date', $membership->end_date
);
2985 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2986 $template->assign('mem_status', $membership_status);
2987 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2988 $values['is_pay_later'] = 1;
2990 // Pass amount to floatval as string '0.00' is considered a
2991 // valid amount and includes Fee section in the mail.
2992 if (isset($values['amount'])) {
2993 $values['amount'] = floatval($values['amount']);
2996 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2997 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2998 $template->assign('cancelSubscriptionUrl', $url);
2999 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3000 $template->assign('updateSubscriptionBillingUrl', $url);
3001 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3002 $template->assign('updateSubscriptionUrl', $url);
3005 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3008 // otherwise if its about sending emails, continue sending without return, as we
3009 // don't want to exit the loop.
3014 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3020 * Gather values for contribution mail - this function has been created
3021 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3022 * Values related to the contribution in question are gathered
3024 * @param array $input
3025 * Input into function (probably from payment processor).
3026 * @param array $values
3028 * The set of ids related to the input.
3031 * @throws \CRM_Core_Exception
3033 public function _gatherMessageValues($input, &$values, $ids = []) {
3034 // set display address of contributor
3035 $values['billingName'] = '';
3036 if ($this->address_id
) {
3037 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3038 $addressDetails = reset($addressDetails);
3039 $values['billingName'] = $addressDetails['name'] ??
'';
3041 // Else we assign the billing address of the contribution contact.
3043 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3044 $addressDetails = reset($addressDetails);
3046 $values['address'] = $addressDetails['display'] ??
'';
3048 if ($this->_component
=== 'contribute') {
3049 //get soft contributions
3050 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3051 if (!empty($softContributions)) {
3052 $values['softContributions'] = $softContributions['soft_credit'];
3054 if (isset($this->contribution_page_id
)) {
3055 // This is a call we want to use less, in favour of loading related objects.
3056 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3057 if ($this->contribution_page_id
) {
3058 // This is precautionary as there are some legacy flows, but it should really be
3060 if (!isset($this->_relatedObjects
['contributionPage'])) {
3061 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3063 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3066 // no contribution page -probably back office
3068 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3069 $values['title'] = 'Contribution';
3071 // set lineItem for contribution
3073 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3074 if (!empty($lineItems)) {
3075 $firstLineItem = reset($lineItems);
3077 if (!empty($firstLineItem['price_set_id'])) {
3078 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3079 'id' => $firstLineItem['price_set_id'],
3080 'return' => 'is_quick_config, id',
3082 $values['priceSetID'] = $priceSet['id'];
3084 foreach ($lineItems as &$eachItem) {
3085 if (isset($this->_relatedObjects
['membership'])
3086 && is_array($this->_relatedObjects
['membership'])
3087 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3088 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
3089 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
3090 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
3092 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3093 // However, that does create upgrade pain so would be better to be phased in.
3094 $values['useForMember'] = empty($priceSet['is_quick_config']);
3096 $values['lineItem'][0] = $lineItems;
3100 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3104 // if this is onbehalf of contribution then set related contact
3105 if (!empty($relatedContact['individual_id'])) {
3106 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3110 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3113 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3116 foreach ($groupTree as $key => $group) {
3117 if ($key === 'info') {
3121 foreach ($group['fields'] as $k => $customField) {
3122 $groupLabel = $group['title'];
3123 if (!empty($customField['customValue'])) {
3124 foreach ($customField['customValue'] as $customFieldValues) {
3125 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3130 $values['customGroup'] = $customGroup;
3132 $values['is_pay_later'] = $this->is_pay_later
;
3138 * Assign message variables to template but try to break the habit.
3140 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3141 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3142 * multiple recurring payments for processors like IATS that use tokens.
3144 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3145 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3146 * Note we send directly from this function in some cases because it is only partly refactored.
3148 * Don't call this function directly as the signature will change.
3152 * @param bool $returnMessageText
3156 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3157 // @todo - this should have a better separation of concerns - ie.
3158 // gatherMessageValues should build an array of values to be assigned to the template
3159 // and this function should assign them (assigning null if not set).
3160 // the way the pcpParams & honor Params section works is a baby-step towards this.
3161 $template = CRM_Core_Smarty
::singleton();
3162 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3163 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3164 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3165 $template->assign('billingName', $values['billingName']);
3167 // For some unit tests contribution cannot contain paymentProcessor information
3168 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3169 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3171 //assign honor information to receipt message
3172 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3175 'soft_credit_type' => NULL,
3176 'honor_block_is_active' => NULL,
3178 if (isset($softRecord['soft_credit'])) {
3179 //if id of contribution page is present
3180 if (!empty($values['id'])) {
3181 $values['honor'] = [
3182 'honor_profile_values' => [],
3183 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3184 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3187 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3188 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3191 //offline contribution
3192 $softCreditTypes = $softCredits = [];
3193 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3194 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3195 $softCredits[$key] = [
3196 'Name' => $softCredit['contact_name'],
3197 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3200 $template->assign('softCreditTypes', $softCreditTypes);
3201 $template->assign('softCredits', $softCredits);
3205 $dao = new CRM_Contribute_DAO_ContributionProduct();
3206 $dao->contribution_id
= $this->id
;
3207 if ($dao->find(TRUE)) {
3208 $premiumId = $dao->product_id
;
3209 $template->assign('option', $dao->product_option
);
3211 $productDAO = new CRM_Contribute_DAO_Product();
3212 $productDAO->id
= $premiumId;
3213 $productDAO->find(TRUE);
3214 $template->assign('selectPremium', TRUE);
3215 $template->assign('product_name', $productDAO->name
);
3216 $template->assign('price', $productDAO->price
);
3217 $template->assign('sku', $productDAO->sku
);
3219 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3220 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3221 if (!$values['amount'] && isset($this->total_amount
)) {
3222 $values['amount'] = $this->total_amount
;
3227 'pcp_display_in_roll' => NULL,
3228 'pcp_roll_nickname' => NULL,
3229 'pcp_personal_note' => NULL,
3233 if (strtolower($this->_component
) == 'contribute') {
3235 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3236 $softDAO->contribution_id
= $this->id
;
3237 if ($softDAO->find(TRUE)) {
3238 $pcpParams['pcpBlock'] = TRUE;
3239 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3240 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3241 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3243 //assign the pcp page title for email subject
3244 $pcpDAO = new CRM_PCP_DAO_PCP();
3245 $pcpDAO->id
= $softDAO->pcp_id
;
3246 if ($pcpDAO->find(TRUE)) {
3247 $pcpParams['title'] = $pcpDAO->title
;
3251 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3252 $template->assign($templateKey, $templateValue);
3255 if ($this->financial_type_id
) {
3256 $values['financial_type_id'] = $this->financial_type_id
;
3259 $template->assign('trxn_id', $this->trxn_id
);
3260 $template->assign('receive_date',
3261 CRM_Utils_Date
::processDate($this->receive_date
)
3263 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3264 $template->assign('action', $this->is_test ?
1024 : 1);
3265 $template->assign('receipt_text',
3266 CRM_Utils_Array
::value('receipt_text',
3270 $template->assign('is_monetary', 1);
3271 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3272 $template->assign('currency', $this->currency
);
3273 $template->assign('address', CRM_Utils_Address
::format($input));
3274 if (!empty($values['customGroup'])) {
3275 $template->assign('customGroup', $values['customGroup']);
3277 if (!empty($values['softContributions'])) {
3278 $template->assign('softContributions', $values['softContributions']);
3280 if ($this->_component
== 'event') {
3281 $template->assign('title', $values['event']['title']);
3282 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3284 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3285 $viewRoles[] = $participantRoles[$v];
3287 $values['event']['participant_role'] = implode(', ', $viewRoles);
3288 $template->assign('event', $values['event']);
3289 $template->assign('participant', $values['participant']);
3290 $template->assign('location', $values['location']);
3291 $template->assign('customPre', $values['custom_pre_id']);
3292 $template->assign('customPost', $values['custom_post_id']);
3295 if ($this->_relatedObjects
['participant']->is_test
) {
3299 $values['params'] = [];
3300 //to get email of primary participant.
3301 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3302 $primaryAmount[] = [
3303 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3304 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3306 //build an array of cId/pId of participants
3307 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3308 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3309 //send receipt to additional participant if exists
3310 if (count($additionalIDs)) {
3311 $template->assign('isPrimary', 0);
3312 $template->assign('customProfile', NULL);
3313 //set additionalParticipant true
3314 $values['params']['additionalParticipant'] = TRUE;
3315 foreach ($additionalIDs as $pId => $cId) {
3317 //to change the status pending to completed
3318 $additional = new CRM_Event_DAO_Participant();
3319 $additional->id
= $pId;
3320 $additional->contact_id
= $cId;
3321 $additional->find(TRUE);
3322 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3323 $additional->status_id
= 1;
3324 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3325 //if additional participant dont have email
3327 if (!$additionalParticipantInfo) {
3328 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3331 'label' => $additional->fee_level
,
3332 'amount' => $additional->fee_amount
,
3334 $primaryAmount[] = [
3335 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3336 'amount' => $additional->fee_amount
,
3338 $additional->save();
3339 $template->assign('amount', $amount);
3340 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3344 //build an array of custom profile and assigning it to template
3345 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3347 if (count($customProfile)) {
3348 $template->assign('customProfile', $customProfile);
3351 // for primary contact
3352 $values['params']['additionalParticipant'] = FALSE;
3353 $template->assign('isPrimary', 1);
3354 $template->assign('amount', $primaryAmount);
3355 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3356 if ($this->payment_instrument_id
) {
3357 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3358 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3360 // carry paylater, since we did not created billing,
3361 // so need to pull email from primary location, CRM-4395
3362 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3368 * Check whether payment processor supports
3369 * cancellation of contribution subscription
3371 * @param int $contributionId
3374 * @param bool $isNotCancelled
3378 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3379 $cacheKeyString = "$contributionId";
3380 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3382 static $supportsCancel = [];
3384 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3385 $supportsCancel[$cacheKeyString] = FALSE;
3386 $isCancelled = FALSE;
3388 if ($isNotCancelled) {
3389 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3392 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3393 if (!empty($paymentObject)) {
3394 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3397 return $supportsCancel[$cacheKeyString];
3401 * Check whether subscription is already cancelled.
3403 * @param int $contributionId
3407 * contribution status
3409 public static function isSubscriptionCancelled($contributionId) {
3411 SELECT cr.contribution_status_id
3412 FROM civicrm_contribution_recur cr
3413 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3414 WHERE con.id = %1 LIMIT 1";
3415 $params = [1 => [$contributionId, 'Integer']];
3416 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3417 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3418 if ($status == 'Cancelled') {
3425 * Create all financial accounts entry.
3427 * @param array $params
3428 * Contribution object, line item array and params for trxn.
3431 * @param array $financialTrxnValues
3433 * @return null|\CRM_Core_BAO_FinancialTrxn
3435 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3436 $skipRecords = $update = $return = $isRelatedId = FALSE;
3438 $additionalParticipantId = [];
3439 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3440 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3442 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3443 $entityId = $params['participant_id'];
3444 $entityTable = 'civicrm_participant';
3445 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3447 elseif (!empty($params['membership_id'])) {
3448 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3449 // are created off one contribution should be handled elsewhere
3450 $entityId = $params['membership_id'];
3451 $entityTable = 'civicrm_membership';
3454 $entityId = $params['contribution']->id
;
3455 $entityTable = 'civicrm_contribution';
3458 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3459 $isRelatedId = TRUE;
3462 $entityID[] = $entityId;
3463 if (!empty($additionalParticipantId)) {
3464 $entityID +
= $additionalParticipantId;
3466 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3467 if (empty($params['prevContribution'])) {
3474 $statusId = $params['contribution']->contribution_status_id
;
3475 // CRM-13964 partial payment
3476 if ($contributionStatus == 'Partially paid'
3477 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3479 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3480 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3482 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3483 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3484 $params['total_amount'] = $partialAmtPay;
3486 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3487 if (empty($balanceTrxnInfo['trxn_id'])) {
3488 // create new balance transaction record
3489 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3491 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3492 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3493 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3494 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3495 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3496 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3497 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3498 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3499 $balanceTrxnParams['status_id'] = $statusId;
3500 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3501 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3502 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3503 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3504 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3505 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3507 $balanceTrxnParams['is_payment'] = 1;
3509 if (!empty($params['payment_processor'])) {
3510 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3512 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3516 // build line item array if its not set in $params
3517 if (empty($params['line_item']) ||
$additionalParticipantId) {
3518 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3521 if ($contributionStatus != 'Failed' &&
3522 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3524 $skipRecords = TRUE;
3529 if (in_array($contributionStatus, $pendingStatus)) {
3530 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3531 $params['financial_type_id'],
3532 'Accounts Receivable Account is'
3535 elseif (!empty($params['payment_processor'])) {
3536 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3537 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3538 'id' => $params['payment_processor'],
3539 'return' => 'payment_instrument_id',
3542 elseif (!empty($params['payment_instrument_id'])) {
3543 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3546 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3547 $queryParams = [1 => [$relationTypeId, 'Integer']];
3548 $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);
3551 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3552 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3553 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3555 //build financial transaction params
3557 'contribution_id' => $params['contribution']->id
,
3558 'to_financial_account_id' => $params['to_financial_account_id'],
3559 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3560 'total_amount' => $totalAmount,
3561 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3562 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3563 'currency' => $params['contribution']->currency
,
3564 'trxn_id' => $params['contribution']->trxn_id
,
3565 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3566 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3567 // this should really default to completed (after discussion).
3568 'status_id' => $statusId,
3569 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3570 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3571 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3572 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3574 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3575 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3576 if (isset($params['refund_trxn_id'])) {
3577 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3578 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3581 //CRM-16259, set is_payment flag for non pending status
3582 if (!in_array($contributionStatus, $pendingStatus)) {
3583 $trxnParams['is_payment'] = 1;
3585 if (!empty($params['payment_processor'])) {
3586 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3589 if (isset($fromFinancialAccountId)) {
3590 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3593 // consider external values passed for recording transaction entry
3594 if (!empty($financialTrxnValues)) {
3595 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3597 if (empty($trxnParams['payment_processor_id'])) {
3598 unset($trxnParams['payment_processor_id']);
3601 $params['trxnParams'] = $trxnParams;
3603 if (!empty($params['prevContribution'])) {
3605 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3606 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3607 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3608 if (!isset($params['trxnParams']['trxn_id'])) {
3609 // Actually I have no idea why we are overwriting any values from the previous contribution.
3610 // (filling makes sense to me). However, only protecting this value as I really really know we
3611 // don't want this one overwritten.
3613 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3615 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3617 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3618 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3619 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3621 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3622 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3625 //if financial type is changed
3626 if (!empty($params['financial_type_id']) &&
3627 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3629 $accountRelationship = 'Income Account is';
3630 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3631 $accountRelationship = 'Deferred Revenue Account is';
3633 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3634 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3635 if ($oldFinancialAccount != $newFinancialAccount) {
3636 $params['total_amount'] = 0;
3637 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3638 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3639 $params['prevContribution']->financial_type_id
, $accountRelationship);
3642 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3643 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3644 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3647 self
::updateFinancialAccounts($params, 'changeFinancialType');
3648 $params['skipLineItem'] = FALSE;
3649 foreach ($params['line_item'] as &$lineItems) {
3650 foreach ($lineItems as &$line) {
3651 $line['financial_type_id'] = $params['financial_type_id'];
3654 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3655 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3656 $params['financial_account_id'] = $newFinancialAccount;
3657 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3658 self
::updateFinancialAccounts($params);
3659 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3660 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3662 $params['deferred_financial_account_id'] = $newFinancialAccount;
3666 //Update contribution status
3667 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3668 if (!isset($params['refund_trxn_id'])) {
3669 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3670 // gets preference over another so I am only 'protecting' a very specific tested flow
3671 // and letting natural justice take care of the rest.
3672 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3674 if (!empty($params['contribution_status_id']) &&
3675 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3677 //Update Financial Records
3678 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3679 if ($callUpdateFinancialAccounts) {
3680 self
::updateFinancialAccounts($params, 'changedStatus');
3681 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3686 // change Payment Instrument for a Completed contribution
3687 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3688 // instrument is null and now new payment instrument is added along with the payment
3689 if (!$params['contribution']->payment_instrument_id
) {
3690 $params['contribution']->find(TRUE);
3692 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3693 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3695 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3696 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3699 //if Change contribution amount
3700 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3701 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3702 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3703 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3704 if (isset($totalAmount) &&
3705 $totalAmount != $params['prevContribution']->total_amount
3707 //Update Financial Records
3708 $params['trxnParams']['from_financial_account_id'] = NULL;
3709 self
::updateFinancialAccounts($params, 'changedAmount');
3710 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3715 // Looks like we might have a data correction update.
3716 // This would be a case where a transaction id has been entered but it is incorrect &
3717 // the person goes back in & fixes it, as opposed to a new transaction.
3718 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3719 // the data fix scenario.
3721 if (isset($params['refund_trxn_id'])) {
3722 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3723 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3724 civicrm_api3('FinancialTrxn', 'create', [
3725 'id' => $refundIDs['financialTrxnId'],
3726 'trxn_id' => $params['refund_trxn_id'],
3730 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3731 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3732 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3737 // records finanical trxn and entity financial trxn
3738 // also make it available as return value
3739 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3740 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3741 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3742 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3743 $params['entity_id'] = $financialTxn->id
;
3744 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3745 self
::$_trxnIDs[] = $financialTxn->id
;
3749 // record line items and financial items
3750 if (empty($params['skipLineItem'])) {
3751 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3754 // create batch entry if batch_id is passed and
3755 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3756 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3758 'batch_id' => $params['batch_id'],
3759 'entity_table' => 'civicrm_financial_trxn',
3760 'entity_id' => $financialTxn->id
,
3762 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3765 // when a fee is charged
3766 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3767 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3770 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3771 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3773 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3774 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3775 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3777 unset($params['line_item']);
3778 self
::$_trxnIDs = NULL;
3783 * Update all financial accounts entry.
3785 * @param array $params
3786 * Contribution object, line item array and params for trxn.
3788 * @param string $context
3791 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3792 * adds unpredictability.
3795 public static function updateFinancialAccounts(&$params, $context = NULL) {
3797 $inputParams = $params;
3798 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3800 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3801 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3802 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3805 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3806 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3807 $params['entity_id'] = $trxn->id
;
3809 $itemParams['entity_table'] = 'civicrm_line_item';
3810 $trxnIds['id'] = $params['entity_id'];
3811 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3812 foreach ($params['line_item'] as $fieldId => $fields) {
3813 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3818 * Is this contribution status a reversal.
3820 * If so we would expect to record a negative value in the financial_trxn table.
3822 * @param int $status_id
3826 public static function isContributionStatusNegative($status_id) {
3827 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3828 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3832 * Check status validation on update of a contribution.
3834 * @param array $values
3835 * Previous form values before submit.
3837 * @param array $fields
3838 * The input form values.
3840 * @param array $errors
3845 public static function checkStatusValidation($values, &$fields, &$errors) {
3846 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3847 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3848 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3852 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3854 'Cancelled' => ['Completed', 'Refunded'],
3855 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3856 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3857 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3858 'Refunded' => ['Cancelled', 'Completed'],
3859 'Partially paid' => ['Completed'],
3860 'Pending refund' => ['Completed', 'Refunded'],
3863 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3864 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3866 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3867 1 => $contributionStatuses[$values['contribution_status_id']],
3868 2 => $contributionStatuses[$fields['contribution_status_id']],
3874 * Delete contribution of contact.
3878 * @param int $contactId
3882 public static function deleteContactContribution($contactId) {
3883 $contribution = new CRM_Contribute_DAO_Contribution();
3884 $contribution->contact_id
= $contactId;
3885 $contribution->find();
3886 while ($contribution->fetch()) {
3887 self
::deleteContribution($contribution->id
);
3892 * Get options for a given contribution field.
3894 * @param string $fieldName
3895 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3896 * @param array $props whatever is known about this dao object.
3898 * @return array|bool
3899 * @see CRM_Core_DAO::buildOptions
3902 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3903 $className = __CLASS__
;
3905 if (isset($props['orderColumn'])) {
3906 $params['orderColumn'] = $props['orderColumn'];
3908 switch ($fieldName) {
3909 // This field is not part of this object but the api supports it
3910 case 'payment_processor':
3911 $className = 'CRM_Contribute_BAO_ContributionPage';
3912 // Filter results by contribution page
3913 if (!empty($props['contribution_page_id'])) {
3914 $page = civicrm_api('contribution_page', 'getsingle', [
3916 'id' => ($props['contribution_page_id']),
3918 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3919 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3923 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3924 case 'honor_type_id':
3925 $className = 'CRM_Contribute_BAO_ContributionSoft';
3926 $fieldName = 'soft_credit_type_id';
3927 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3930 case 'contribution_status_id':
3931 if ($context !== 'validate') {
3932 $params['condition'] = "v.name <> 'Template'";
3935 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3939 * Validate financial type.
3943 * @param int $financialTypeId
3944 * Financial Type id.
3946 * @param string $relationName
3948 * @return array|bool
3950 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3951 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3953 if (!$financialAccount) {
3954 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3960 * @param int $targetCid
3961 * @param $activityType
3962 * @param string $title
3963 * @param int $contributionId
3964 * @param string $totalAmount
3965 * @param string $currency
3966 * @param string $trxn_date
3968 * @throws \CRM_Core_Exception
3969 * @throws \CiviCRM_API3_Exception
3971 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3972 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3973 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3974 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3975 // source record id would be the contribution id
3976 $srcRecId = $contributionId;
3980 'source_contact_id' => $targetCid,
3981 'source_record_id' => $srcRecId,
3982 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3983 'subject' => $subject,
3984 'activity_date_time' => $date,
3985 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3986 'skipRecentView' => TRUE,
3989 // create activity with target contacts
3990 $session = CRM_Core_Session
::singleton();
3991 $id = $session->get('userID');
3993 $activityParams['source_contact_id'] = $id;
3994 $activityParams['target_contact_id'][] = $targetCid;
3996 civicrm_api3('Activity', 'create', $activityParams);
4000 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4004 * @param bool $getTrxnInfo
4005 * @param bool $usingLineTotal
4009 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4010 // @todo deprecate passing in component - always call with contribution.
4011 if ($component == 'event') {
4012 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4014 if (!$contributionId) {
4015 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4016 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4017 $id = $primaryParticipantId;
4019 if (!$contributionId) {
4024 elseif ($component == 'membership') {
4025 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4028 $contributionId = $id;
4031 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4032 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4034 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4035 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4037 if (empty($total['total_amount']) ||
$usingLineTotal) {
4038 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4041 $baseTrxnId = $total['trxn_id'];
4042 $total = $total['total_amount'];
4045 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4047 $contribution = civicrm_api3('Contribution', 'getsingle', [
4048 'id' => $contributionId,
4052 'contribution_status_id',
4053 'financial_type_id',
4057 $info['payLater'] = $contribution['is_pay_later'];
4058 $info['contribution_status'] = $contribution['contribution_status'];
4059 $info['currency'] = $contribution['currency'];
4061 $financialTypeId = $contribution['financial_type_id'];
4062 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4064 $info['total'] = $total;
4065 $info['paid'] = $total - $paymentBalance;
4066 $info['balance'] = $paymentBalance;
4068 $info['component'] = $component;
4070 if ($getTrxnInfo && $baseTrxnId) {
4071 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4073 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4075 ft.payment_instrument_id,
4076 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4078 FROM civicrm_contribution con
4079 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4080 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4081 AND ft.to_financial_account_id != %2
4082 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4083 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4084 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4086 WHERE con.id = %1 AND ft.is_payment = 1
4089 1 => [$contributionId, 'Integer'],
4090 2 => [$feeFinancialAccount, 'Integer'],
4092 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4093 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
4095 while ($resultDAO->fetch()) {
4096 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4097 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4098 if ($resultDAO->card_type_id
) {
4099 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4100 $pantruncation = '';
4101 if ($resultDAO->pan_truncation
) {
4102 $pantruncation = ": {$resultDAO->pan_truncation}";
4104 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4107 // show payment edit link only for payments done via backoffice form
4108 $paymentEditLink = '';
4109 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4111 CRM_Core_Action
::UPDATE
=> [
4112 'name' => "<i class='crm-i fa-pencil'></i>",
4113 'url' => 'civicrm/payment/edit',
4114 'class' => 'medium-popup',
4115 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4116 'title' => ts('Edit Payment'),
4119 $paymentEditLink = CRM_Core_Action
::formLink(
4121 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4123 'id' => $resultDAO->id
,
4124 'contribution_id' => $contributionId,
4130 'id' => $resultDAO->id
,
4131 'total_amount' => $resultDAO->total_amount
,
4132 'financial_type' => $resultDAO->financial_account
,
4133 'payment_instrument' => $paidByLabel,
4134 'receive_date' => $resultDAO->trxn_date
,
4135 'trxn_id' => $resultDAO->trxn_id
,
4136 'status' => $statuses[$resultDAO->status_id
],
4137 'currency' => $resultDAO->currency
,
4138 'action' => $paymentEditLink,
4140 if ($paidByName == 'Check') {
4141 $val['check_number'] = $resultDAO->check_number
;
4145 $info['transaction'] = $rows;
4148 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4153 * Get the outstanding balance on a contribution.
4155 * @param int $contributionId
4156 * @param float $contributionTotal
4157 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4161 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4162 if ($contributionTotal === NULL) {
4163 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4166 return (float) CRM_Utils_Money
::subtractCurrencies(
4168 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4169 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4174 * Get the tax amount (misnamed function).
4176 * @param array $params
4177 * @param bool $isLineItem
4181 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4182 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4184 // This function should be only called after standardisation (removal of
4185 // thousand separator & using a decimal point for cents separator.
4186 // However, we don't know if that is always true :-(
4187 // There is a deprecation notice tho :-)
4188 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4189 // Update contribution.
4190 if (!empty($params['id'])) {
4191 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4192 // there are no tax implications - early return.
4193 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4196 if (empty($params['prevContribution'])) {
4197 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4200 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4201 if (!isset($params[$field])) {
4202 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4203 // Tax amount gets added back on later....
4204 $params['total_amount'] = $params['prevContribution']->total_amount
-
4205 $params['prevContribution']->tax_amount
;
4208 $params[$field] = $params['prevContribution']->$field;
4209 if ($params[$field] != $params['prevContribution']->$field) {
4215 self
::calculateMissingAmountParams($params, $params['id']);
4216 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4217 // Assign tax Amount on update of contribution
4218 if (!empty($params['prevContribution']->tax_amount
)) {
4219 $params['tax_amount'] = 'null';
4220 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4221 foreach ($params['line_item'] as $setID => $priceField) {
4222 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4223 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4230 // New Contribution and update of contribution with tax rate financial type
4231 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4232 empty($params['skipLineItem']) && !$isLineItem
4234 $taxRateParams = $taxRates[$params['financial_type_id']];
4235 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4236 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4238 // Get Line Item on update of contribution
4239 if (isset($params['id'])) {
4240 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4243 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4245 foreach ($params['line_item'] as $setID => $priceField) {
4246 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4247 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4250 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4252 elseif (isset($params['api.line_item.create'])) {
4253 // Update total amount of contribution using lineItem
4254 $taxAmountArray = [];
4255 foreach ($params['api.line_item.create'] as $key => $value) {
4256 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4257 $taxRate = $taxRates[$value['financial_type_id']];
4258 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4259 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4262 $params['tax_amount'] = array_sum($taxAmountArray);
4263 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4266 // update line item of contrbution
4267 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4268 $taxRate = $taxRates[$params['financial_type_id']];
4269 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4270 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4277 * Check financial type validation on update of a contribution.
4279 * @param int $financialTypeId
4280 * Value of latest Financial Type.
4282 * @param int $contributionId
4285 * @param array $errors
4290 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4291 if (!empty($financialTypeId)) {
4292 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4293 if ($oldFinancialTypeId == $financialTypeId) {
4297 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4299 '1' => [$contributionId, 'Integer'],
4301 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4302 if ($result->N
> 1) {
4303 $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.');
4308 * Update related pledge payment payments.
4310 * This function has been refactored out of the back office contribution form and may
4311 * still overlap with other functions.
4313 * @param string $action
4314 * @param int $pledgePaymentID
4315 * @param int $contributionID
4316 * @param bool $adjustTotalAmount
4317 * @param float $total_amount
4318 * @param float $original_total_amount
4319 * @param int $contribution_status_id
4320 * @param int $original_contribution_status_id
4322 public static function updateRelatedPledge(
4328 $original_total_amount,
4329 $contribution_status_id,
4330 $original_contribution_status_id
4332 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4336 if ($pledgePaymentID) {
4337 //store contribution id in payment record.
4338 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4341 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4348 if (!$pledgePaymentID) {
4351 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4357 $updatePledgePaymentStatus = FALSE;
4359 // If either the status or the amount has changed we update the pledge status.
4360 if ($action & CRM_Core_Action
::ADD
) {
4361 $updatePledgePaymentStatus = TRUE;
4363 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4364 ($original_total_amount != $total_amount))
4366 $updatePledgePaymentStatus = TRUE;
4369 if ($updatePledgePaymentStatus) {
4370 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4372 $contribution_status_id,
4381 * Compute the stats values
4383 * @param string $stat either 'mode' or 'median'
4384 * @param string $sql
4385 * @param string $alias of civicrm_contribution
4387 * @return array|null
4391 public static function computeStats($stat, $sql, $alias = NULL) {
4392 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4397 * Is there only one line item attached to the contribution.
4403 * @throws \CiviCRM_API3_Exception
4405 public static function isSingleLineItem($id) {
4406 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4407 return ($lineItemCount == 1);
4411 * Complete an order.
4413 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4415 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4417 * Moving it out of the BaseIPN class is just the first step.
4419 * @param array $input
4421 * @param array $objects
4422 * @param CRM_Core_Transaction $transaction
4423 * @param CRM_Contribute_BAO_Contribution $contribution
4424 * @param bool $isPostPaymentCreate
4425 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4426 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4427 * transitioning related elements).
4430 * @throws \CRM_Core_Exception
4431 * @throws \CiviCRM_API3_Exception
4433 public static function completeOrder($input, &$ids, $objects, $transaction, $contribution, $isPostPaymentCreate = FALSE) {
4434 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4435 // The previous details are used when calculating line items so keep it before any code that 'does something'
4436 if (!empty($contribution->id
)) {
4437 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4439 $inputContributionWhiteList = [
4444 'payment_instrument_id',
4449 'contribution_status_id',
4453 if (self
::isSingleLineItem($primaryContributionID)) {
4454 $inputContributionWhiteList[] = 'financial_type_id';
4457 $participant = CRM_Utils_Array
::value('participant', $objects);
4458 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4459 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4460 $event = CRM_Utils_Array
::value('event', $objects);
4462 $paymentProcessorId = '';
4463 if (isset($objects['paymentProcessor'])) {
4464 if (is_array($objects['paymentProcessor'])) {
4465 $paymentProcessorId = $objects['paymentProcessor']['id'];
4468 $paymentProcessorId = $objects['paymentProcessor']->id
;
4472 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4474 $contributionParams = array_merge([
4475 'contribution_status_id' => $completedContributionStatusID,
4476 'source' => self
::getRecurringContributionDescription($contribution, $event),
4477 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4480 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4481 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4482 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4485 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4487 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4488 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4489 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4490 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4493 if ($recurringContributionID) {
4494 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4496 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4498 if (empty($contributionParams['receive_date']) && $changeDate) {
4499 $contributionParams['receive_date'] = $changeDate;
4502 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4503 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4506 if (isset($input['is_email_receipt'])) {
4507 $values['is_email_receipt'] = $input['is_email_receipt'];
4510 if ($input['component'] == 'contribute') {
4511 if ($contribution->contribution_page_id
) {
4512 // Figure out what we gain from this.
4513 // Note that we may have overwritten the is_email_receipt input, fix that below.
4514 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4516 elseif ($recurContrib && $recurringContributionID) {
4517 $values['amount'] = $recurContrib->amount
;
4518 $values['financial_type_id'] = $objects['contributionType']->id
;
4519 $values['title'] = $source = ts('Offline Recurring Contribution');
4522 if (isset($input['is_email_receipt'])) {
4523 // CRM-19601 - we may have overwritten this above.
4524 $values['is_email_receipt'] = $input['is_email_receipt'];
4526 elseif ($recurContrib && $recurringContributionID) {
4527 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4528 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4529 // 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
4530 // Instance that had the table added via an upgrade in 4.1
4531 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4532 // https://lab.civicrm.org/dev/core/issues/1245
4533 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4536 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4537 self
::updateMembershipBasedOnCompletionOfContribution(
4539 $primaryContributionID,
4545 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4546 if ($event->is_email_confirm
) {
4547 // @todo this should be set by the function that sends the mail after sending.
4548 $contributionParams['receipt_date'] = $changeDate;
4550 $participantParams['id'] = $participant->id
;
4551 $participantParams['status_id'] = 'Registered';
4552 civicrm_api3('Participant', 'create', $participantParams);
4556 $contributionParams['id'] = $contribution->id
;
4557 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4559 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4560 // unsetting it here does NOT cause any other contribution test to fail!
4561 unset($contributionParams['financial_type_id']);
4562 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4564 // Add new soft credit against current $contribution.
4565 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4566 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4569 if (empty($contribution->_relatedObjects
['participant']) && !empty($contribution->_relatedObjects
['membership'])) {
4570 // @fixme Can we remove this if altogether? - we removed the participant if / else and left relatedObjects['participant'] to ensure behaviour didn't change but it is probably not required.
4571 // @todo - use getRelatedMemberships instead
4572 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4573 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4574 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4577 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4578 $transaction->commit();
4580 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4581 $contributionParams['contribution_status_id'], $input['amount']);
4583 // create an activity record
4584 if ($input['component'] == 'contribute') {
4586 $targetContactID = NULL;
4587 if (!empty($ids['related_contact'])) {
4588 $targetContactID = $contribution->contact_id
;
4589 $contribution->contact_id
= $ids['related_contact'];
4591 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4594 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4595 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4596 if (!array_key_exists('is_email_receipt', $values) ||
4597 $values['is_email_receipt'] == 1
4599 civicrm_api3('Contribution', 'sendconfirmation', [
4600 'id' => $contribution->id
,
4601 'payment_processor_id' => $paymentProcessorId,
4603 CRM_Core_Error
::debug_log_message("Receipt sent");
4606 CRM_Core_Error
::debug_log_message("Success: Database updated");
4607 return $contributionResult;
4611 * Send receipt from contribution.
4613 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4615 * Note that the compose message part has been moved to contribution
4616 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4618 * @param array $input
4619 * Incoming data from Payment processor.
4621 * Related object IDs.
4622 * @param int $contributionID
4623 * @param array $values
4624 * Values related to objects that have already been loaded.
4625 * @param bool $returnMessageText
4626 * Should text be returned instead of sent. This.
4627 * is because the function is also used to generate pdfs
4630 * @throws \CRM_Core_Exception
4631 * @throws \CiviCRM_API3_Exception
4632 * @throws \Exception
4634 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4635 $returnMessageText = FALSE) {
4637 $contribution = new CRM_Contribute_BAO_Contribution();
4638 $contribution->id
= $contributionID;
4639 if (!$contribution->find(TRUE)) {
4640 throw new CRM_Core_Exception('Contribution does not exist');
4642 $contribution->loadRelatedObjects($input, $ids, TRUE);
4643 // set receipt from e-mail and name in value
4644 if (!$returnMessageText) {
4645 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4647 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4648 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4649 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4650 civicrm_api3('Contribution', 'create', [
4651 'receipt_date' => 'now',
4652 'id' => $contribution->id
,
4659 * Generate From email and from name in an array values
4661 * @param array $input
4662 * @param \CRM_Contribute_BAO_Contribution $contribution
4666 public static function generateFromEmailAndName($input, $contribution) {
4667 // Use input value if supplied.
4668 if (!empty($input['receipt_from_email'])) {
4670 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4671 $input['receipt_from_email'],
4674 // if we are still empty see if we can use anything from a contribution page.
4676 if (!empty($contribution->contribution_page_id
)) {
4677 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4679 // if we are still empty see if we can use anything from a contribution page.
4680 if (!empty($pageValues['receipt_from_email'])) {
4682 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4683 $pageValues['receipt_from_email'],
4686 // If we are still empty fall back to the domain or logged in user information.
4687 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4691 * Generate credit note id with next avaible number
4696 public static function createCreditNoteId() {
4697 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4699 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4700 $creditNoteId = NULL;
4704 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4705 $result = civicrm_api3('Contribution', 'getcount', [
4707 'creditnote_id' => $creditNoteId,
4709 } while ($result > 0);
4711 return $creditNoteId;
4715 * Load related memberships.
4719 * @return array $ids
4724 * Note that in theory it should be possible to retrieve these from the line_item table
4725 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4726 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4727 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4728 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4730 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4733 public function loadRelatedMembershipObjects($ids = []) {
4735 SELECT membership_id
4736 FROM civicrm_membership_payment
4737 WHERE contribution_id = %1 ";
4738 $params = [1 => [$this->id
, 'Integer']];
4739 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4741 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4742 while ($dao->fetch()) {
4743 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4744 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4748 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4749 foreach ($ids['membership'] as $id) {
4751 $membership = new CRM_Member_BAO_Membership();
4752 $membership->id
= $id;
4753 if (!$membership->find(TRUE)) {
4754 throw new Exception("Could not find membership record: $id");
4756 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4757 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4758 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4759 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4767 * This function is used to record partial payments for contribution
4769 * @param array $contribution
4771 * @param array $params
4773 * @return CRM_Financial_DAO_FinancialTrxn
4775 public static function recordPartialPayment($contribution, $params) {
4776 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4777 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4778 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4779 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4780 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4781 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4782 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4783 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4784 $balanceTrxnParams['currency'] = $contribution['currency'];
4785 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4786 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4787 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4788 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4789 $balanceTrxnParams['is_payment'] = 1;
4791 if (!empty($params['payment_processor'])) {
4792 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4793 // also anticipates it.
4794 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4795 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4797 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4801 * Get the description (source field) for the recurring contribution.
4803 * @param CRM_Contribute_BAO_Contribution $contribution
4804 * @param CRM_Event_DAO_Event|null $event
4807 * @throws \CiviCRM_API3_Exception
4809 protected static function getRecurringContributionDescription($contribution, $event) {
4810 if (!empty($contribution->source
)) {
4811 return $contribution->source
;
4813 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4814 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4815 'id' => $contribution->contribution_page_id
,
4816 'return' => 'title',
4818 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4821 return ts('Online Event Registration') . ': ' . $event->title
;
4823 elseif (!empty($contribution->contribution_recur_id
)) {
4824 return 'recurring contribution';
4830 * Function to add payments for contribution for Partially Paid status
4832 * @deprecated this is known to be flawed and possibly buggy.
4834 * Replace with Order.create->Payment.create flow.
4836 * @param array $contributions
4838 * @throws \CiviCRM_API3_Exception
4840 public static function addPayments($contributions) {
4841 // get financial trxn which is a payment
4842 $ftSql = "SELECT ft.id, ft.total_amount
4843 FROM civicrm_financial_trxn ft
4844 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4845 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4846 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4847 'labelColumn' => 'name',
4849 foreach ($contributions as $contribution) {
4850 if ($contributionStatus[$contribution->contribution_status_id
] !== 'Partially paid') {
4853 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, [
4861 // store financial item Proportionaly.
4863 'total_amount' => $ftDao->total_amount
,
4864 'contribution_id' => $contribution->id
,
4866 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4871 * Function use to store line item proportionally in in entity financial trxn table
4873 * @param array $trxnParams
4875 * @param int $trxnId
4877 * @param float $contributionTotalAmount
4879 * @throws \CiviCRM_API3_Exception
4881 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4882 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4883 if (!empty($lineItems)) {
4884 // get financial item
4885 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4887 'contribution_total_amount' => $contributionTotalAmount,
4888 'trxn_total_amount' => $trxnParams['total_amount'],
4889 'trxn_id' => $trxnId,
4891 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4896 * Checks if line items total amounts
4897 * match the contribution total amount.
4899 * @param array $params
4900 * array of order params.
4902 * @throws \API_Exception
4904 public static function checkLineItems(&$params) {
4905 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4906 $lineItemAmount = 0;
4908 foreach ($params['line_items'] as &$lineItems) {
4909 foreach ($lineItems['line_item'] as &$item) {
4910 if (empty($item['financial_type_id'])) {
4911 $item['financial_type_id'] = $params['financial_type_id'];
4913 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4917 if (!isset($totalAmount)) {
4918 $params['total_amount'] = $lineItemAmount;
4921 $currency = CRM_Utils_Array
::value('currency', $params, '');
4923 if (empty($currency)) {
4924 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4927 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4928 throw new CRM_Contribute_Exception_CheckLineItemsException();
4934 * Get the financial account for the item associated with the new transaction.
4936 * @param array $params
4937 * @param int $default
4941 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4943 if (!empty($params['financial_account_id'])) {
4944 return $params['financial_account_id'];
4947 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4948 $preferredAccountsRelationships = [
4949 'Refunded' => 'Credit/Contra Revenue Account is',
4950 'Chargeback' => 'Chargeback Account is',
4953 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4954 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4955 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4957 $preferredAccountsRelationships[$contributionStatus]
4965 * ContributionPage values were being imposed onto values.
4967 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4968 * REALLY didn't want superimposed. The rest are left there in their overkill out
4971 * The rationale for making this explicit is that it was a case of carefully set values being
4972 * seemingly randonly overwritten without much care. In general I think array randomly setting
4973 * variables en mass is risky.
4975 * @param array $values
4979 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4980 $contributionPageValues = [];
4981 CRM_Contribute_BAO_ContributionPage
::setValues(
4982 $this->contribution_page_id
,
4983 $contributionPageValues
4986 // These are the values that I believe to be useful.
4989 'pay_later_receipt',
4991 'receipt_from_email',
4992 'receipt_from_name',
4996 'honoree_profile_id',
4997 'onbehalf_profile_id',
4998 'honor_block_is_active',
4999 // Kinda might be - but would be on the contribution...
5002 // Included for 'fear of regression' but can't justify any use for these....
5004 'payment_processor',
5005 'financial_type_id',
5006 'amount_block_is_active',
5011 'default_amount_id',
5015 'initial_amount_help_text',
5016 'initial_amount_label',
5018 'is_allow_other_amount',
5019 'is_billing_required',
5020 'is_confirm_enabled',
5021 'is_credit_card_only',
5023 'is_partial_payment',
5024 'is_recur_installments',
5025 'is_recur_interval',
5029 'min_initial_amount',
5030 'recur_frequency_unit',
5037 foreach ($valuesToCopy as $valueToCopy) {
5038 if (isset($contributionPageValues[$valueToCopy])) {
5039 if ($valueToCopy === 'title') {
5040 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
5043 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5051 * Get values of CiviContribute Settings
5052 * and check if its enabled or not.
5053 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5054 * in serialized form. Usually this should be stored as flat settings for each form fields
5055 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5056 * settings we will live with an inconsistency because it's too hard to change for now.
5057 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5060 * @param string $name
5061 * @param bool $checkInvoicing
5065 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5066 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5068 if ($checkInvoicing && empty($contributeSettings['invoicing'])) {
5073 return CRM_Utils_Array
::value($name, $contributeSettings);
5075 return $contributeSettings;
5079 * This function process contribution related objects.
5081 * @param int $contributionId
5082 * @param int $statusId
5083 * @param int|null $previousStatusId
5085 * @param string $receiveDate
5087 * @return null|string
5089 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5091 if (!$contributionId ||
!$statusId) {
5096 'contribution_id' => $contributionId,
5097 'contribution_status_id' => $statusId,
5098 'previous_contribution_status_id' => $previousStatusId,
5099 'receive_date' => $receiveDate,
5102 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5104 if (!is_array($updateResult) ||
5105 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5106 !is_array($updatedComponents) ||
5107 empty($updatedComponents)
5112 // get the user display name.
5114 SELECT display_name as displayName
5115 FROM civicrm_contact
5116 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5117 WHERE civicrm_contribution.id = {$contributionId}";
5118 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5120 // get the status message for user.
5121 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5123 if ($componentName == 'CiviMember') {
5124 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5125 CRM_Member_PseudoConstant
::membershipStatus()
5128 $statusNameMsgPart = 'updated';
5129 switch ($updatedStatusName) {
5132 $statusNameMsgPart = $updatedStatusName;
5136 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5137 1 => $userDisplayName,
5138 2 => $statusNameMsgPart,
5142 if ($componentName == 'CiviEvent') {
5143 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5144 CRM_Event_PseudoConstant
::participantStatus()
5146 if ($updatedStatusName == 'Cancelled') {
5147 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5149 elseif ($updatedStatusName == 'Registered') {
5150 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5154 if ($componentName == 'CiviPledge') {
5155 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5156 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5158 if ($updatedStatusName == 'Cancelled') {
5159 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5161 elseif ($updatedStatusName == 'Failed') {
5162 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5164 elseif ($updatedStatusName == 'Completed') {
5165 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5174 * Get the contribution as it is in the database before being updated.
5176 * @param int $contributionID
5178 * @return \CRM_Contribute_BAO_Contribution|null
5180 private static function getOriginalContribution($contributionID) {
5181 return self
::getValues(['id' => $contributionID]);
5185 * Get the amount for the financial item row.
5187 * Helper function to start to break down recordFinancialTransactions for readability.
5189 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5191 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5192 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5195 * @param array $params
5196 * Params as passed to contribution.create
5198 * @param string $context
5199 * changeFinancialType| changedAmount
5200 * @param array $lineItemDetails
5202 * @param bool $isARefund
5203 * Is this a refund / negative transaction.
5204 * @param int $previousLineItemTotal
5207 * @todo move recordFinancialAccounts & helper functions to their own class?
5210 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5211 if ($context == 'changedAmount') {
5212 $lineTotal = $lineItemDetails['line_total'];
5213 if ($lineTotal != $previousLineItemTotal) {
5214 $lineTotal -= $previousLineItemTotal;
5218 elseif ($context == 'changeFinancialType') {
5219 return -$lineItemDetails['line_total'];
5221 elseif ($context == 'changedStatus') {
5222 $cancelledTaxAmount = 0;
5224 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5226 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5228 elseif ($context === NULL) {
5229 // erm, yes because? but, hey, it's tested.
5230 return $lineItemDetails['line_total'];
5232 elseif (empty($lineItemDetails['line_total'])) {
5233 // follow legacy code path
5235 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5236 return $params['total_amount'];
5239 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5244 * Get the multiplier for adjusting rows.
5246 * If we are dealing with a refund or cancellation then it will be a negative
5247 * amount to reflect the negative transaction.
5249 * If we are changing Financial Type it will be a negative amount to
5250 * adjust down the old type.
5252 * @param int $contribution_status_id
5253 * @param string $context
5257 protected static function getMultiplier($contribution_status_id, $context) {
5258 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5265 * Does this transaction reflect a payment instrument change.
5267 * @param array $params
5268 * @param array $pendingStatuses
5272 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5273 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5275 if (array_key_exists('payment_instrument_id', $params)) {
5276 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5277 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5279 //check if status is changed from Pending to Completed
5280 // do not update payment instrument changes for Pending to Completed
5281 if (!($contributionStatus == 'Completed' &&
5282 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5287 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5288 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5289 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5293 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5294 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5296 // another special case when check number is changed, create new financial records
5297 // create financial trxn with negative amount
5305 * Update the memberships associated with a contribution if it has been completed.
5307 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5308 * load them in this function. Code clean up would compensate for any minor performance implication.
5310 * @param \CRM_Contribute_BAO_Contribution $contribution
5311 * @param int $primaryContributionID
5312 * @param string $changeDate
5314 * @throws \CRM_Core_Exception
5315 * @throws \CiviCRM_API3_Exception
5317 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5318 $memberships = self
::getRelatedMemberships($contribution->id
);
5319 foreach ($memberships as $membership) {
5320 $membershipParams = [
5321 'id' => $membership['id'],
5322 'contact_id' => $membership['contact_id'],
5323 'is_test' => $membership['is_test'],
5324 'membership_type_id' => $membership['membership_type_id'],
5325 'membership_activity_status' => 'Completed',
5328 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5329 $membershipParams['membership_type_id'],
5330 $membershipParams['is_test'],
5331 $membershipParams['id']
5334 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5335 // this picks up membership type changes during renewals
5336 // @todo this is almost certainly an obsolete sql call, the pre-change
5337 // membership is accessible via $this->_relatedObjects
5339 SELECT membership_type_id
5340 FROM civicrm_membership_log
5341 WHERE membership_id={$membershipParams['id']}
5344 $dao = CRM_Core_DAO
::executeQuery($sql);
5345 if ($dao->fetch()) {
5346 if (!empty($dao->membership_type_id
)) {
5347 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5350 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5351 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5352 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5353 // 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.
5354 // @todo once apiv4 ships with core switch to that & find sanity.
5355 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5356 $membershipParams['membership_type_id'],
5357 $primaryContributionID
5360 // @todo remove all this stuff in favour of letting the api call further down handle in
5361 // (it is a duplication of what the api does).
5362 $dates = array_fill_keys([
5367 if ($currentMembership) {
5369 * Fixed FOR CRM-4433
5370 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5371 * when Contribution mode is notify and membership is for renewal )
5373 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5375 // @todo - we should pass membership_type_id instead of null here but not
5376 // adding as not sure of testing
5377 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5378 $changeDate, NULL, $membershipParams['num_terms']
5380 $dates['join_date'] = $currentMembership['join_date'];
5383 //get the status for membership.
5384 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5386 $dates['join_date'],
5389 $membershipParams['membership_type_id'],
5393 unset($dates['end_date']);
5394 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5395 //we might be renewing membership,
5396 //so make status override false.
5397 $membershipParams['is_override'] = FALSE;
5398 $membershipParams['status_override_end_date'] = 'null';
5400 //CRM-17723 - reset static $relatedContactIds array()
5401 // @todo move it to Civi Statics.
5403 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5404 civicrm_api3('Membership', 'create', $membershipParams);
5409 * Get payment links as they relate to a contribution.
5411 * If a payment can be made then include a payment link & if a refund is appropriate
5412 * then a refund link.
5415 * @param float $balance
5416 * @param string $contributionStatus
5419 * $actionLinks Links array containing:
5423 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5424 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5425 // In general the balance is the best way to determine if a payment can be added or not,
5426 // but not for Failed contributions, where we don't accept additional payments at the moment.
5427 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5428 // do accept more payments agains them.
5432 if ((int) $balance > 0) {
5433 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5435 'url' => CRM_Utils_System
::url('civicrm/payment', [
5441 'title' => ts('Submit Credit Card payment'),
5445 'url' => CRM_Utils_System
::url('civicrm/payment', [
5450 'title' => ts('Record Payment'),
5453 elseif ((int) $balance < 0) {
5455 'url' => CRM_Utils_System
::url('civicrm/payment', [
5460 'title' => ts('Record Refund'),
5463 return $actionLinks;
5467 * Get a query to determine the amount donated by the contact/s in the current financial year.
5469 * @param array $contactIDs
5473 public static function getAnnualQuery($contactIDs) {
5474 $contactIDs = implode(',', $contactIDs);
5475 $config = CRM_Core_Config
::singleton();
5476 $currentMonth = date('m');
5477 $currentDay = date('d');
5479 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5481 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5482 (int) $config->fiscalYearStart
['d'] > $currentDay
5485 $year = date('Y') - 1;
5490 $nextYear = $year +
1;
5492 if ($config->fiscalYearStart
) {
5493 $newFiscalYearStart = $config->fiscalYearStart
;
5494 if ($newFiscalYearStart['M'] < 10) {
5495 // This is just a clumsy way of adding padding.
5496 // @todo next round look for a nicer way.
5497 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5499 if ($newFiscalYearStart['d'] < 10) {
5500 // This is just a clumsy way of adding padding.
5501 // @todo next round look for a nicer way.
5502 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5504 $config->fiscalYearStart
= $newFiscalYearStart;
5505 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5508 // First of January.
5511 $startDate = "$year$monthDay";
5512 $endDate = "$nextYear$monthDay";
5515 'contact_id' => 'IN (' . $contactIDs . ')',
5516 'is_test' => ' = 0',
5517 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5519 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5520 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5523 foreach ($whereClauses as $key => $clause) {
5524 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5526 $whereClauseString = implode(' AND ', $clauses);
5528 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5529 // this group by + having on contribution_status_id improves performance
5531 SELECT COUNT(*) as count,
5532 SUM(total_amount) as amount,
5533 AVG(total_amount) as average,
5535 FROM civicrm_contribution b
5536 WHERE " . $whereClauseString . "
5537 GROUP BY currency, contribution_status_id
5538 HAVING $havingClause
5544 * Assign Test Value.
5546 * @param string $fieldName
5547 * @param array $fieldDef
5548 * @param int $counter
5550 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5551 if ($fieldName == 'tax_amount') {
5552 $this->{$fieldName} = "0.00";
5554 elseif ($fieldName == 'net_amount') {
5555 $this->{$fieldName} = "2.00";
5557 elseif ($fieldName == 'total_amount') {
5558 $this->{$fieldName} = "3.00";
5560 elseif ($fieldName == 'fee_amount') {
5561 $this->{$fieldName} = "1.00";
5564 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5569 * Check if contribution has participant/membership payment.
5571 * @param int $contributionId
5576 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5577 // get line item for contribution
5578 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5579 // check if line item is for membership or participant
5580 foreach ($lineItems as $items) {
5581 if ($items['entity_table'] == 'civicrm_participant') {
5585 elseif ($items['entity_table'] == 'civicrm_membership') {
5597 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5599 * @param array $trxnParams
5600 * Financial trxn params
5601 * @param array $contributionParams
5602 * Contribution Params
5606 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5607 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5610 $statusId = $contributionParams['contribution']->contribution_status_id
;
5611 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5612 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5613 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5614 // Return if contribution status is not completed.
5615 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5616 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5617 && $contributionParams['prevContribution']->is_pay_later
== 0
5623 $params = $trxnParams;
5624 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5625 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5626 $params['to_financial_account_id'] = $arAccountId;
5627 $params['status_id'] = array_search('Pending', $contributionStatuses);
5628 $params['is_payment'] = FALSE;
5629 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5630 self
::$_trxnIDs[] = $trxn->id
;
5631 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5635 * Calculate financial item amount when contribution is updated.
5637 * @param array $params
5638 * contribution params
5639 * @param array $amountParams
5641 * @param string $context
5645 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5646 if (!empty($params['is_quick_config'])) {
5647 $amount = $amountParams['item_amount'];
5649 $amount = $params['total_amount'];
5650 if ($context === NULL) {
5651 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5656 $amount = $amountParams['line_total'];
5657 if ($context == 'changedAmount') {
5658 $amount -= $amountParams['previous_line_total'];
5660 $amount *= $amountParams['diff'];
5666 * Retrieve Sales Tax Financial Accounts.
5672 public static function getSalesTaxFinancialAccounts() {
5673 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5674 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5675 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5676 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5677 $queryParams = [1 => [$accountRel, 'Integer']];
5678 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5679 $financialAccount = [];
5680 while ($dao->fetch()) {
5681 $financialAccount[$dao->id
] = $dao->id
;
5683 return $financialAccount;
5687 * Create tax entry in civicrm_entity_financial_trxn table.
5689 * @param array $entityParams
5691 * @param array $eftParams
5693 * @throws \CiviCRM_API3_Exception
5695 public static function createProportionalEntry($entityParams, $eftParams) {
5697 if ($entityParams['contribution_total_amount'] != 0) {
5698 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5700 // Record Entity Financial Trxn; CRM-20145
5701 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5702 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5706 * Create array of last financial item id's.
5708 * @param int $contributionId
5712 public static function getLastFinancialItemIds($contributionId) {
5713 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5714 FROM civicrm_financial_item fi
5715 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5716 WHERE li.contribution_id = %1";
5717 $dao = CRM_Core_DAO
::executeQuery($sql, [
5723 $ftIds = $taxItems = [];
5724 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5725 while ($dao->fetch()) {
5726 /* if sales tax item*/
5727 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5728 $taxItems[$dao->price_field_value_id
] = [
5729 'financial_item_id' => $dao->id
,
5730 'amount' => $dao->tax_amount
,
5734 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5737 return [$ftIds, $taxItems];
5741 * Create proportional entries in civicrm_entity_financial_trxn.
5743 * @param array $entityParams
5745 * @param array $lineItems
5747 * @param array $ftIds
5749 * @param array $taxItems
5751 * @throws \CiviCRM_API3_Exception
5753 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5755 'entity_table' => 'civicrm_financial_item',
5756 'financial_trxn_id' => $entityParams['trxn_id'],
5758 foreach ($lineItems as $key => $value) {
5759 if ($value['qty'] == 0) {
5762 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5763 $entityParams['line_item_amount'] = $value['line_total'];
5764 self
::createProportionalEntry($entityParams, $eftParams);
5765 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5766 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5767 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5768 self
::createProportionalEntry($entityParams, $eftParams);
5774 * Load entities related to the contribution into $this->_relatedObjects.
5778 * @throws \CRM_Core_Exception
5780 protected function loadRelatedEntitiesByID($ids) {
5782 'contact' => 'CRM_Contact_BAO_Contact',
5783 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5784 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5785 'financialType' => 'CRM_Financial_BAO_FinancialType',
5786 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5788 foreach ($entities as $entity => $bao) {
5789 if (!empty($ids[$entity])) {
5790 $this->_relatedObjects
[$entity] = new $bao();
5791 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5792 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5793 throw new CRM_Core_Exception($entity . ' could not be loaded');
5800 * Should an email receipt be sent for this contribution when complete.
5802 * @param array $input
5806 protected function isEmailReceipt($input) {
5807 if (isset($input['is_email_receipt'])) {
5808 return $input['is_email_receipt'];
5810 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5811 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5817 * Function to replace contribution tokens.
5819 * @param array $contributionIds
5821 * @param string $subject
5823 * @param array $subjectToken
5825 * @param string $text
5827 * @param string $html
5829 * @param array $messageToken
5831 * @param bool $escapeSmarty
5834 * @throws \CiviCRM_API3_Exception
5836 public static function replaceContributionTokens(
5845 if (empty($contributionIds)) {
5848 $contributionDetails = [];
5849 foreach ($contributionIds as $id) {
5850 $result = self
::getContributionTokenValues($id, $messageToken);
5851 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5852 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5853 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5855 return $contributionDetails;
5859 * Get the contribution fields for $id and display labels where
5860 * appropriate (if the token is present).
5863 * @param array $messageToken
5866 public static function getContributionTokenValues($id, $messageToken) {
5870 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5871 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5872 if (!empty($messageToken)) {
5873 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5874 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5875 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5883 * Get invoice_number for contribution.
5885 * @param int $contributionID
5889 public static function getInvoiceNumber($contributionID) {
5890 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5891 return $invoicePrefix . $contributionID;
5898 * Load the values needed for the event message.
5900 * @param int $eventID
5901 * @param int $participantID
5902 * @param int|null $contributionID
5905 * @throws \CRM_Core_Exception
5907 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5912 $values = ['event' => []];
5914 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5915 // add custom fields for event
5916 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5918 $eventCustomGroup = [];
5919 foreach ($eventGroupTree as $key => $group) {
5920 if ($key === 'info') {
5924 foreach ($group['fields'] as $k => $customField) {
5925 $groupLabel = $group['title'];
5926 if (!empty($customField['customValue'])) {
5927 foreach ($customField['customValue'] as $customFieldValues) {
5928 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5933 $values['event']['customGroup'] = $eventCustomGroup;
5935 //get participant details
5936 $participantParams = [
5937 'id' => $participantID,
5940 $values['participant'] = [];
5942 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5943 // add custom fields for event
5944 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5945 $participantCustomGroup = [];
5946 foreach ($participantGroupTree as $key => $group) {
5947 if ($key === 'info') {
5951 foreach ($group['fields'] as $k => $customField) {
5952 $groupLabel = $group['title'];
5953 if (!empty($customField['customValue'])) {
5954 foreach ($customField['customValue'] as $customFieldValues) {
5955 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5960 $values['participant']['customGroup'] = $participantCustomGroup;
5962 //get location details
5964 'entity_id' => $eventID,
5965 'entity_table' => 'civicrm_event',
5967 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5970 'entity_table' => 'civicrm_event',
5971 'entity_id' => $eventID,
5972 'module' => 'CiviEvent',
5975 list($custom_pre_id,
5977 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5979 $values['custom_pre_id'] = $custom_pre_id;
5980 $values['custom_post_id'] = $custom_post_ids;
5982 // set lineItem for event contribution
5983 if ($contributionID) {
5984 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5985 if (!empty($participantIds)) {
5986 foreach ($participantIds as $pIDs) {
5987 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5988 if (!CRM_Utils_System
::isNull($lineItem)) {
5989 $values['lineItem'][] = $lineItem;