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 = []) {
93 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
94 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
95 $action = $contributionID ?
'edit' : 'create';
97 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
98 $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)]);
99 throw new CRM_Core_Exception($message);
102 // first clean up all the money fields
107 'non_deductible_amount',
110 //if priceset is used, no need to cleanup money
111 if (!empty($params['skipCleanMoney'])) {
115 // @todo put a deprecated here - this should be done in the form layer.
116 $params['skipCleanMoney'] = FALSE;
117 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
120 foreach ($moneyFields as $field) {
121 if (isset($params[$field])) {
122 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
126 //set defaults in create mode
127 if (!$contributionID) {
128 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
130 if (empty($params['invoice_number'])) {
131 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
132 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
136 //if contribution is created with cancelled or refunded status, add credit note id
137 // do the same for chargeback - this entered the code 'accidentally' but moving it to here
138 // as part of cleanup maintains consistency.
139 if (self
::isContributionStatusNegative(CRM_Utils_Array
::value('contribution_status_id', $params))) {
140 if (empty($params['creditnote_id'])) {
141 $params['creditnote_id'] = self
::createCreditNoteId();
144 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
145 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
146 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
148 if (!$contributionStatusID) {
149 // Since the fee amount is expecting this (later on) ensure it is always set.
150 // It would only not be set for an update where it is unchanged.
151 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
152 'id' => $contributionID,
153 'return' => 'contribution_status_id',
156 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
159 && CRM_Utils_Array
::value('membership_id', $params)
160 && Civi
::settings()->get('deferred_revenue_enabled')
162 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
163 if ($memberStartDate) {
164 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
167 self
::calculateMissingAmountParams($params, $contributionID);
169 if (!empty($params['payment_instrument_id'])) {
170 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
171 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
172 $params['check_number'] = 'null';
176 $setPrevContribution = TRUE;
177 // CRM-13964 partial payment
178 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
179 $partialAmtTotal = $params['partial_payment_total'];
180 $partialAmtPay = $params['partial_amount_to_pay'];
181 $params['total_amount'] = $partialAmtTotal;
182 if ($partialAmtPay < $partialAmtTotal) {
183 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
184 $params['is_pay_later'] = 0;
185 $setPrevContribution = FALSE;
188 if ($contributionID && $setPrevContribution) {
189 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
191 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
193 if ($contributionID && !empty($params['revenue_recognition_date'])
194 && !($previousContributionStatus === 'Pending')
195 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
197 unset($params['revenue_recognition_date']);
200 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
201 isset($params['financial_type_id']))) {
202 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
205 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
207 $contribution = new CRM_Contribute_BAO_Contribution();
208 $contribution->copyValues($params);
210 $contribution->id
= $contributionID;
212 if (empty($contribution->id
)) {
213 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
214 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
215 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
219 $result = $contribution->save();
221 // Add financial_trxn details as part of fix for CRM-4724
222 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
223 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
225 //add Account details
226 $params['contribution'] = $contribution;
227 if (empty($params['is_post_payment_create'])) {
228 // If this is being called from the Payment.create api/ BAO then that Entity
229 // takes responsibility for the financial transactions. In fact calling Payment.create
230 // to add payments & having it call completetransaction and / or contribution.create
231 // to update related entities is the preferred flow.
232 // Note that leveraging this parameter for any other code flow is not supported and
233 // is likely to break in future and / or cause serious problems in your data.
234 // https://github.com/civicrm/civicrm-core/pull/14673
235 self
::recordFinancialAccounts($params);
238 if (self
::isUpdateToRecurringContribution($params)) {
239 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
240 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
242 CRM_Utils_Array
::value('receive_date', $params)
246 $params['contribution_id'] = $contribution->id
;
248 if (!empty($params['custom']) &&
249 is_array($params['custom'])
251 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
254 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
256 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
261 * Is this contribution updating an existing recurring contribution.
263 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
264 * pending payment is being confirmed (or failing).
266 * @param array $params
270 public static function isUpdateToRecurringContribution($params) {
271 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
274 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
277 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
280 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
281 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
288 * Get defaults for new entity.
292 public static function getDefaults() {
294 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
295 FALSE, FALSE, FALSE, 'AND is_default = 1')
297 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
298 'receive_date' => date('Y-m-d H:i:s'),
303 * Fetch the object and store the values in the values array.
305 * @param array $params
306 * Input parameters to find object.
307 * @param array $values
308 * Output values of the object.
310 * The array that holds all the db ids.
312 * @return CRM_Contribute_BAO_Contribution|null
313 * The found object or null
315 public static function getValues($params, &$values = [], &$ids = []) {
316 if (empty($params)) {
319 $contribution = new CRM_Contribute_BAO_Contribution();
321 $contribution->copyValues($params);
323 if ($contribution->find(TRUE)) {
324 $ids['contribution'] = $contribution->id
;
326 CRM_Core_DAO
::storeValues($contribution, $values);
328 return $contribution;
330 // return by reference
336 * Get the values and resolve the most common mappings.
338 * Since contribution status is resolved in almost every function that calls getValues it makes
339 * sense to have an extra function to resolve it rather than repeat the code.
341 * Think carefully before adding more mappings to be resolved as there could be performance implications
342 * if this function starts to be called from more iterative functions.
344 * @param array $params
345 * Input parameters to find object.
348 * Array of the found contribution.
349 * @throws CRM_Core_Exception
351 public static function getValuesWithMappings($params) {
353 $contribution = self
::getValues($params, $values, $ids);
354 if (is_null($contribution)) {
355 throw new CRM_Core_Exception('No contribution found');
357 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
362 * Calculate net_amount & fee_amount if they are not set.
364 * Net amount should be total - fee.
365 * This should only be called for new contributions.
367 * @param array $params
368 * Params for a new contribution before they are saved.
369 * @param int|null $contributionID
370 * Contribution ID if we are dealing with an update.
372 * @throws \CiviCRM_API3_Exception
374 public static function calculateMissingAmountParams(&$params, $contributionID) {
375 if (!$contributionID && !isset($params['fee_amount'])) {
376 if (isset($params['total_amount']) && isset($params['net_amount'])) {
377 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
380 $params['fee_amount'] = 0;
383 if (!isset($params['net_amount'])) {
384 if (!$contributionID) {
385 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
388 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
389 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
390 // net_amount may need adjusting.
391 $contribution = civicrm_api3('Contribution', 'getsingle', [
392 'id' => $contributionID,
393 'return' => ['total_amount', 'net_amount', 'fee_amount'],
395 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
396 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
397 $params['net_amount'] = $totalAmount - $feeAmount;
405 * @param $billingLocationTypeID
409 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
410 $hasBillingField = FALSE;
419 //build address array
421 $addressParams['location_type_id'] = $billingLocationTypeID;
422 $addressParams['is_billing'] = 1;
424 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
425 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
426 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
427 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
429 foreach ($billingFields as $value) {
430 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
431 if (!empty($addressParams[$value])) {
432 $hasBillingField = TRUE;
435 return [$hasBillingField, $addressParams];
439 * Get address params ready to be passed to the payment processor.
441 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
442 * To create an address we need state_province_id.
444 * @param array $params
445 * @param int $billingLocationTypeID
449 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
450 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
451 foreach ($addressParams as $name => $field) {
452 if (substr($name, 0, 8) == 'billing_') {
453 $addressParams[substr($name, 9)] = $addressParams[$field];
456 return [$hasBillingField, $addressParams];
460 * Get the number of terms for this contribution for a given membership type
461 * based on querying the line item table and relevant price field values
462 * Note that any one contribution should only be able to have one line item relating to a particular membership
465 * @param int $membershipTypeID
467 * @param int $contributionID
471 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
472 $numTerms = CRM_Core_DAO
::singleValueQuery("
473 SELECT membership_num_terms FROM civicrm_line_item li
474 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
475 WHERE contribution_id = %1 AND membership_type_id = %2",
476 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
478 // default of 1 is precautionary
479 return empty($numTerms) ?
1 : $numTerms;
483 * Takes an associative array and creates a contribution object.
485 * @param array $params
486 * (reference ) an assoc array of name/value pairs.
488 * The array that holds all the db ids.
490 * @return CRM_Contribute_BAO_Contribution
492 * @throws \CRM_Core_Exception
493 * @throws \CiviCRM_API3_Exception
495 public static function create(&$params, $ids = []) {
502 'revenue_recognition_date',
504 foreach ($dateFields as $df) {
505 if (isset($params[$df])) {
506 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
510 $transaction = new CRM_Core_Transaction();
513 $contribution = self
::add($params, $ids);
515 catch (CRM_Core_Exception
$e) {
516 $transaction->rollback();
520 $params['contribution_id'] = $contribution->id
;
521 $session = CRM_Core_Session
::singleton();
523 if (!empty($params['note'])) {
525 'entity_table' => 'civicrm_contribution',
526 'note' => $params['note'],
527 'entity_id' => $contribution->id
,
528 'contact_id' => $session->get('userID'),
529 'modified_date' => date('Ymd'),
531 if (!$noteParams['contact_id']) {
532 $noteParams['contact_id'] = $params['contact_id'];
534 CRM_Core_BAO_Note
::add($noteParams);
537 // make entry in batch entity batch table
538 if (!empty($params['batch_id'])) {
539 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
546 $retrieveRequired = 0;
547 foreach ($titleFields as $titleField) {
548 if (!isset($contribution->$titleField)) {
549 $retrieveRequired = 1;
553 if ($retrieveRequired == 1) {
554 $contribution->find(TRUE);
558 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
560 $transaction->commit();
562 $activity = civicrm_api3('Activity', 'get', [
563 'source_record_id' => $contribution->id
,
564 'options' => ['limit' => 1],
566 'activity_type_id' => 'Contribution',
567 'return' => ['id', 'campaign'],
570 //CRM-18406: Update activity when edit contribution.
571 if ($activity['count']) {
572 // CRM-13237 : if activity record found, update it with campaign id of contribution
573 // @todo compare campaign ids first.
574 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
575 $contribution->activity_id
= $activity['id'];
578 if (empty($contribution->contact_id
)) {
579 $contribution->find(TRUE);
581 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
583 // do not add to recent items for import, CRM-4399
584 if (empty($params['skipRecentView'])) {
585 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
586 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
588 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
595 $retrieveRequired = 0;
596 foreach ($titleFields as $titleField) {
597 if (!isset($contribution->$titleField)) {
598 $retrieveRequired = 1;
602 if ($retrieveRequired == 1) {
603 $contribution->find(TRUE);
605 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
606 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
609 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
610 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
611 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
615 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
616 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
617 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
621 // add the recently created Contribution
622 CRM_Utils_Recent
::add($title,
626 $contribution->contact_id
,
632 return $contribution;
636 * Get the values for pseudoconstants for name->value and reverse.
638 * @param array $defaults
639 * (reference) the default values, some of which need to be resolved.
640 * @param bool $reverse
641 * True if we want to resolve the values in the reverse direction (value -> name).
643 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
644 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
645 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
646 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
647 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
651 * Convert associative array names to values and vice-versa.
653 * This function is used by both the web form layer and the api. Note that
654 * the api needs the name => value conversion, also the view layer typically
655 * requires value => name conversion
657 * @param array $defaults
658 * @param string $property
659 * @param array $lookup
660 * @param bool $reverse
664 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
665 $id = $property . '_id';
667 $src = $reverse ?
$property : $id;
668 $dst = $reverse ?
$id : $property;
670 if (!array_key_exists($src, $defaults)) {
674 $look = $reverse ?
array_flip($lookup) : $lookup;
676 if (is_array($look)) {
677 if (!array_key_exists($defaults[$src], $look)) {
681 $defaults[$dst] = $look[$defaults[$src]];
686 * Retrieve DB object based on input parameters.
688 * It also stores all the retrieved values in the default array.
690 * @param array $params
691 * (reference ) an assoc array of name/value pairs.
692 * @param array $defaults
693 * (reference ) an assoc array to hold the name / value pairs.
694 * in a hierarchical manner
696 * (reference) the array that holds all the db ids.
698 * @return CRM_Contribute_BAO_Contribution
700 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
701 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
702 return $contribution;
706 * Combine all the importable fields from the lower levels object.
708 * The ordering is important, since currently we do not have a weight
709 * scheme. Adding weight is super important and should be done in the
710 * next week or so, before this can be called complete.
712 * @param string $contactType
713 * @param bool $status
716 * array of importable Fields
718 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
719 if (!self
::$_importableFields) {
720 if (!self
::$_importableFields) {
721 self
::$_importableFields = [];
725 $fields = ['' => ['title' => ts('- do not import -')]];
728 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
731 $note = CRM_Core_DAO_Note
::import();
732 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
733 unset($tmpFields['option_value']);
734 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
735 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
737 // Using new Dedupe rule.
739 'contact_type' => $contactType,
740 'used' => 'Unsupervised',
742 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
743 $tmpContactField = [];
744 if (is_array($fieldsArray)) {
745 foreach ($fieldsArray as $value) {
746 //skip if there is no dupe rule
747 if ($value == 'none') {
750 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
755 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
756 $tmpContactField[trim($value)] = $contactFields[trim($value)];
758 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
761 $title = $tmpContactField[trim($value)]['title'];
763 $tmpContactField[trim($value)]['title'] = $title;
767 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
768 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
769 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
770 $fields = array_merge($fields, $tmpContactField);
771 $fields = array_merge($fields, $tmpFields);
772 $fields = array_merge($fields, $note);
773 $fields = array_merge($fields, $optionFields);
774 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
775 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
776 self
::$_importableFields = $fields;
778 return self
::$_importableFields;
782 * Combine all the exportable fields from the lower level objects.
784 * @param bool $checkPermission
787 * array of exportable Fields
789 public static function &exportableFields($checkPermission = TRUE) {
790 if (!self
::$_exportableFields) {
791 if (!self
::$_exportableFields) {
792 self
::$_exportableFields = [];
795 $fields = CRM_Contribute_DAO_Contribution
::export();
796 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
797 $fields = array_merge(
799 CRM_Contribute_DAO_Product
::export(),
800 CRM_Contribute_DAO_ContributionProduct
::export(),
801 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
803 'contribution_product_id' => [
804 'title' => ts('Premium'),
805 'name' => 'contribution_product_id',
806 'where' => 'civicrm_product.id',
807 'data_type' => CRM_Utils_Type
::T_INT
,
813 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
815 $contributionPage = [
816 'contribution_page' => [
817 'title' => ts('Contribution Page'),
818 'name' => 'contribution_page',
819 'where' => 'civicrm_contribution_page.title',
820 'data_type' => CRM_Utils_Type
::T_STRING
,
824 $contributionNote = [
825 'contribution_note' => [
826 'title' => ts('Contribution Note'),
827 'name' => 'contribution_note',
828 'data_type' => CRM_Utils_Type
::T_TEXT
,
833 'contribution_batch' => [
834 'title' => ts('Batch Name'),
840 'contribution_campaign_title' => [
841 'title' => ts('Campaign Title'),
842 'name' => 'campaign_title',
843 'where' => 'civicrm_campaign.title',
844 'data_type' => CRM_Utils_Type
::T_STRING
,
847 $softCreditFields = [
848 'contribution_soft_credit_name' => [
849 'name' => 'contribution_soft_credit_name',
850 'title' => ts('Soft Credit For'),
851 'where' => 'civicrm_contact_d.display_name',
852 'data_type' => CRM_Utils_Type
::T_STRING
,
854 'contribution_soft_credit_amount' => [
855 'name' => 'contribution_soft_credit_amount',
856 'title' => ts('Soft Credit Amount'),
857 'where' => 'civicrm_contribution_soft.amount',
858 'data_type' => CRM_Utils_Type
::T_MONEY
,
860 'contribution_soft_credit_type' => [
861 'name' => 'contribution_soft_credit_type',
862 'title' => ts('Soft Credit Type'),
863 'where' => 'contribution_softcredit_type.label',
864 'data_type' => CRM_Utils_Type
::T_STRING
,
866 'contribution_soft_credit_contribution_id' => [
867 'name' => 'contribution_soft_credit_contribution_id',
868 'title' => ts('Soft Credit For Contribution ID'),
869 'where' => 'civicrm_contribution_soft.contribution_id',
870 'data_type' => CRM_Utils_Type
::T_INT
,
872 'contribution_soft_credit_contact_id' => [
873 'name' => 'contribution_soft_credit_contact_id',
874 'title' => ts('Soft Credit For Contact ID'),
875 'where' => 'civicrm_contact_d.id',
876 'data_type' => CRM_Utils_Type
::T_INT
,
880 $fields = array_merge($fields, $contributionPage,
881 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
882 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
885 self
::$_exportableFields = $fields;
888 return self
::$_exportableFields;
892 * Record an activity when a payment is received.
894 * @todo this is intended to be moved to payment BAO class as a protected function
895 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
896 * merit it's own function as it makes the code less rather than more readable.
898 * @param int $contributionId
899 * @param int $participantId
900 * @param string $totalAmount
901 * @param string $currency
902 * @param string $trxnDate
904 * @throws \CRM_Core_Exception
905 * @throws \CiviCRM_API3_Exception
907 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
908 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
910 if ($participantId) {
911 $inputParams['id'] = $participantId;
914 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
915 $entityObj = $entityObj[$participantId];
916 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
919 $entityObj = new CRM_Contribute_BAO_Contribution();
920 $entityObj->id
= $contributionId;
921 $entityObj->find(TRUE);
922 $title = ts('Contribution');
924 // @todo per block above this is not a logical splitting off of functionality.
925 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
929 * Get the value for the To Financial Account.
931 * @param $contribution
936 public static function getToFinancialAccount($contribution, $params) {
937 if (!empty($params['payment_processor_id'])) {
938 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
940 if (!empty($params['payment_instrument_id'])) {
941 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
944 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
945 $queryParams = [1 => [$relationTypeId, 'Integer']];
946 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
951 * Get memberships realted to the contribution.
953 * @param int $contributionID
957 protected static function getRelatedMemberships($contributionID) {
958 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
959 'return' => 'membership_id',
960 'contribution_id' => (int) $contributionID,
963 foreach ($membershipPayments as $membershipPayment) {
964 $membershipIDs[] = $membershipPayment['membership_id'];
966 if (empty($membershipIDs)) {
969 // We could combine this with the MembershipPayment.get - we'd
970 // need to re-wrangle the params (here or in the calling function)
971 // as they would then me membership.contact_id, membership.is_test etc
972 return civicrm_api3('Membership', 'get', [
973 'id' => ['IN' => $membershipIDs],
974 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
979 * Cancel contribution.
981 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
983 * @param $processContributionObject
984 * @param $memberships
985 * @param $contributionId
986 * @param $membershipStatuses
987 * @param $updateResult
988 * @param $participant
990 * @param $pledgePayment
992 * @param $pledgePaymentIDs
993 * @param $contributionStatusId
997 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
998 // @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
999 $processContribution = FALSE;
1000 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1001 if (is_array($memberships)) {
1002 foreach ($memberships as $membership) {
1004 //Update Membership status if there is no other completed contribution associated with the membership.
1005 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1006 foreach ($relatedContributions as $contriId) {
1007 if ($contriId == $contributionId) {
1010 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1011 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1015 if ($membership && $update) {
1016 $newStatus = array_search('Cancelled', $membershipStatuses);
1019 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1021 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1022 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1023 'target_contact_id' => $membership->contact_id
,
1024 'source_record_id' => $membership->id
,
1025 'activity_type_id' => 'Change Membership Status',
1026 'status_id' => 'Completed',
1027 'priority_id' => 'Normal',
1028 'activity_date_time' => 'now',
1031 $membership->status_id
= $newStatus;
1032 $membership->is_override
= TRUE;
1033 $membership->status_override_end_date
= 'null';
1034 $membership->save();
1035 civicrm_api3('activity', 'create', $activityParam);
1037 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1038 if ($processContributionObject) {
1039 $processContribution = TRUE;
1046 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1047 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1049 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1050 if ($processContributionObject) {
1051 $processContribution = TRUE;
1055 if ($pledgePayment) {
1056 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1058 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1059 if ($processContributionObject) {
1060 $processContribution = TRUE;
1063 return [$updateResult, $processContribution];
1067 * Do any accounting updates required as a result of a contribution status change.
1069 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1070 * this may attempt to add a payment. We need to resolve that....
1072 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1073 * then updates the contribution but this process should not also record another financial trxn.
1074 * Currently we have weak detection fot that scenario & where it is detected the first returned
1075 * value is FALSE - meaning 'do not continue'.
1077 * We should also look at the fact that the calling function - updateFinancialAccounts
1078 * bunches together some disparate processes rather than having separate appropriate
1081 * @param array $params
1084 * Return indicates whether the updateFinancialAccounts function should continue.
1086 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1087 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1088 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1090 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1091 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1092 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1093 // why it is here or where it is handled instead.
1094 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1095 && $currentContributionStatus == 'Partially paid'))
1100 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1101 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1102 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1103 if (empty($params['contribution']->creditnote_id
)) {
1104 // This is always set in the Contribution::create function.
1105 CRM_Core_Error
::deprecatedFunctionWarning('Logic says this line is never reached & can be removed');
1106 $creditNoteId = self
::createCreditNoteId();
1107 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
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'];
1120 if (empty($params['contribution']->creditnote_id
)) {
1121 // This is always set in the Contribution::create function.
1122 CRM_Core_Error
::deprecatedFunctionWarning('Logic says this line is never reached & can be removed');
1123 $creditNoteId = self
::createCreditNoteId();
1124 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1128 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1129 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1133 if (($previousContributionStatus == 'Pending'
1134 ||
$previousContributionStatus == 'In Progress')
1135 && ($currentContributionStatus == 'Completed')
1137 if (empty($params['line_item'])) {
1139 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1140 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1141 // & this can be removed
1144 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1145 // This is an update so original currency if none passed in.
1146 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1148 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1149 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1150 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1151 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1153 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1156 'entity_table' => 'civicrm_financial_item',
1158 foreach ($params['line_item'] as $fieldId => $fields) {
1159 foreach ($fields as $fieldValueId => $lineItemDetails) {
1160 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1162 1 => [$lineItemDetails['id'], 'Integer'],
1164 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1165 while ($financialItem->fetch()) {
1166 $entityParams['entity_id'] = $financialItem->id
;
1167 $entityParams['amount'] = $financialItem->amount
;
1168 foreach (self
::$_trxnIDs as $tID) {
1169 $entityParams['financial_trxn_id'] = $tID;
1170 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1181 * It is possible to override the membership id that is updated from the payment processor.
1183 * Historically Paypal does this & it still does if it determines data is messed up - see
1184 * https://lab.civicrm.org/dev/membership/issues/13
1186 * Read the comment block on repeattransaction for more information
1187 * about how things should work.
1189 * @param int $contributionID
1190 * @param array $input
1192 * @throws \CiviCRM_API3_Exception
1194 protected static function handleMembershipIDOverride($contributionID, $input) {
1195 if (!empty($input['membership_id'])) {
1196 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1197 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1202 * Update all financial items related to the line item tto have a status of paid.
1204 * @param int $lineItemID
1206 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1209 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1212 2 => [$lineItemID, 'Integer'],
1214 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1215 CRM_Core_DAO
::executeQuery($query, $fparams);
1219 * Create the financial items for the line.
1221 * @param array $params
1222 * @param string $context
1223 * @param array $fields
1224 * @param array $previousLineItems
1225 * @param array $inputParams
1226 * @param bool $isARefund
1227 * @param array $trxnIds
1228 * @param int $fieldId
1232 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1233 foreach ($fields as $fieldValueId => $lineItemDetails) {
1234 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1235 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1236 if ($params['contribution']->receive_date
) {
1237 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1240 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1242 $currency = $params['prevContribution']->currency
;
1243 if ($params['contribution']->currency
) {
1244 $currency = $params['contribution']->currency
;
1246 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1248 'transaction_date' => $receiveDate,
1249 'contact_id' => $params['prevContribution']->contact_id
,
1250 'currency' => $currency,
1251 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1252 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
1253 'status_id' => $prevFinancialItem['status_id'],
1254 'financial_account_id' => $financialAccount,
1255 'entity_table' => 'civicrm_line_item',
1256 'entity_id' => $lineItemDetails['id'],
1258 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1259 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1260 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1262 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1263 $taxAmount = (float) $lineItemDetails['tax_amount'];
1264 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1265 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1266 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1268 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1269 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1271 if ($taxAmount != 0) {
1272 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1273 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1274 if ($lineItemDetails['financial_type_id']) {
1275 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1277 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1285 * Does this contributtion status update represent a refund.
1287 * @param int $previousContributionStatusID
1288 * @param int $currentContributionStatusID
1292 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1293 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1296 return self
::isContributionStatusNegative($currentContributionStatusID);
1302 public function addSelectWhereClause() {
1303 $whereClauses = parent
::addSelectWhereClause();
1304 if ($whereClauses !== []) {
1305 // In this case permisssions have been applied & we assume the
1306 // financialaclreport is applying these
1307 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1308 return $whereClauses;
1311 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1312 return $whereClauses;
1314 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1315 if (empty($types)) {
1316 $whereClauses['financial_type_id'] = 'IN (0)';
1319 $whereClauses['financial_type_id'] = [
1320 'IN (' . implode(',', array_keys($types)) . ')',
1323 return $whereClauses;
1327 * @param null $status
1328 * @param null $startDate
1329 * @param null $endDate
1331 * @return array|null
1333 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1337 $where[] = 'contribution_status_id = 1';
1341 $where[] = 'contribution_status_id = 3';
1346 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1349 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1351 $financialTypeACLJoin = '';
1352 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1353 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1354 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1355 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1356 if ($financialTypes) {
1357 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1358 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1361 $where[] = "c.financial_type_id IN (0)";
1365 $whereCond = implode(' AND ', $where);
1368 SELECT sum( total_amount ) as total_amount,
1369 count( c.id ) as total_count,
1371 FROM civicrm_contribution c
1372 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1373 $financialTypeACLJoin
1375 AND ( is_test = 0 OR is_test IS NULL )
1376 AND contact.is_deleted = 0
1380 $dao = CRM_Core_DAO
::executeQuery($query);
1383 while ($dao->fetch()) {
1384 $count +
= $dao->total_count
;
1385 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1389 'amount' => implode(', ', $amount),
1397 * Delete the indirect records associated with this contribution first.
1401 * @return mixed|null
1402 * $results no of deleted Contribution on success, false otherwise
1404 public static function deleteContribution($id) {
1405 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1407 $transaction = new CRM_Core_Transaction();
1410 //delete activity record
1412 'source_record_id' => $id,
1413 // activity type id for contribution
1414 'activity_type_id' => 6,
1417 CRM_Activity_BAO_Activity
::deleteActivity($params);
1419 //delete billing address if exists for this contribution.
1420 self
::deleteAddress($id);
1422 //update pledge and pledge payment, CRM-3961
1423 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1425 // remove entry from civicrm_price_set_entity, CRM-5095
1426 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1427 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1429 // cleanup line items.
1430 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1432 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1433 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1435 if ($participantId) {
1436 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1439 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1443 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1444 $noteId = key($note);
1446 CRM_Core_BAO_Note
::del($noteId, FALSE);
1449 $dao = new CRM_Contribute_DAO_Contribution();
1452 $results = $dao->delete();
1454 $transaction->commit();
1456 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1458 // delete the recently created Contribution
1459 $contributionRecent = [
1461 'type' => 'Contribution',
1463 CRM_Utils_Recent
::del($contributionRecent);
1469 * React to a financial transaction (payment) failure.
1471 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1472 * payments is important for forensic and outreach reasons.
1474 * @param int $contributionID
1475 * @param int $contactID
1476 * @param string $message
1478 * @throws \CiviCRM_API3_Exception
1480 public static function failPayment($contributionID, $contactID, $message) {
1481 civicrm_api3('activity', 'create', [
1482 'activity_type_id' => 'Failed Payment',
1483 'details' => $message,
1484 'subject' => ts('Payment failed at payment processor'),
1485 'source_record_id' => $contributionID,
1486 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1489 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1490 civicrm_api3('contribution', 'create', [
1491 'id' => $contributionID,
1492 'contribution_status_id' => 'Failed',
1497 * Check if there is a contribution with the same trxn_id or invoice_id.
1499 * @param array $input
1500 * An assoc array of name/value pairs.
1501 * @param array $duplicates
1502 * (reference) store ids of duplicate contribs.
1506 * true if duplicate, false otherwise
1508 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1510 $id = CRM_Utils_Array
::value('id', $input);
1512 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1513 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1519 $clause[] = "trxn_id = %1";
1520 $input[1] = [$trxn_id, 'String'];
1524 $clause[] = "invoice_id = %2";
1525 $input[2] = [$invoice_id, 'String'];
1528 if (empty($clause)) {
1532 $clause = implode(' OR ', $clause);
1534 $clause = "( $clause ) AND id != %3";
1535 $input[3] = [$id, 'Integer'];
1538 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1539 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1541 while ($dao->fetch()) {
1542 $duplicates[] = $dao->id
;
1549 * Takes an associative array and creates a contribution_product object.
1551 * the function extract all the params it needs to initialize the create a
1552 * contribution_product object. the params array could contain additional unused name/value
1555 * @param array $params
1556 * (reference) an assoc array of name/value pairs.
1558 * @return CRM_Contribute_DAO_ContributionProduct
1560 public static function addPremium(&$params) {
1561 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1562 $contributionProduct->copyValues($params);
1563 return $contributionProduct->save();
1567 * Get list of contribution fields for profile.
1568 * For now we only allow custom contribution fields to be in
1571 * @param bool $addExtraFields
1572 * True if special fields needs to be added.
1575 * the list of contribution fields
1577 public static function getContributionFields($addExtraFields = TRUE) {
1578 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1579 // @todo remove this - this line was added because payment_instrument_id was not
1580 // set to exportable - but now it is.
1581 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1583 if ($addExtraFields) {
1584 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1587 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1589 foreach ($contributionFields as $key => $var) {
1590 if ($key == 'contribution_contact_id') {
1593 elseif ($key == 'contribution_campaign_id') {
1594 $var['title'] = ts('Campaign');
1596 $fields[$key] = $var;
1599 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1604 * Add extra fields specific to contribution.
1606 public static function getSpecialContributionFields() {
1608 'contribution_soft_credit_name' => [
1609 'name' => 'contribution_soft_credit_name',
1610 'title' => ts('Soft Credit Name'),
1611 'headerPattern' => '/^soft_credit_name$/i',
1612 'where' => 'civicrm_contact_d.display_name',
1614 'contribution_soft_credit_email' => [
1615 'name' => 'contribution_soft_credit_email',
1616 'title' => ts('Soft Credit Email'),
1617 'headerPattern' => '/^soft_credit_email$/i',
1618 'where' => 'soft_email.email',
1620 'contribution_soft_credit_phone' => [
1621 'name' => 'contribution_soft_credit_phone',
1622 'title' => ts('Soft Credit Phone'),
1623 'headerPattern' => '/^soft_credit_phone$/i',
1624 'where' => 'soft_phone.phone',
1626 'contribution_soft_credit_contact_id' => [
1627 'name' => 'contribution_soft_credit_contact_id',
1628 'title' => ts('Soft Credit Contact ID'),
1629 'headerPattern' => '/^soft_credit_contact_id$/i',
1630 'where' => 'civicrm_contribution_soft.contact_id',
1632 'contribution_pcp_title' => [
1633 'name' => 'contribution_pcp_title',
1634 'title' => ts('Personal Campaign Page Title'),
1635 'headerPattern' => '/^contribution_pcp_title$/i',
1636 'where' => 'contribution_pcp.title',
1640 return $extraFields;
1644 * @param int $pageID
1648 public static function getCurrentandGoalAmount($pageID) {
1650 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1651 FROM civicrm_contribution_page p,
1652 civicrm_contribution c
1653 WHERE p.id = c.contribution_page_id
1655 AND c.cancel_date is null
1659 $config = CRM_Core_Config
::singleton();
1660 $params = [1 => [$pageID, 'Integer']];
1661 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1663 if ($dao->fetch()) {
1664 return [$dao->goal
, $dao->total
];
1667 return [NULL, NULL];
1672 * Get list of contributions which credit the passed in contact ID.
1674 * The returned array provides details about the original contribution & donor.
1676 * @param int $honorId
1677 * In Honor of Contact ID.
1680 * list of contribution fields
1681 * @todo - this is a confusing function called from one place. It has a test. It would be
1682 * nice to deprecate it.
1685 public static function getHonorContacts($honorId) {
1687 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1688 $honorDAO->contact_id
= $honorId;
1691 $type = CRM_Contribute_PseudoConstant
::financialType();
1693 while ($honorDAO->fetch()) {
1694 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1695 $contributionDAO->id
= $honorDAO->contribution_id
;
1697 if ($contributionDAO->find(TRUE)) {
1698 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1699 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1700 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1701 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1702 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1703 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1704 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1705 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1706 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1714 * Get the sort name of a contact for a particular contribution.
1717 * Id of the contribution.
1719 * @return null|string
1720 * sort name of the contact if found
1722 public static function sortName($id) {
1723 $id = CRM_Utils_Type
::escape($id, 'Integer');
1726 SELECT civicrm_contact.sort_name
1727 FROM civicrm_contribution, civicrm_contact
1728 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1729 AND civicrm_contribution.id = {$id}
1731 return CRM_Core_DAO
::singleValueQuery($query);
1735 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1737 * @param int|array $contactIDs
1741 public static function annual($contactIDs) {
1742 if (!is_array($contactIDs)) {
1743 // In practice I can't fine any evidence that this function is ever called with
1744 // anything other than a single contact id, but left like this due to .... fear.
1745 $contactIDs = explode(',', $contactIDs);
1748 $query = self
::getAnnualQuery($contactIDs);
1749 $dao = CRM_Core_DAO
::executeQuery($query);
1751 $amount = $average = [];
1752 while ($dao->fetch()) {
1753 if ($dao->count
> 0 && $dao->amount
> 0) {
1754 $count +
= $dao->count
;
1755 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1756 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1762 implode(', ', $amount),
1763 implode(', ', $average),
1770 * Check if there is a contribution with the params passed in.
1772 * Used for trxn_id,invoice_id and contribution_id
1774 * @param array $params
1775 * An assoc array of name/value pairs.
1778 * contribution id if success else NULL
1780 public static function checkDuplicateIds($params) {
1781 $dao = new CRM_Contribute_DAO_Contribution();
1785 foreach ($params as $k => $v) {
1787 $clause[] = "$k = '$v'";
1790 $clause = implode(' AND ', $clause);
1791 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1792 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1794 while ($dao->fetch()) {
1802 * Get the contribution details for component export.
1804 * @param int $exportMode
1806 * @param array $componentIds
1812 public static function getContributionDetails($exportMode, $componentIds) {
1813 $paymentDetails = [];
1814 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1816 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1817 $componentSelect = " civicrm_participant_payment.participant_id id";
1818 $additionalClause = "
1819 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1820 AND civicrm_participant_payment.participant_id {$componentClause} )
1823 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1824 $componentSelect = " civicrm_membership_payment.membership_id id";
1825 $additionalClause = "
1826 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1827 AND civicrm_membership_payment.membership_id {$componentClause} )
1830 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1831 $componentSelect = " civicrm_pledge_payment.id id";
1832 $additionalClause = "
1833 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1834 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1838 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1839 trxn_id, {$componentSelect}
1840 FROM civicrm_contribution
1841 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1842 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1843 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1844 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1845 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1846 AND option_group_contribution_status.id = contribution_status.option_group_id )
1850 $dao = CRM_Core_DAO
::executeQuery($query);
1852 while ($dao->fetch()) {
1853 $paymentDetails[$dao->id
] = [
1854 'total_amount' => $dao->total_amount
,
1855 'contribution_status' => $dao->status
,
1856 'receive_date' => $dao->receive_date
,
1857 'pay_instru' => $dao->payment_instrument
,
1858 'trxn_id' => $dao->trxn_id
,
1862 return $paymentDetails;
1866 * Create address associated with contribution record.
1868 * As long as there is one or more billing field in the parameters we will create the address.
1870 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1873 * @param array $params
1874 * @param int $billingLocationTypeID
1879 public static function createAddress($params, $billingLocationTypeID) {
1880 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1881 if ($hasBillingField) {
1882 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1883 return $address->id
;
1890 * Delete billing address record related contribution.
1892 * @param int $contributionId
1893 * @param int $contactId
1895 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1897 $contactJoin = NULL;
1899 if ($contributionId) {
1900 $clauses[] = "cc.id = {$contributionId}";
1904 $clauses[] = "cco.id = {$contactId}";
1905 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1908 if (empty($clauses)) {
1909 CRM_Core_Error
::fatal();
1912 $condition = implode(' OR ', $clauses);
1916 FROM civicrm_address ca
1917 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1921 $dao = CRM_Core_DAO
::executeQuery($query);
1923 while ($dao->fetch()) {
1924 $params = ['id' => $dao->id
];
1925 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1930 * This function check online pending contribution associated w/
1931 * Online Event Registration or Online Membership signup.
1933 * @param int $componentId
1934 * Participant/membership id.
1935 * @param string $componentName
1939 * pending contribution id.
1941 public static function checkOnlinePendingContribution($componentId, $componentName) {
1942 $contributionId = NULL;
1943 if (!$componentId ||
1944 !in_array($componentName, ['Event', 'Membership'])
1946 return $contributionId;
1949 if ($componentName == 'Event') {
1950 $idName = 'participant_id';
1951 $componentTable = 'civicrm_participant';
1952 $paymentTable = 'civicrm_participant_payment';
1953 $source = ts('Online Event Registration');
1956 if ($componentName == 'Membership') {
1957 $idName = 'membership_id';
1958 $componentTable = 'civicrm_membership';
1959 $paymentTable = 'civicrm_membership_payment';
1960 $source = ts('Online Contribution');
1963 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1966 SELECT component.id as {$idName},
1967 componentPayment.contribution_id as contribution_id,
1968 contribution.source source,
1969 contribution.contribution_status_id as contribution_status_id,
1970 contribution.is_pay_later as is_pay_later
1971 FROM $componentTable component
1972 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1973 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1974 WHERE component.id = {$componentId}";
1976 $dao = CRM_Core_DAO
::executeQuery($query);
1978 while ($dao->fetch()) {
1979 if ($dao->contribution_id
&&
1980 $dao->is_pay_later
&&
1981 $dao->contribution_status_id
== $pendingStatusId &&
1982 strpos($dao->source
, $source) !== FALSE
1984 $contributionId = $dao->contribution_id
;
1988 return $contributionId;
1992 * Update contribution as well as related objects.
1994 * This function by-passes hooks - to address this - don't use this function.
1996 * @param array $params
1997 * @param bool $processContributionObject
2001 * @throws CRM_Core_Exception
2002 * @throws \CiviCRM_API3_Exception
2005 * Use api contribute.completetransaction
2006 * For failures use failPayment (preferably exposing by api in the process).
2009 public static function transitionComponents($params, $processContributionObject = FALSE) {
2010 // get minimum required values.
2011 $contactId = CRM_Utils_Array
::value('contact_id', $params);
2012 $componentId = CRM_Utils_Array
::value('component_id', $params);
2013 $componentName = CRM_Utils_Array
::value('componentName', $params);
2014 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
2015 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
2017 // if we already processed contribution object pass previous status id.
2018 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
2022 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2024 // we process only ( Completed, Cancelled, or Failed ) contributions.
2025 if (!$contributionId ||
2026 !in_array($contributionStatusId, [
2027 array_search('Completed', $contributionStatuses),
2028 array_search('Cancelled', $contributionStatuses),
2029 array_search('Failed', $contributionStatuses),
2032 return $updateResult;
2035 if (!$componentName ||
!$componentId) {
2036 // get the related component details.
2037 $componentDetails = self
::getComponentDetails($contributionId);
2040 $componentDetails['contact_id'] = $contactId;
2041 $componentDetails['component'] = $componentName;
2043 if ($componentName == 'event') {
2044 $componentDetails['participant'] = $componentId;
2047 $componentDetails['membership'] = $componentId;
2051 if (!empty($componentDetails['contact_id'])) {
2052 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2058 // do check for required ids.
2059 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2060 return $updateResult;
2063 //now we are ready w/ required ids, start processing.
2065 $baseIPN = new CRM_Core_Payment_BaseIPN();
2067 $input = $ids = $objects = [];
2069 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
2070 $ids['contribution'] = $contributionId;
2071 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
2072 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
2073 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
2074 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
2075 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
2076 $ids['contributionRecur'] = NULL;
2077 $ids['contributionPage'] = NULL;
2079 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2080 CRM_Core_Error
::fatal();
2083 $memberships = &$objects['membership'];
2084 $participant = &$objects['participant'];
2085 $pledgePayment = &$objects['pledge_payment'];
2086 $contribution = &$objects['contribution'];
2087 $pledgeID = $oldStatus = NULL;
2088 $pledgePaymentIDs = [];
2089 if ($pledgePayment) {
2090 foreach ($pledgePayment as $key => $object) {
2091 $pledgePaymentIDs[] = $object->id
;
2093 $pledgeID = $pledgePayment[0]->pledge_id
;
2096 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2099 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2100 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2105 // we might want to process contribution object.
2106 $processContribution = FALSE;
2107 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2108 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2109 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2111 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2112 if (is_array($memberships)) {
2113 foreach ($memberships as $membership) {
2115 //Update Membership status if there is no other completed contribution associated with the membership.
2116 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2117 foreach ($relatedContributions as $contriId) {
2118 if ($contriId == $contributionId) {
2121 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2122 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2126 if ($membership && $update) {
2127 $membership->status_id
= array_search('Expired', $membershipStatuses);
2128 $membership->is_override
= TRUE;
2129 $membership->status_override_end_date
= 'null';
2130 $membership->save();
2132 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2133 if ($processContributionObject) {
2134 $processContribution = TRUE;
2140 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2141 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2143 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2144 if ($processContributionObject) {
2145 $processContribution = TRUE;
2149 if ($pledgePayment) {
2150 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2152 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2153 if ($processContributionObject) {
2154 $processContribution = TRUE;
2158 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2160 // only pending contribution related object processed.
2161 if ($previousContriStatusId &&
2162 !in_array($contributionStatuses[$previousContriStatusId], [
2167 // this is case when we already processed contribution object.
2168 return $updateResult;
2170 elseif (!$previousContriStatusId &&
2171 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2176 // this is case when we are going to process contribution object later.
2177 return $updateResult;
2180 if (is_array($memberships)) {
2181 foreach ($memberships as $membership) {
2186 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2187 $membership->membership_type_id
,
2188 $membership->is_test
, $membership->id
2191 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2192 // this picks up membership type changes during renewals
2194 SELECT membership_type_id
2195 FROM civicrm_membership_log
2196 WHERE membership_id=$membership->id
2199 $dao = new CRM_Core_DAO();
2201 if ($dao->fetch()) {
2202 if (!empty($dao->membership_type_id
)) {
2203 $membership->membership_type_id
= $dao->membership_type_id
;
2204 $membership->save();
2207 // else fall back to using current membership type
2208 // Figure out number of terms
2210 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2211 foreach ($lineitems as $lineitem) {
2212 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2213 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2215 // in case membership_num_terms comes through as null or zero
2216 $numterms = $numterms >= 1 ?
$numterms : 1;
2221 // CRM-15735-to update the membership status as per the contribution receive date
2223 $oldStatus = $membership->status_id
;
2224 if (!empty($params['receive_date'])) {
2225 $joinDate = $params['receive_date'];
2226 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2227 $membership->end_date
,
2228 $membership->join_date
,
2229 $params['receive_date'],
2231 $membership->membership_type_id
,
2234 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2235 $membership->save();
2238 if ($currentMembership) {
2239 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2240 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2241 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2244 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2247 //get the status for membership.
2248 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2250 $dates['join_date'],
2253 $membership->membership_type_id
,
2257 $formattedParams = [
2258 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2259 array_search('Current', $membershipStatuses)
2261 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2262 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2263 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2266 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2268 $membership->copyValues($formattedParams);
2269 $membership->save();
2271 //updating the membership log
2272 $membershipLog = [];
2273 $membershipLog = $formattedParams;
2274 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2275 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2277 $membershipLog['start_date'] = $logStartDate;
2278 $membershipLog['membership_id'] = $membership->id
;
2279 $membershipLog['modified_id'] = $membership->contact_id
;
2280 $membershipLog['modified_date'] = date('Ymd');
2281 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2283 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2285 //update related Memberships.
2286 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2288 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2289 $scheduledActivityID = CRM_Utils_Array
::value('id',
2290 civicrm_api3('Activity', 'Get',
2292 'source_record_id' => $membership->id
,
2293 'activity_type_id' => $activityType,
2294 'status_id' => 'Scheduled',
2297 'sort' => 'id DESC',
2302 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2303 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2304 if ($scheduledActivityID) {
2305 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2310 // track membership status change if any
2311 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2312 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2313 CRM_Activity_BAO_Activity
::addActivity($membership,
2314 'Change Membership Status',
2317 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2318 'source_contact_id' => $membershipLog['modified_id'],
2319 'priority_id' => 'Normal',
2324 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2325 if ($processContributionObject) {
2326 $processContribution = TRUE;
2329 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2335 $updatedStatusId = array_search('Registered', $participantStatuses);
2336 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2338 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2339 if ($processContributionObject) {
2340 $processContribution = TRUE;
2344 if ($pledgePayment) {
2345 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2347 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2348 if ($processContributionObject) {
2349 $processContribution = TRUE;
2354 // process contribution object.
2355 if ($processContribution) {
2356 $contributionParams = [];
2363 'payment_instrument_id',
2366 'financial_type_id',
2367 'contribution_status_id',
2368 'non_deductible_amount',
2372 foreach ($fields as $field) {
2373 if (empty($params[$field])) {
2376 $contributionParams[$field] = $params[$field];
2379 $ids = ['contribution' => $contributionId];
2380 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2383 return $updateResult;
2387 * Returns all contribution related object ids.
2389 * @param $contributionId
2393 public static function getComponentDetails($contributionId) {
2394 $componentDetails = $pledgePayment = [];
2395 if (!$contributionId) {
2396 return $componentDetails;
2400 SELECT c.id as contribution_id,
2401 c.contact_id as contact_id,
2402 c.contribution_recur_id,
2403 mp.membership_id as membership_id,
2404 m.membership_type_id as membership_type_id,
2405 pp.participant_id as participant_id,
2406 p.event_id as event_id,
2407 pgp.id as pledge_payment_id
2408 FROM civicrm_contribution c
2409 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2410 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2411 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2412 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2413 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2414 WHERE c.id = $contributionId";
2416 $dao = CRM_Core_DAO
::executeQuery($query);
2417 $componentDetails = [];
2419 while ($dao->fetch()) {
2420 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2421 $componentDetails['contact_id'] = $dao->contact_id
;
2422 if ($dao->event_id
) {
2423 $componentDetails['event'] = $dao->event_id
;
2425 if ($dao->participant_id
) {
2426 $componentDetails['participant'] = $dao->participant_id
;
2428 if ($dao->membership_id
) {
2429 if (!isset($componentDetails['membership'])) {
2430 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2432 $componentDetails['membership'][] = $dao->membership_id
;
2433 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2435 if ($dao->pledge_payment_id
) {
2436 $pledgePayment[] = $dao->pledge_payment_id
;
2438 if ($dao->contribution_recur_id
) {
2439 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2443 if ($pledgePayment) {
2444 $componentDetails['pledge_payment'] = $pledgePayment;
2447 return $componentDetails;
2451 * @param int $contactId
2452 * @param bool $includeSoftCredit
2454 * @return null|string
2456 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2460 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2461 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2462 $liWhere = " AND i.financial_type_id IN (0)";
2463 if (!empty($financialTypes)) {
2464 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2465 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2467 $contactContributionsSQL = "
2468 SELECT contribution.id AS id
2469 FROM civicrm_contribution contribution
2470 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2471 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2475 $contactSoftCreditContributionsSQL = "
2476 SELECT contribution.id
2477 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2478 ON ( contribution.id = softContribution.contribution_id )
2479 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2480 $query = "SELECT count( x.id ) count FROM ( ";
2481 $query .= $contactContributionsSQL;
2483 if ($includeSoftCredit) {
2484 $query .= " UNION ";
2485 $query .= $contactSoftCreditContributionsSQL;
2490 return CRM_Core_DAO
::singleValueQuery($query);
2494 * Repeat a transaction as part of a recurring series.
2497 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2498 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2499 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2500 * and associated entities.
2501 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2502 * which updates the various entities and sends appropriate emails.
2504 * Gaps in the above (@todo)
2505 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2506 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2507 * 3) Repeat transaction duplicates rather than calls Order.create
2508 * 4) Use of payment.create still limited - completetransaction is more common.
2509 * 5) the template transaction is tricky - historically we used the first contribution
2510 * linked to a recurring contribution. More recently that was changed to be the most recent.
2511 * Ideally it would be an actual template - not a contribution used as a template which
2512 * would give more appropriate flexibility. Note line_items have an entity so that table
2513 * could be used for the line item template - the difficulty is the custom fields...
2514 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2515 * to load the membership(s) referred to via line items in the template transactions. Any other
2516 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2517 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2518 * - membership_payment record
2519 * - civicrm_membership.contribution_recur_id
2521 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2522 * of historical processors since this has been handled 'forever' - specifically for paypal.
2523 * albeit by an even nastier mechanism than the current input override.
2524 * The count is out on how correct related entities wind up in this case.
2526 * @param CRM_Contribute_BAO_Contribution $contribution
2527 * @param array $input
2528 * @param array $contributionParams
2529 * @param int $paymentProcessorID
2532 * @throws CiviCRM_API3_Exception
2534 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2535 if (!empty($contribution->id
)) {
2538 if (empty($contribution->id
)) {
2539 // Unclear why this would only be set for repeats.
2540 if (!empty($input['amount'])) {
2541 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2544 if (!empty($contributionParams['contribution_recur_id'])) {
2545 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2546 'id' => $contributionParams['contribution_recur_id'],
2548 if (!empty($recurringContribution['campaign_id'])) {
2549 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2550 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2552 if (!empty($recurringContribution['financial_type_id'])) {
2553 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2554 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2557 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2558 $contributionParams['contribution_recur_id'],
2559 array_intersect_key($contributionParams, [
2560 'total_amount' => TRUE,
2561 'financial_type_id' => TRUE,
2564 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2566 $contributionParams['status_id'] = 'Pending';
2567 if (isset($contributionParams['financial_type_id'])) {
2568 // Give precedence to passed in type.
2569 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2572 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2574 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2575 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2577 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2578 //do not create CC or BCC emails or profile notifications.
2579 //The if is just to be safe. Not sure if we can ever arrive with this unset
2580 // but per CRM-19478 it seems it can be 'null'
2581 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2582 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2584 if (!empty($contribution->tax_amount
)) {
2585 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2588 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2589 $contribution->id
= $createContribution['id'];
2590 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2591 self
::handleMembershipIDOverride($contribution->id
, $input);
2597 * Get individual id for onbehalf contribution.
2599 * @param int $contributionId
2601 * @param int $contributorId
2605 * containing organization id and individual id
2607 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2611 if (!$contributionId) {
2615 // fetch contributor id if null
2616 if (!$contributorId) {
2617 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2618 $contributionId, 'contact_id'
2622 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2623 $activityTypeId = array_search('Contribution', $activityTypeIds);
2625 if ($activityTypeId && $contributorId) {
2627 SELECT civicrm_activity_contact.contact_id
2628 FROM civicrm_activity_contact
2629 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2630 WHERE civicrm_activity.activity_type_id = %1
2631 AND civicrm_activity.source_record_id = %2
2632 AND civicrm_activity_contact.record_type_id = %3
2635 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2636 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2639 1 => [$activityTypeId, 'Integer'],
2640 2 => [$contributionId, 'Integer'],
2641 3 => [$sourceID, 'Integer'],
2644 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2646 // for on behalf contribution source is individual and contributor is organization
2647 if ($sourceContactId && $sourceContactId != $contributorId) {
2648 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2649 // get rel type id for employee of relation
2650 foreach ($relationshipTypeIds as $id => $typeVals) {
2651 if ($typeVals['name_a_b'] == 'Employee of') {
2652 $relationshipTypeId = $id;
2657 $rel = new CRM_Contact_DAO_Relationship();
2658 $rel->relationship_type_id
= $relationshipTypeId;
2659 $rel->contact_id_a
= $sourceContactId;
2660 $rel->contact_id_b
= $contributorId;
2661 if ($rel->find(TRUE)) {
2662 $ids['individual_id'] = $rel->contact_id_a
;
2663 $ids['organization_id'] = $rel->contact_id_b
;
2674 public static function getContributionDates() {
2675 $config = CRM_Core_Config
::singleton();
2676 $currentMonth = date('m');
2677 $currentDay = date('d');
2678 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2679 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2680 (int ) $config->fiscalYearStart
['d'] > $currentDay
2683 $year = date('Y') - 1;
2688 $year = ['Y' => $year];
2689 $yearDate = $config->fiscalYearStart
;
2690 $yearDate = array_merge($year, $yearDate);
2691 $yearDate = CRM_Utils_Date
::format($yearDate);
2693 $monthDate = date('Ym') . '01';
2699 'yearDate' => $yearDate,
2700 'monthDate' => $monthDate,
2705 * Load objects relations to contribution object.
2706 * Objects are stored in the $_relatedObjects property
2707 * In the first instance we are just moving functionality from BASEIpn -
2709 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2711 * Note that the unit test for the BaseIPN class tests this function
2713 * @param array $input
2714 * Input as delivered from Payment Processor.
2716 * Ids as Loaded by Payment Processor.
2717 * @param bool $loadAll
2718 * Load all related objects - even where id not passed in? (allows API to call this).
2723 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2724 // @todo deprecate this function - the steps should be
2725 // 1) add additional functions like 'getRelatedMemberships'
2726 // 2) switch all calls that refer to ->_relatedObjects to
2727 // using the helper functions
2728 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2729 // 4) make ->_relatedObjects protected
2730 // 5) hone up the individual functions to not use rely on this having been called
2731 // 6) deprecate like mad
2733 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2734 if (empty($ids['contact']) && isset($this->contact_id
)) {
2735 $ids['contact'] = $this->contact_id
;
2738 if (empty($this->_component
)) {
2739 if (!empty($ids['event'])) {
2740 $this->_component
= 'event';
2743 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2747 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2748 // refactoring than anything else, and has unit test coverage.
2749 if (empty($this->financial_type_id
)) {
2753 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2758 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2759 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2760 $this->contribution_page_id
,
2763 if ($paymentProcessorID) {
2764 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2768 $ids['contributionType'] = $this->financial_type_id
;
2769 $ids['financialType'] = $this->financial_type_id
;
2770 if ($this->contribution_page_id
) {
2771 $ids['contributionPage'] = $this->contribution_page_id
;
2774 $this->loadRelatedEntitiesByID($ids);
2776 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2777 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2780 if (!empty($ids['pledge_payment'])) {
2781 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2782 if (empty($paymentID)) {
2785 $payment = new CRM_Pledge_BAO_PledgePayment();
2786 $payment->id
= $paymentID;
2787 if (!$payment->find(TRUE)) {
2788 throw new Exception("Could not find pledge payment record: " . $paymentID);
2790 $this->_relatedObjects
['pledge_payment'][] = $payment;
2794 // These are probably no longer accessed from anywhere
2795 // @todo remove this line, after ensuring not used.
2796 $ids = $this->loadRelatedMembershipObjects($ids);
2798 if ($this->_component
!= 'contribute') {
2799 // we are in event mode
2800 // make sure event exists and is valid
2801 $event = new CRM_Event_BAO_Event();
2802 $event->id
= $ids['event'];
2803 if ($ids['event'] &&
2806 throw new Exception("Could not find event: " . $ids['event']);
2809 $this->_relatedObjects
['event'] = &$event;
2811 $participant = new CRM_Event_BAO_Participant();
2812 $participant->id
= $ids['participant'];
2813 if ($ids['participant'] &&
2814 !$participant->find(TRUE)
2816 throw new Exception("Could not find participant: " . $ids['participant']);
2818 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2820 $this->_relatedObjects
['participant'] = &$participant;
2822 // get the payment processor id from event - this is inaccurate see CRM-16923
2823 // in future we should look at throwing an exception here rather than an dubious guess.
2824 if (!$paymentProcessorID) {
2825 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2826 if ($paymentProcessorID) {
2827 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2832 if ($paymentProcessorID) {
2833 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2834 $this->is_test ?
'test' : 'live'
2836 $ids['paymentProcessor'] = $paymentProcessorID;
2837 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2840 // Add contribution id to $ids. CRM-20401
2841 $ids['contribution'] = $this->id
;
2846 * Create array of message information - ie. return html version, txt version, to field
2848 * @param array $input
2849 * Incoming information.
2850 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2851 * just check presence of recur object but maintaining legacy approach
2854 * IDs of related objects.
2855 * @param array $values
2856 * Any values that may have already been compiled by calling process.
2857 * This is augmented by values 'gathered' by gatherMessageValues
2858 * @param bool $returnMessageText
2859 * Distinguishes between whether to send message or return.
2860 * message text. We are working towards this function ALWAYS returning message text & calling
2861 * function doing emails / pdfs with it
2867 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2868 $this->loadRelatedObjects($input, $ids);
2870 if (empty($this->_component
)) {
2871 $this->_component
= CRM_Utils_Array
::value('component', $input);
2874 //not really sure what params might be passed in but lets merge em into values
2875 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2876 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2877 if (!empty($input['receipt_date'])) {
2878 $values['receipt_date'] = $input['receipt_date'];
2881 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2882 //what does recur 'mean here - to do with payment processor return functionality but
2883 // what is the importance
2884 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2885 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2887 $entityID = $entity = NULL;
2888 if (isset($ids['contribution'])) {
2889 $entity = 'contribution';
2890 $entityID = $ids['contribution'];
2892 if (!empty($ids['membership'])) {
2893 //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
2894 // 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
2895 // line having loaded an array
2896 $ids['membership'] = (array) $ids['membership'];
2897 $entity = 'membership';
2898 $entityID = $ids['membership'][0];
2901 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2902 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2903 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2905 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2906 //direct mode showing billing block, so use directIPN for temporary
2907 $template->assign('contributeMode', 'directIPN');
2910 // todo remove strtolower - check consistency
2911 if (strtolower($this->_component
) == 'event') {
2912 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2913 $values['event'] = [];
2915 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2917 //get location details
2919 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2920 'entity_table' => 'civicrm_event',
2922 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2925 'entity_table' => 'civicrm_event',
2926 'entity_id' => $ids['event'],
2927 'module' => 'CiviEvent',
2930 list($custom_pre_id,
2932 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2934 $values['custom_pre_id'] = $custom_pre_id;
2935 $values['custom_post_id'] = $custom_post_ids;
2936 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2937 //and cases involving status updation through ipn
2938 // whatever that means!
2939 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2940 // perhaps we should throw an e-notice if amount is set & force total_amount?
2941 if (!empty($input['amount'])) {
2942 $values['totalAmount'] = $input['amount'];
2944 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2945 if ($values['event']['is_email_confirm']) {
2946 $values['is_email_receipt'] = 1;
2949 if (!empty($ids['contribution'])) {
2950 $values['contributionId'] = $ids['contribution'];
2953 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2954 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2958 $values['contribution_id'] = $this->id
;
2959 if (!empty($ids['related_contact'])) {
2960 $values['related_contact'] = $ids['related_contact'];
2961 if (isset($ids['onbehalf_dupe_alert'])) {
2962 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2965 'contact_id' => $ids['contact'],
2966 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2967 'Home', 'id', 'name'
2970 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2971 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2974 if ($this->is_test
) {
2977 if (!empty($this->_relatedObjects
['membership'])) {
2978 foreach ($this->_relatedObjects
['membership'] as $membership) {
2979 if ($membership->id
) {
2980 $values['membership_id'] = $membership->id
;
2981 $values['isMembership'] = TRUE;
2982 $values['membership_assign'] = TRUE;
2984 // need to set the membership values here
2985 $template->assign('membership_name',
2986 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2988 $template->assign('mem_start_date', $membership->start_date
);
2989 $template->assign('mem_join_date', $membership->join_date
);
2990 $template->assign('mem_end_date', $membership->end_date
);
2991 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2992 $template->assign('mem_status', $membership_status);
2993 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2994 $values['is_pay_later'] = 1;
2996 // Pass amount to floatval as string '0.00' is considered a
2997 // valid amount and includes Fee section in the mail.
2998 if (isset($values['amount'])) {
2999 $values['amount'] = floatval($values['amount']);
3002 if (!empty($this->contribution_recur_id
) && $paymentObject) {
3003 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
3004 $template->assign('cancelSubscriptionUrl', $url);
3005 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3006 $template->assign('updateSubscriptionBillingUrl', $url);
3007 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3008 $template->assign('updateSubscriptionUrl', $url);
3011 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3014 // otherwise if its about sending emails, continue sending without return, as we
3015 // don't want to exit the loop.
3020 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3026 * Gather values for contribution mail - this function has been created
3027 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3028 * Values related to the contribution in question are gathered
3030 * @param array $input
3031 * Input into function (probably from payment processor).
3032 * @param array $values
3034 * The set of ids related to the input.
3037 * @throws \CRM_Core_Exception
3039 public function _gatherMessageValues($input, &$values, $ids = []) {
3040 // set display address of contributor
3041 $values['billingName'] = '';
3042 if ($this->address_id
) {
3043 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3044 $addressDetails = reset($addressDetails);
3045 $values['billingName'] = $addressDetails['name'] ??
'';
3047 // Else we assign the billing address of the contribution contact.
3049 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3050 $addressDetails = reset($addressDetails);
3052 $values['address'] = $addressDetails['display'] ??
'';
3054 if ($this->_component
=== 'contribute') {
3055 //get soft contributions
3056 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3057 if (!empty($softContributions)) {
3058 $values['softContributions'] = $softContributions['soft_credit'];
3060 if (isset($this->contribution_page_id
)) {
3061 // This is a call we want to use less, in favour of loading related objects.
3062 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3063 if ($this->contribution_page_id
) {
3064 // This is precautionary as there are some legacy flows, but it should really be
3066 if (!isset($this->_relatedObjects
['contributionPage'])) {
3067 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3069 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3072 // no contribution page -probably back office
3074 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3075 $values['title'] = 'Contribution';
3077 // set lineItem for contribution
3079 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3080 if (!empty($lineItems)) {
3081 $firstLineItem = reset($lineItems);
3083 if (!empty($firstLineItem['price_set_id'])) {
3084 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3085 'id' => $firstLineItem['price_set_id'],
3086 'return' => 'is_quick_config, id',
3088 $values['priceSetID'] = $priceSet['id'];
3090 foreach ($lineItems as &$eachItem) {
3091 if (isset($this->_relatedObjects
['membership'])
3092 && is_array($this->_relatedObjects
['membership'])
3093 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3094 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
3095 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
3096 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
3098 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3099 // However, that does create upgrade pain so would be better to be phased in.
3100 $values['useForMember'] = empty($priceSet['is_quick_config']);
3102 $values['lineItem'][0] = $lineItems;
3106 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3110 // if this is onbehalf of contribution then set related contact
3111 if (!empty($relatedContact['individual_id'])) {
3112 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3116 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3119 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3122 foreach ($groupTree as $key => $group) {
3123 if ($key === 'info') {
3127 foreach ($group['fields'] as $k => $customField) {
3128 $groupLabel = $group['title'];
3129 if (!empty($customField['customValue'])) {
3130 foreach ($customField['customValue'] as $customFieldValues) {
3131 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3136 $values['customGroup'] = $customGroup;
3138 $values['is_pay_later'] = $this->is_pay_later
;
3144 * Assign message variables to template but try to break the habit.
3146 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3147 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3148 * multiple recurring payments for processors like IATS that use tokens.
3150 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3151 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3152 * Note we send directly from this function in some cases because it is only partly refactored.
3154 * Don't call this function directly as the signature will change.
3158 * @param bool $returnMessageText
3162 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3163 // @todo - this should have a better separation of concerns - ie.
3164 // gatherMessageValues should build an array of values to be assigned to the template
3165 // and this function should assign them (assigning null if not set).
3166 // the way the pcpParams & honor Params section works is a baby-step towards this.
3167 $template = CRM_Core_Smarty
::singleton();
3168 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3169 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3170 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3171 $template->assign('billingName', $values['billingName']);
3173 // For some unit tests contribution cannot contain paymentProcessor information
3174 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3175 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3177 //assign honor information to receipt message
3178 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3181 'soft_credit_type' => NULL,
3182 'honor_block_is_active' => NULL,
3184 if (isset($softRecord['soft_credit'])) {
3185 //if id of contribution page is present
3186 if (!empty($values['id'])) {
3187 $values['honor'] = [
3188 'honor_profile_values' => [],
3189 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3190 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3193 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3194 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3197 //offline contribution
3198 $softCreditTypes = $softCredits = [];
3199 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3200 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3201 $softCredits[$key] = [
3202 'Name' => $softCredit['contact_name'],
3203 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3206 $template->assign('softCreditTypes', $softCreditTypes);
3207 $template->assign('softCredits', $softCredits);
3211 $dao = new CRM_Contribute_DAO_ContributionProduct();
3212 $dao->contribution_id
= $this->id
;
3213 if ($dao->find(TRUE)) {
3214 $premiumId = $dao->product_id
;
3215 $template->assign('option', $dao->product_option
);
3217 $productDAO = new CRM_Contribute_DAO_Product();
3218 $productDAO->id
= $premiumId;
3219 $productDAO->find(TRUE);
3220 $template->assign('selectPremium', TRUE);
3221 $template->assign('product_name', $productDAO->name
);
3222 $template->assign('price', $productDAO->price
);
3223 $template->assign('sku', $productDAO->sku
);
3225 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3226 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3227 if (!$values['amount'] && isset($this->total_amount
)) {
3228 $values['amount'] = $this->total_amount
;
3233 'pcp_display_in_roll' => NULL,
3234 'pcp_roll_nickname' => NULL,
3235 'pcp_personal_note' => NULL,
3239 if (strtolower($this->_component
) == 'contribute') {
3241 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3242 $softDAO->contribution_id
= $this->id
;
3243 if ($softDAO->find(TRUE)) {
3244 $pcpParams['pcpBlock'] = TRUE;
3245 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3246 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3247 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3249 //assign the pcp page title for email subject
3250 $pcpDAO = new CRM_PCP_DAO_PCP();
3251 $pcpDAO->id
= $softDAO->pcp_id
;
3252 if ($pcpDAO->find(TRUE)) {
3253 $pcpParams['title'] = $pcpDAO->title
;
3257 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3258 $template->assign($templateKey, $templateValue);
3261 if ($this->financial_type_id
) {
3262 $values['financial_type_id'] = $this->financial_type_id
;
3265 $template->assign('trxn_id', $this->trxn_id
);
3266 $template->assign('receive_date',
3267 CRM_Utils_Date
::processDate($this->receive_date
)
3269 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3270 $template->assign('action', $this->is_test ?
1024 : 1);
3271 $template->assign('receipt_text',
3272 CRM_Utils_Array
::value('receipt_text',
3276 $template->assign('is_monetary', 1);
3277 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3278 $template->assign('currency', $this->currency
);
3279 $template->assign('address', CRM_Utils_Address
::format($input));
3280 if (!empty($values['customGroup'])) {
3281 $template->assign('customGroup', $values['customGroup']);
3283 if (!empty($values['softContributions'])) {
3284 $template->assign('softContributions', $values['softContributions']);
3286 if ($this->_component
== 'event') {
3287 $template->assign('title', $values['event']['title']);
3288 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3290 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3291 $viewRoles[] = $participantRoles[$v];
3293 $values['event']['participant_role'] = implode(', ', $viewRoles);
3294 $template->assign('event', $values['event']);
3295 $template->assign('participant', $values['participant']);
3296 $template->assign('location', $values['location']);
3297 $template->assign('customPre', $values['custom_pre_id']);
3298 $template->assign('customPost', $values['custom_post_id']);
3301 if ($this->_relatedObjects
['participant']->is_test
) {
3305 $values['params'] = [];
3306 //to get email of primary participant.
3307 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3308 $primaryAmount[] = [
3309 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3310 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3312 //build an array of cId/pId of participants
3313 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3314 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3315 //send receipt to additional participant if exists
3316 if (count($additionalIDs)) {
3317 $template->assign('isPrimary', 0);
3318 $template->assign('customProfile', NULL);
3319 //set additionalParticipant true
3320 $values['params']['additionalParticipant'] = TRUE;
3321 foreach ($additionalIDs as $pId => $cId) {
3323 //to change the status pending to completed
3324 $additional = new CRM_Event_DAO_Participant();
3325 $additional->id
= $pId;
3326 $additional->contact_id
= $cId;
3327 $additional->find(TRUE);
3328 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3329 $additional->status_id
= 1;
3330 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3331 //if additional participant dont have email
3333 if (!$additionalParticipantInfo) {
3334 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3337 'label' => $additional->fee_level
,
3338 'amount' => $additional->fee_amount
,
3340 $primaryAmount[] = [
3341 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3342 'amount' => $additional->fee_amount
,
3344 $additional->save();
3345 $template->assign('amount', $amount);
3346 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3350 //build an array of custom profile and assigning it to template
3351 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3353 if (count($customProfile)) {
3354 $template->assign('customProfile', $customProfile);
3357 // for primary contact
3358 $values['params']['additionalParticipant'] = FALSE;
3359 $template->assign('isPrimary', 1);
3360 $template->assign('amount', $primaryAmount);
3361 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3362 if ($this->payment_instrument_id
) {
3363 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3364 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3366 // carry paylater, since we did not created billing,
3367 // so need to pull email from primary location, CRM-4395
3368 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3374 * Check whether payment processor supports
3375 * cancellation of contribution subscription
3377 * @param int $contributionId
3380 * @param bool $isNotCancelled
3384 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3385 $cacheKeyString = "$contributionId";
3386 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3388 static $supportsCancel = [];
3390 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3391 $supportsCancel[$cacheKeyString] = FALSE;
3392 $isCancelled = FALSE;
3394 if ($isNotCancelled) {
3395 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3398 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3399 if (!empty($paymentObject)) {
3400 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3403 return $supportsCancel[$cacheKeyString];
3407 * Check whether subscription is already cancelled.
3409 * @param int $contributionId
3413 * contribution status
3415 public static function isSubscriptionCancelled($contributionId) {
3417 SELECT cr.contribution_status_id
3418 FROM civicrm_contribution_recur cr
3419 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3420 WHERE con.id = %1 LIMIT 1";
3421 $params = [1 => [$contributionId, 'Integer']];
3422 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3423 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3424 if ($status == 'Cancelled') {
3431 * Create all financial accounts entry.
3433 * @param array $params
3434 * Contribution object, line item array and params for trxn.
3437 * @param array $financialTrxnValues
3439 * @return null|\CRM_Core_BAO_FinancialTrxn
3441 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3442 $skipRecords = $update = $return = $isRelatedId = FALSE;
3444 $additionalParticipantId = [];
3445 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3446 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3448 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3449 $entityId = $params['participant_id'];
3450 $entityTable = 'civicrm_participant';
3451 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3453 elseif (!empty($params['membership_id'])) {
3454 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3455 // are created off one contribution should be handled elsewhere
3456 $entityId = $params['membership_id'];
3457 $entityTable = 'civicrm_membership';
3460 $entityId = $params['contribution']->id
;
3461 $entityTable = 'civicrm_contribution';
3464 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3465 $isRelatedId = TRUE;
3468 $entityID[] = $entityId;
3469 if (!empty($additionalParticipantId)) {
3470 $entityID +
= $additionalParticipantId;
3472 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3473 if (empty($params['prevContribution'])) {
3480 $statusId = $params['contribution']->contribution_status_id
;
3481 // CRM-13964 partial payment
3482 if ($contributionStatus == 'Partially paid'
3483 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3485 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3486 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3488 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3489 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3490 $params['total_amount'] = $partialAmtPay;
3492 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3493 if (empty($balanceTrxnInfo['trxn_id'])) {
3494 // create new balance transaction record
3495 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3497 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3498 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3499 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3500 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3501 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3502 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3503 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3504 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3505 $balanceTrxnParams['status_id'] = $statusId;
3506 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3507 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3508 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3509 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3510 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3511 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3513 $balanceTrxnParams['is_payment'] = 1;
3515 if (!empty($params['payment_processor'])) {
3516 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3518 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3522 // build line item array if its not set in $params
3523 if (empty($params['line_item']) ||
$additionalParticipantId) {
3524 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3527 if ($contributionStatus != 'Failed' &&
3528 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3530 $skipRecords = TRUE;
3535 if (in_array($contributionStatus, $pendingStatus)) {
3536 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3537 $params['financial_type_id'],
3538 'Accounts Receivable Account is'
3541 elseif (!empty($params['payment_processor'])) {
3542 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3543 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3544 'id' => $params['payment_processor'],
3545 'return' => 'payment_instrument_id',
3548 elseif (!empty($params['payment_instrument_id'])) {
3549 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3552 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3553 $queryParams = [1 => [$relationTypeId, 'Integer']];
3554 $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);
3557 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3558 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3559 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3561 //build financial transaction params
3563 'contribution_id' => $params['contribution']->id
,
3564 'to_financial_account_id' => $params['to_financial_account_id'],
3565 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3566 'total_amount' => $totalAmount,
3567 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3568 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3569 'currency' => $params['contribution']->currency
,
3570 'trxn_id' => $params['contribution']->trxn_id
,
3571 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3572 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3573 // this should really default to completed (after discussion).
3574 'status_id' => $statusId,
3575 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3576 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3577 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3578 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3580 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3581 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3582 if (isset($params['refund_trxn_id'])) {
3583 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3584 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3587 //CRM-16259, set is_payment flag for non pending status
3588 if (!in_array($contributionStatus, $pendingStatus)) {
3589 $trxnParams['is_payment'] = 1;
3591 if (!empty($params['payment_processor'])) {
3592 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3595 if (isset($fromFinancialAccountId)) {
3596 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3599 // consider external values passed for recording transaction entry
3600 if (!empty($financialTrxnValues)) {
3601 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3603 if (empty($trxnParams['payment_processor_id'])) {
3604 unset($trxnParams['payment_processor_id']);
3607 $params['trxnParams'] = $trxnParams;
3609 if (!empty($params['prevContribution'])) {
3611 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3612 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3613 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3614 if (!isset($params['trxnParams']['trxn_id'])) {
3615 // Actually I have no idea why we are overwriting any values from the previous contribution.
3616 // (filling makes sense to me). However, only protecting this value as I really really know we
3617 // don't want this one overwritten.
3619 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3621 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3623 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3624 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3625 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3627 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3628 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3631 //if financial type is changed
3632 if (!empty($params['financial_type_id']) &&
3633 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3635 $accountRelationship = 'Income Account is';
3636 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3637 $accountRelationship = 'Deferred Revenue Account is';
3639 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3640 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3641 if ($oldFinancialAccount != $newFinancialAccount) {
3642 $params['total_amount'] = 0;
3643 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3644 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3645 $params['prevContribution']->financial_type_id
, $accountRelationship);
3648 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3649 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3650 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3653 self
::updateFinancialAccounts($params, 'changeFinancialType');
3654 $params['skipLineItem'] = FALSE;
3655 foreach ($params['line_item'] as &$lineItems) {
3656 foreach ($lineItems as &$line) {
3657 $line['financial_type_id'] = $params['financial_type_id'];
3660 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3661 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3662 $params['financial_account_id'] = $newFinancialAccount;
3663 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3664 self
::updateFinancialAccounts($params);
3665 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3666 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3668 $params['deferred_financial_account_id'] = $newFinancialAccount;
3672 //Update contribution status
3673 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3674 if (!isset($params['refund_trxn_id'])) {
3675 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3676 // gets preference over another so I am only 'protecting' a very specific tested flow
3677 // and letting natural justice take care of the rest.
3678 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3680 if (!empty($params['contribution_status_id']) &&
3681 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3683 //Update Financial Records
3684 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3685 if ($callUpdateFinancialAccounts) {
3686 self
::updateFinancialAccounts($params, 'changedStatus');
3687 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3692 // change Payment Instrument for a Completed contribution
3693 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3694 // instrument is null and now new payment instrument is added along with the payment
3695 if (!$params['contribution']->payment_instrument_id
) {
3696 $params['contribution']->find(TRUE);
3698 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3699 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3701 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3702 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3705 //if Change contribution amount
3706 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3707 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3708 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3709 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3710 if (isset($totalAmount) &&
3711 $totalAmount != $params['prevContribution']->total_amount
3713 //Update Financial Records
3714 $params['trxnParams']['from_financial_account_id'] = NULL;
3715 self
::updateFinancialAccounts($params, 'changedAmount');
3716 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3721 // Looks like we might have a data correction update.
3722 // This would be a case where a transaction id has been entered but it is incorrect &
3723 // the person goes back in & fixes it, as opposed to a new transaction.
3724 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3725 // the data fix scenario.
3727 if (isset($params['refund_trxn_id'])) {
3728 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3729 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3730 civicrm_api3('FinancialTrxn', 'create', [
3731 'id' => $refundIDs['financialTrxnId'],
3732 'trxn_id' => $params['refund_trxn_id'],
3736 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3737 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3738 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3743 // records finanical trxn and entity financial trxn
3744 // also make it available as return value
3745 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3746 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3747 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3748 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3749 $params['entity_id'] = $financialTxn->id
;
3750 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3751 self
::$_trxnIDs[] = $financialTxn->id
;
3755 // record line items and financial items
3756 if (empty($params['skipLineItem'])) {
3757 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3760 // create batch entry if batch_id is passed and
3761 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3762 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3764 'batch_id' => $params['batch_id'],
3765 'entity_table' => 'civicrm_financial_trxn',
3766 'entity_id' => $financialTxn->id
,
3768 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3771 // when a fee is charged
3772 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3773 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3776 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3777 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3779 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3780 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3781 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3783 unset($params['line_item']);
3784 self
::$_trxnIDs = NULL;
3789 * Update all financial accounts entry.
3791 * @param array $params
3792 * Contribution object, line item array and params for trxn.
3794 * @param string $context
3797 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3798 * adds unpredictability.
3801 public static function updateFinancialAccounts(&$params, $context = NULL) {
3803 $inputParams = $params;
3804 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3806 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3807 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3808 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3811 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3812 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3813 $params['entity_id'] = $trxn->id
;
3815 $itemParams['entity_table'] = 'civicrm_line_item';
3816 $trxnIds['id'] = $params['entity_id'];
3817 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3818 foreach ($params['line_item'] as $fieldId => $fields) {
3819 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3824 * Is this contribution status a reversal.
3826 * If so we would expect to record a negative value in the financial_trxn table.
3828 * @param int $status_id
3832 public static function isContributionStatusNegative($status_id) {
3833 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3834 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3838 * Check status validation on update of a contribution.
3840 * @param array $values
3841 * Previous form values before submit.
3843 * @param array $fields
3844 * The input form values.
3846 * @param array $errors
3851 public static function checkStatusValidation($values, &$fields, &$errors) {
3852 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3853 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3854 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3858 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3860 'Cancelled' => ['Completed', 'Refunded'],
3861 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3862 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3863 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3864 'Refunded' => ['Cancelled', 'Completed'],
3865 'Partially paid' => ['Completed'],
3866 'Pending refund' => ['Completed', 'Refunded'],
3869 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3870 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3872 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3873 1 => $contributionStatuses[$values['contribution_status_id']],
3874 2 => $contributionStatuses[$fields['contribution_status_id']],
3880 * Delete contribution of contact.
3884 * @param int $contactId
3888 public static function deleteContactContribution($contactId) {
3889 $contribution = new CRM_Contribute_DAO_Contribution();
3890 $contribution->contact_id
= $contactId;
3891 $contribution->find();
3892 while ($contribution->fetch()) {
3893 self
::deleteContribution($contribution->id
);
3898 * Get options for a given contribution field.
3900 * @param string $fieldName
3901 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3902 * @param array $props whatever is known about this dao object.
3904 * @return array|bool
3905 * @see CRM_Core_DAO::buildOptions
3908 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3909 $className = __CLASS__
;
3911 if (isset($props['orderColumn'])) {
3912 $params['orderColumn'] = $props['orderColumn'];
3914 switch ($fieldName) {
3915 // This field is not part of this object but the api supports it
3916 case 'payment_processor':
3917 $className = 'CRM_Contribute_BAO_ContributionPage';
3918 // Filter results by contribution page
3919 if (!empty($props['contribution_page_id'])) {
3920 $page = civicrm_api('contribution_page', 'getsingle', [
3922 'id' => ($props['contribution_page_id']),
3924 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3925 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3929 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3930 case 'honor_type_id':
3931 $className = 'CRM_Contribute_BAO_ContributionSoft';
3932 $fieldName = 'soft_credit_type_id';
3933 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3936 case 'contribution_status_id':
3937 if ($context !== 'validate') {
3938 $params['condition'] = "v.name <> 'Template'";
3941 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3945 * Validate financial type.
3949 * @param int $financialTypeId
3950 * Financial Type id.
3952 * @param string $relationName
3954 * @return array|bool
3956 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3957 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3959 if (!$financialAccount) {
3960 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3966 * @param int $targetCid
3967 * @param $activityType
3968 * @param string $title
3969 * @param int $contributionId
3970 * @param string $totalAmount
3971 * @param string $currency
3972 * @param string $trxn_date
3974 * @throws \CRM_Core_Exception
3975 * @throws \CiviCRM_API3_Exception
3977 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3978 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3979 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3980 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3981 // source record id would be the contribution id
3982 $srcRecId = $contributionId;
3986 'source_contact_id' => $targetCid,
3987 'source_record_id' => $srcRecId,
3988 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3989 'subject' => $subject,
3990 'activity_date_time' => $date,
3991 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3992 'skipRecentView' => TRUE,
3995 // create activity with target contacts
3996 $session = CRM_Core_Session
::singleton();
3997 $id = $session->get('userID');
3999 $activityParams['source_contact_id'] = $id;
4000 $activityParams['target_contact_id'][] = $targetCid;
4002 civicrm_api3('Activity', 'create', $activityParams);
4006 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4010 * @param bool $getTrxnInfo
4011 * @param bool $usingLineTotal
4015 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4016 // @todo deprecate passing in component - always call with contribution.
4017 if ($component == 'event') {
4018 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4020 if (!$contributionId) {
4021 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4022 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4023 $id = $primaryParticipantId;
4025 if (!$contributionId) {
4030 elseif ($component == 'membership') {
4031 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4034 $contributionId = $id;
4037 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4038 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4040 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4041 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4043 if (empty($total['total_amount']) ||
$usingLineTotal) {
4044 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4047 $baseTrxnId = $total['trxn_id'];
4048 $total = $total['total_amount'];
4051 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4053 $contribution = civicrm_api3('Contribution', 'getsingle', [
4054 'id' => $contributionId,
4058 'contribution_status_id',
4059 'financial_type_id',
4063 $info['payLater'] = $contribution['is_pay_later'];
4064 $info['contribution_status'] = $contribution['contribution_status'];
4065 $info['currency'] = $contribution['currency'];
4067 $financialTypeId = $contribution['financial_type_id'];
4068 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4070 $info['total'] = $total;
4071 $info['paid'] = $total - $paymentBalance;
4072 $info['balance'] = $paymentBalance;
4074 $info['component'] = $component;
4076 if ($getTrxnInfo && $baseTrxnId) {
4077 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4079 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4081 ft.payment_instrument_id,
4082 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4084 FROM civicrm_contribution con
4085 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4086 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4087 AND ft.to_financial_account_id != %2
4088 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4089 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4090 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4092 WHERE con.id = %1 AND ft.is_payment = 1
4095 1 => [$contributionId, 'Integer'],
4096 2 => [$feeFinancialAccount, 'Integer'],
4098 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4099 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
4101 while ($resultDAO->fetch()) {
4102 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4103 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4104 if ($resultDAO->card_type_id
) {
4105 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4106 $pantruncation = '';
4107 if ($resultDAO->pan_truncation
) {
4108 $pantruncation = ": {$resultDAO->pan_truncation}";
4110 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4113 // show payment edit link only for payments done via backoffice form
4114 $paymentEditLink = '';
4115 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4117 CRM_Core_Action
::UPDATE
=> [
4118 'name' => "<i class='crm-i fa-pencil'></i>",
4119 'url' => 'civicrm/payment/edit',
4120 'class' => 'medium-popup',
4121 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4122 'title' => ts('Edit Payment'),
4125 $paymentEditLink = CRM_Core_Action
::formLink(
4127 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4129 'id' => $resultDAO->id
,
4130 'contribution_id' => $contributionId,
4136 'id' => $resultDAO->id
,
4137 'total_amount' => $resultDAO->total_amount
,
4138 'financial_type' => $resultDAO->financial_account
,
4139 'payment_instrument' => $paidByLabel,
4140 'receive_date' => $resultDAO->trxn_date
,
4141 'trxn_id' => $resultDAO->trxn_id
,
4142 'status' => $statuses[$resultDAO->status_id
],
4143 'currency' => $resultDAO->currency
,
4144 'action' => $paymentEditLink,
4146 if ($paidByName == 'Check') {
4147 $val['check_number'] = $resultDAO->check_number
;
4151 $info['transaction'] = $rows;
4154 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4159 * Get the outstanding balance on a contribution.
4161 * @param int $contributionId
4162 * @param float $contributionTotal
4163 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4167 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4168 if ($contributionTotal === NULL) {
4169 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4172 return (float) CRM_Utils_Money
::subtractCurrencies(
4174 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE) ?
: 0,
4175 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4180 * Get the tax amount (misnamed function).
4182 * @param array $params
4183 * @param bool $isLineItem
4187 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4188 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4190 // This function should be only called after standardisation (removal of
4191 // thousand separator & using a decimal point for cents separator.
4192 // However, we don't know if that is always true :-(
4193 // There is a deprecation notice tho :-)
4194 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4195 // Update contribution.
4196 if (!empty($params['id'])) {
4197 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4198 // there are no tax implications - early return.
4199 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4202 if (empty($params['prevContribution'])) {
4203 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4206 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4207 if (!isset($params[$field])) {
4208 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4209 // Tax amount gets added back on later....
4210 $params['total_amount'] = $params['prevContribution']->total_amount
-
4211 $params['prevContribution']->tax_amount
;
4214 $params[$field] = $params['prevContribution']->$field;
4215 if ($params[$field] != $params['prevContribution']->$field) {
4221 self
::calculateMissingAmountParams($params, $params['id']);
4222 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4223 // Assign tax Amount on update of contribution
4224 if (!empty($params['prevContribution']->tax_amount
)) {
4225 $params['tax_amount'] = 'null';
4226 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4227 foreach ($params['line_item'] as $setID => $priceField) {
4228 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4229 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4236 // New Contribution and update of contribution with tax rate financial type
4237 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4238 empty($params['skipLineItem']) && !$isLineItem
4240 $taxRateParams = $taxRates[$params['financial_type_id']];
4241 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4242 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4244 // Get Line Item on update of contribution
4245 if (isset($params['id'])) {
4246 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4249 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4251 foreach ($params['line_item'] as $setID => $priceField) {
4252 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4253 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4256 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4258 elseif (isset($params['api.line_item.create'])) {
4259 // Update total amount of contribution using lineItem
4260 $taxAmountArray = [];
4261 foreach ($params['api.line_item.create'] as $key => $value) {
4262 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4263 $taxRate = $taxRates[$value['financial_type_id']];
4264 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4265 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4268 $params['tax_amount'] = array_sum($taxAmountArray);
4269 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4272 // update line item of contrbution
4273 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4274 $taxRate = $taxRates[$params['financial_type_id']];
4275 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4276 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4283 * Check financial type validation on update of a contribution.
4285 * @param int $financialTypeId
4286 * Value of latest Financial Type.
4288 * @param int $contributionId
4291 * @param array $errors
4296 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4297 if (!empty($financialTypeId)) {
4298 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4299 if ($oldFinancialTypeId == $financialTypeId) {
4303 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4305 '1' => [$contributionId, 'Integer'],
4307 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4308 if ($result->N
> 1) {
4309 $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.');
4314 * Update related pledge payment payments.
4316 * This function has been refactored out of the back office contribution form and may
4317 * still overlap with other functions.
4319 * @param string $action
4320 * @param int $pledgePaymentID
4321 * @param int $contributionID
4322 * @param bool $adjustTotalAmount
4323 * @param float $total_amount
4324 * @param float $original_total_amount
4325 * @param int $contribution_status_id
4326 * @param int $original_contribution_status_id
4328 public static function updateRelatedPledge(
4334 $original_total_amount,
4335 $contribution_status_id,
4336 $original_contribution_status_id
4338 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4342 if ($pledgePaymentID) {
4343 //store contribution id in payment record.
4344 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4347 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4354 if (!$pledgePaymentID) {
4357 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4363 $updatePledgePaymentStatus = FALSE;
4365 // If either the status or the amount has changed we update the pledge status.
4366 if ($action & CRM_Core_Action
::ADD
) {
4367 $updatePledgePaymentStatus = TRUE;
4369 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4370 ($original_total_amount != $total_amount))
4372 $updatePledgePaymentStatus = TRUE;
4375 if ($updatePledgePaymentStatus) {
4376 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4378 $contribution_status_id,
4387 * Compute the stats values
4389 * @param string $stat either 'mode' or 'median'
4390 * @param string $sql
4391 * @param string $alias of civicrm_contribution
4393 * @return array|null
4397 public static function computeStats($stat, $sql, $alias = NULL) {
4398 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4403 * Is there only one line item attached to the contribution.
4409 * @throws \CiviCRM_API3_Exception
4411 public static function isSingleLineItem($id) {
4412 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4413 return ($lineItemCount == 1);
4417 * Complete an order.
4419 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4421 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4423 * Moving it out of the BaseIPN class is just the first step.
4425 * @param array $input
4427 * @param array $objects
4428 * @param CRM_Core_Transaction $transaction
4429 * @param CRM_Contribute_BAO_Contribution $contribution
4430 * @param bool $isPostPaymentCreate
4431 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4432 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4433 * transitioning related elements).
4436 * @throws \CRM_Core_Exception
4437 * @throws \CiviCRM_API3_Exception
4439 public static function completeOrder($input, &$ids, $objects, $transaction, $contribution, $isPostPaymentCreate = FALSE) {
4440 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4441 // The previous details are used when calculating line items so keep it before any code that 'does something'
4442 if (!empty($contribution->id
)) {
4443 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4445 $inputContributionWhiteList = [
4450 'payment_instrument_id',
4455 'contribution_status_id',
4459 if (self
::isSingleLineItem($primaryContributionID)) {
4460 $inputContributionWhiteList[] = 'financial_type_id';
4463 $participant = CRM_Utils_Array
::value('participant', $objects);
4464 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4465 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4466 $event = CRM_Utils_Array
::value('event', $objects);
4468 $paymentProcessorId = '';
4469 if (isset($objects['paymentProcessor'])) {
4470 if (is_array($objects['paymentProcessor'])) {
4471 $paymentProcessorId = $objects['paymentProcessor']['id'];
4474 $paymentProcessorId = $objects['paymentProcessor']->id
;
4478 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4480 $contributionParams = array_merge([
4481 'contribution_status_id' => $completedContributionStatusID,
4482 'source' => self
::getRecurringContributionDescription($contribution, $event),
4483 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4486 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4487 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4488 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4491 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4493 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4494 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4495 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4496 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4499 if ($recurringContributionID) {
4500 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4502 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4504 if (empty($contributionParams['receive_date']) && $changeDate) {
4505 $contributionParams['receive_date'] = $changeDate;
4508 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4509 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4512 if (isset($input['is_email_receipt'])) {
4513 $values['is_email_receipt'] = $input['is_email_receipt'];
4516 if ($input['component'] == 'contribute') {
4517 if ($contribution->contribution_page_id
) {
4518 // Figure out what we gain from this.
4519 // Note that we may have overwritten the is_email_receipt input, fix that below.
4520 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4522 elseif ($recurContrib && $recurringContributionID) {
4523 $values['amount'] = $recurContrib->amount
;
4524 $values['financial_type_id'] = $objects['contributionType']->id
;
4525 $values['title'] = $source = ts('Offline Recurring Contribution');
4528 if (isset($input['is_email_receipt'])) {
4529 // CRM-19601 - we may have overwritten this above.
4530 $values['is_email_receipt'] = $input['is_email_receipt'];
4532 elseif ($recurContrib && $recurringContributionID) {
4533 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4534 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4535 // 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
4536 // Instance that had the table added via an upgrade in 4.1
4537 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4538 // https://lab.civicrm.org/dev/core/issues/1245
4539 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4542 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4543 self
::updateMembershipBasedOnCompletionOfContribution(
4545 $primaryContributionID,
4551 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4552 if ($event->is_email_confirm
) {
4553 // @todo this should be set by the function that sends the mail after sending.
4554 $contributionParams['receipt_date'] = $changeDate;
4556 $participantParams['id'] = $participant->id
;
4557 $participantParams['status_id'] = 'Registered';
4558 civicrm_api3('Participant', 'create', $participantParams);
4562 $contributionParams['id'] = $contribution->id
;
4563 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4565 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4566 // unsetting it here does NOT cause any other contribution test to fail!
4567 unset($contributionParams['financial_type_id']);
4568 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4570 // Add new soft credit against current $contribution.
4571 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4572 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4575 if (empty($contribution->_relatedObjects
['participant']) && !empty($contribution->_relatedObjects
['membership'])) {
4576 // @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.
4577 // @todo - use getRelatedMemberships instead
4578 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4579 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4580 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4583 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4584 $transaction->commit();
4586 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4587 $contributionParams['contribution_status_id'], $input['amount']);
4589 // create an activity record
4590 if ($input['component'] == 'contribute') {
4592 $targetContactID = NULL;
4593 if (!empty($ids['related_contact'])) {
4594 $targetContactID = $contribution->contact_id
;
4595 $contribution->contact_id
= $ids['related_contact'];
4597 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4600 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4601 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4602 if (!array_key_exists('is_email_receipt', $values) ||
4603 $values['is_email_receipt'] == 1
4605 civicrm_api3('Contribution', 'sendconfirmation', [
4606 'id' => $contribution->id
,
4607 'payment_processor_id' => $paymentProcessorId,
4609 CRM_Core_Error
::debug_log_message("Receipt sent");
4612 CRM_Core_Error
::debug_log_message("Success: Database updated");
4613 return $contributionResult;
4617 * Send receipt from contribution.
4619 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4621 * Note that the compose message part has been moved to contribution
4622 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4624 * @param array $input
4625 * Incoming data from Payment processor.
4627 * Related object IDs.
4628 * @param int $contributionID
4629 * @param array $values
4630 * Values related to objects that have already been loaded.
4631 * @param bool $returnMessageText
4632 * Should text be returned instead of sent. This.
4633 * is because the function is also used to generate pdfs
4636 * @throws \CRM_Core_Exception
4637 * @throws \CiviCRM_API3_Exception
4638 * @throws \Exception
4640 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4641 $returnMessageText = FALSE) {
4643 $contribution = new CRM_Contribute_BAO_Contribution();
4644 $contribution->id
= $contributionID;
4645 if (!$contribution->find(TRUE)) {
4646 throw new CRM_Core_Exception('Contribution does not exist');
4648 $contribution->loadRelatedObjects($input, $ids, TRUE);
4649 // set receipt from e-mail and name in value
4650 if (!$returnMessageText) {
4651 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4653 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4654 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4655 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4656 civicrm_api3('Contribution', 'create', [
4657 'receipt_date' => 'now',
4658 'id' => $contribution->id
,
4665 * Generate From email and from name in an array values
4667 * @param array $input
4668 * @param \CRM_Contribute_BAO_Contribution $contribution
4672 public static function generateFromEmailAndName($input, $contribution) {
4673 // Use input value if supplied.
4674 if (!empty($input['receipt_from_email'])) {
4676 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4677 $input['receipt_from_email'],
4680 // if we are still empty see if we can use anything from a contribution page.
4682 if (!empty($contribution->contribution_page_id
)) {
4683 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4685 // if we are still empty see if we can use anything from a contribution page.
4686 if (!empty($pageValues['receipt_from_email'])) {
4688 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4689 $pageValues['receipt_from_email'],
4692 // If we are still empty fall back to the domain or logged in user information.
4693 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4697 * Generate credit note id with next avaible number
4702 public static function createCreditNoteId() {
4703 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4705 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4706 $creditNoteId = NULL;
4710 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4711 $result = civicrm_api3('Contribution', 'getcount', [
4713 'creditnote_id' => $creditNoteId,
4715 } while ($result > 0);
4717 return $creditNoteId;
4721 * Load related memberships.
4725 * @return array $ids
4730 * Note that in theory it should be possible to retrieve these from the line_item table
4731 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4732 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4733 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4734 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4736 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4739 public function loadRelatedMembershipObjects($ids = []) {
4741 SELECT membership_id
4742 FROM civicrm_membership_payment
4743 WHERE contribution_id = %1 ";
4744 $params = [1 => [$this->id
, 'Integer']];
4745 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4747 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4748 while ($dao->fetch()) {
4749 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4750 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4754 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4755 foreach ($ids['membership'] as $id) {
4757 $membership = new CRM_Member_BAO_Membership();
4758 $membership->id
= $id;
4759 if (!$membership->find(TRUE)) {
4760 throw new Exception("Could not find membership record: $id");
4762 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4763 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4764 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4765 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4773 * This function is used to record partial payments for contribution
4775 * @param array $contribution
4777 * @param array $params
4779 * @return CRM_Financial_DAO_FinancialTrxn
4781 public static function recordPartialPayment($contribution, $params) {
4782 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4783 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4784 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4785 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4786 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4787 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4788 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4789 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4790 $balanceTrxnParams['currency'] = $contribution['currency'];
4791 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4792 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4793 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4794 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4795 $balanceTrxnParams['is_payment'] = 1;
4797 if (!empty($params['payment_processor'])) {
4798 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4799 // also anticipates it.
4800 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4801 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4803 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4807 * Get the description (source field) for the recurring contribution.
4809 * @param CRM_Contribute_BAO_Contribution $contribution
4810 * @param CRM_Event_DAO_Event|null $event
4813 * @throws \CiviCRM_API3_Exception
4815 protected static function getRecurringContributionDescription($contribution, $event) {
4816 if (!empty($contribution->source
)) {
4817 return $contribution->source
;
4819 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4820 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4821 'id' => $contribution->contribution_page_id
,
4822 'return' => 'title',
4824 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4827 return ts('Online Event Registration') . ': ' . $event->title
;
4829 elseif (!empty($contribution->contribution_recur_id
)) {
4830 return 'recurring contribution';
4836 * Function to add payments for contribution for Partially Paid status
4838 * @deprecated this is known to be flawed and possibly buggy.
4840 * Replace with Order.create->Payment.create flow.
4842 * @param array $contributions
4843 * @param string $contributionStatusId
4845 * @throws \CiviCRM_API3_Exception
4847 public static function addPayments($contributions, $contributionStatusId = NULL) {
4848 // get financial trxn which is a payment
4849 $ftSql = "SELECT ft.id, ft.total_amount
4850 FROM civicrm_financial_trxn ft
4851 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4852 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4853 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4854 'labelColumn' => 'name',
4856 foreach ($contributions as $contribution) {
4857 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4858 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4862 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, [
4870 // store financial item Proportionaly.
4872 'total_amount' => $ftDao->total_amount
,
4873 'contribution_id' => $contribution->id
,
4875 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4880 * Function use to store line item proportionally in in entity financial trxn table
4882 * @param array $trxnParams
4884 * @param int $trxnId
4886 * @param float $contributionTotalAmount
4888 * @throws \CiviCRM_API3_Exception
4890 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4891 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4892 if (!empty($lineItems)) {
4893 // get financial item
4894 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4896 'contribution_total_amount' => $contributionTotalAmount,
4897 'trxn_total_amount' => $trxnParams['total_amount'],
4898 'trxn_id' => $trxnId,
4900 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4905 * Checks if line items total amounts
4906 * match the contribution total amount.
4908 * @param array $params
4909 * array of order params.
4911 * @throws \API_Exception
4913 public static function checkLineItems(&$params) {
4914 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4915 $lineItemAmount = 0;
4917 foreach ($params['line_items'] as &$lineItems) {
4918 foreach ($lineItems['line_item'] as &$item) {
4919 if (empty($item['financial_type_id'])) {
4920 $item['financial_type_id'] = $params['financial_type_id'];
4922 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4926 if (!isset($totalAmount)) {
4927 $params['total_amount'] = $lineItemAmount;
4930 $currency = CRM_Utils_Array
::value('currency', $params, '');
4932 if (empty($currency)) {
4933 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4936 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4937 throw new CRM_Contribute_Exception_CheckLineItemsException();
4943 * Get the financial account for the item associated with the new transaction.
4945 * @param array $params
4946 * @param int $default
4950 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4952 if (!empty($params['financial_account_id'])) {
4953 return $params['financial_account_id'];
4956 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4957 $preferredAccountsRelationships = [
4958 'Refunded' => 'Credit/Contra Revenue Account is',
4959 'Chargeback' => 'Chargeback Account is',
4962 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4963 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4964 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4966 $preferredAccountsRelationships[$contributionStatus]
4974 * ContributionPage values were being imposed onto values.
4976 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4977 * REALLY didn't want superimposed. The rest are left there in their overkill out
4980 * The rationale for making this explicit is that it was a case of carefully set values being
4981 * seemingly randonly overwritten without much care. In general I think array randomly setting
4982 * variables en mass is risky.
4984 * @param array $values
4988 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4989 $contributionPageValues = [];
4990 CRM_Contribute_BAO_ContributionPage
::setValues(
4991 $this->contribution_page_id
,
4992 $contributionPageValues
4995 // These are the values that I believe to be useful.
4998 'pay_later_receipt',
5000 'receipt_from_email',
5001 'receipt_from_name',
5005 'honoree_profile_id',
5006 'onbehalf_profile_id',
5007 'honor_block_is_active',
5008 // Kinda might be - but would be on the contribution...
5011 // Included for 'fear of regression' but can't justify any use for these....
5013 'payment_processor',
5014 'financial_type_id',
5015 'amount_block_is_active',
5020 'default_amount_id',
5024 'initial_amount_help_text',
5025 'initial_amount_label',
5027 'is_allow_other_amount',
5028 'is_billing_required',
5029 'is_confirm_enabled',
5030 'is_credit_card_only',
5032 'is_partial_payment',
5033 'is_recur_installments',
5034 'is_recur_interval',
5038 'min_initial_amount',
5039 'recur_frequency_unit',
5046 foreach ($valuesToCopy as $valueToCopy) {
5047 if (isset($contributionPageValues[$valueToCopy])) {
5048 if ($valueToCopy === 'title') {
5049 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
5052 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5060 * Get values of CiviContribute Settings
5061 * and check if its enabled or not.
5062 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5063 * in serialized form. Usually this should be stored as flat settings for each form fields
5064 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5065 * settings we will live with an inconsistency because it's too hard to change for now.
5066 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5069 * @param string $name
5070 * @param bool $checkInvoicing
5074 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5075 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5077 if ($checkInvoicing && empty($contributeSettings['invoicing'])) {
5082 return CRM_Utils_Array
::value($name, $contributeSettings);
5084 return $contributeSettings;
5088 * This function process contribution related objects.
5090 * @param int $contributionId
5091 * @param int $statusId
5092 * @param int|null $previousStatusId
5094 * @param string $receiveDate
5096 * @return null|string
5098 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5100 if (!$contributionId ||
!$statusId) {
5105 'contribution_id' => $contributionId,
5106 'contribution_status_id' => $statusId,
5107 'previous_contribution_status_id' => $previousStatusId,
5108 'receive_date' => $receiveDate,
5111 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5113 if (!is_array($updateResult) ||
5114 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5115 !is_array($updatedComponents) ||
5116 empty($updatedComponents)
5121 // get the user display name.
5123 SELECT display_name as displayName
5124 FROM civicrm_contact
5125 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5126 WHERE civicrm_contribution.id = {$contributionId}";
5127 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5129 // get the status message for user.
5130 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5132 if ($componentName == 'CiviMember') {
5133 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5134 CRM_Member_PseudoConstant
::membershipStatus()
5137 $statusNameMsgPart = 'updated';
5138 switch ($updatedStatusName) {
5141 $statusNameMsgPart = $updatedStatusName;
5145 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5146 1 => $userDisplayName,
5147 2 => $statusNameMsgPart,
5151 if ($componentName == 'CiviEvent') {
5152 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5153 CRM_Event_PseudoConstant
::participantStatus()
5155 if ($updatedStatusName == 'Cancelled') {
5156 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5158 elseif ($updatedStatusName == 'Registered') {
5159 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5163 if ($componentName == 'CiviPledge') {
5164 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5165 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5167 if ($updatedStatusName == 'Cancelled') {
5168 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5170 elseif ($updatedStatusName == 'Failed') {
5171 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5173 elseif ($updatedStatusName == 'Completed') {
5174 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5183 * Get the contribution as it is in the database before being updated.
5185 * @param int $contributionID
5187 * @return \CRM_Contribute_BAO_Contribution|null
5189 private static function getOriginalContribution($contributionID) {
5190 return self
::getValues(['id' => $contributionID]);
5194 * Get the amount for the financial item row.
5196 * Helper function to start to break down recordFinancialTransactions for readability.
5198 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5200 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5201 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5204 * @param array $params
5205 * Params as passed to contribution.create
5207 * @param string $context
5208 * changeFinancialType| changedAmount
5209 * @param array $lineItemDetails
5211 * @param bool $isARefund
5212 * Is this a refund / negative transaction.
5213 * @param int $previousLineItemTotal
5216 * @todo move recordFinancialAccounts & helper functions to their own class?
5219 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5220 if ($context == 'changedAmount') {
5221 $lineTotal = $lineItemDetails['line_total'];
5222 if ($lineTotal != $previousLineItemTotal) {
5223 $lineTotal -= $previousLineItemTotal;
5227 elseif ($context == 'changeFinancialType') {
5228 return -$lineItemDetails['line_total'];
5230 elseif ($context == 'changedStatus') {
5231 $cancelledTaxAmount = 0;
5233 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5235 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5237 elseif ($context === NULL) {
5238 // erm, yes because? but, hey, it's tested.
5239 return $lineItemDetails['line_total'];
5241 elseif (empty($lineItemDetails['line_total'])) {
5242 // follow legacy code path
5244 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5245 return $params['total_amount'];
5248 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5253 * Get the multiplier for adjusting rows.
5255 * If we are dealing with a refund or cancellation then it will be a negative
5256 * amount to reflect the negative transaction.
5258 * If we are changing Financial Type it will be a negative amount to
5259 * adjust down the old type.
5261 * @param int $contribution_status_id
5262 * @param string $context
5266 protected static function getMultiplier($contribution_status_id, $context) {
5267 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5274 * Does this transaction reflect a payment instrument change.
5276 * @param array $params
5277 * @param array $pendingStatuses
5281 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5282 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5284 if (array_key_exists('payment_instrument_id', $params)) {
5285 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5286 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5288 //check if status is changed from Pending to Completed
5289 // do not update payment instrument changes for Pending to Completed
5290 if (!($contributionStatus == 'Completed' &&
5291 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5296 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5297 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5298 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5302 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5303 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5305 // another special case when check number is changed, create new financial records
5306 // create financial trxn with negative amount
5314 * Update the memberships associated with a contribution if it has been completed.
5316 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5317 * load them in this function. Code clean up would compensate for any minor performance implication.
5319 * @param \CRM_Contribute_BAO_Contribution $contribution
5320 * @param int $primaryContributionID
5321 * @param string $changeDate
5323 * @throws \CRM_Core_Exception
5324 * @throws \CiviCRM_API3_Exception
5326 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5327 $memberships = self
::getRelatedMemberships($contribution->id
);
5328 foreach ($memberships as $membership) {
5329 $membershipParams = [
5330 'id' => $membership['id'],
5331 'contact_id' => $membership['contact_id'],
5332 'is_test' => $membership['is_test'],
5333 'membership_type_id' => $membership['membership_type_id'],
5334 'membership_activity_status' => 'Completed',
5337 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5338 $membershipParams['membership_type_id'],
5339 $membershipParams['is_test'],
5340 $membershipParams['id']
5343 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5344 // this picks up membership type changes during renewals
5345 // @todo this is almost certainly an obsolete sql call, the pre-change
5346 // membership is accessible via $this->_relatedObjects
5348 SELECT membership_type_id
5349 FROM civicrm_membership_log
5350 WHERE membership_id={$membershipParams['id']}
5353 $dao = CRM_Core_DAO
::executeQuery($sql);
5354 if ($dao->fetch()) {
5355 if (!empty($dao->membership_type_id
)) {
5356 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5359 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5360 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5361 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5362 // 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.
5363 // @todo once apiv4 ships with core switch to that & find sanity.
5364 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5365 $membershipParams['membership_type_id'],
5366 $primaryContributionID
5369 // @todo remove all this stuff in favour of letting the api call further down handle in
5370 // (it is a duplication of what the api does).
5371 $dates = array_fill_keys([
5376 if ($currentMembership) {
5378 * Fixed FOR CRM-4433
5379 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5380 * when Contribution mode is notify and membership is for renewal )
5382 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5384 // @todo - we should pass membership_type_id instead of null here but not
5385 // adding as not sure of testing
5386 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5387 $changeDate, NULL, $membershipParams['num_terms']
5389 $dates['join_date'] = $currentMembership['join_date'];
5392 //get the status for membership.
5393 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5395 $dates['join_date'],
5398 $membershipParams['membership_type_id'],
5402 unset($dates['end_date']);
5403 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5404 //we might be renewing membership,
5405 //so make status override false.
5406 $membershipParams['is_override'] = FALSE;
5407 $membershipParams['status_override_end_date'] = 'null';
5409 //CRM-17723 - reset static $relatedContactIds array()
5410 // @todo move it to Civi Statics.
5412 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5413 civicrm_api3('Membership', 'create', $membershipParams);
5418 * Get payment links as they relate to a contribution.
5420 * If a payment can be made then include a payment link & if a refund is appropriate
5421 * then a refund link.
5424 * @param float $balance
5425 * @param string $contributionStatus
5428 * $actionLinks Links array containing:
5432 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5433 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5434 // In general the balance is the best way to determine if a payment can be added or not,
5435 // but not for Failed contributions, where we don't accept additional payments at the moment.
5436 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5437 // do accept more payments agains them.
5441 if ((int) $balance > 0) {
5442 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5444 'url' => CRM_Utils_System
::url('civicrm/payment', [
5450 'title' => ts('Submit Credit Card payment'),
5454 'url' => CRM_Utils_System
::url('civicrm/payment', [
5459 'title' => ts('Record Payment'),
5462 elseif ((int) $balance < 0) {
5464 'url' => CRM_Utils_System
::url('civicrm/payment', [
5469 'title' => ts('Record Refund'),
5472 return $actionLinks;
5476 * Get a query to determine the amount donated by the contact/s in the current financial year.
5478 * @param array $contactIDs
5482 public static function getAnnualQuery($contactIDs) {
5483 $contactIDs = implode(',', $contactIDs);
5484 $config = CRM_Core_Config
::singleton();
5485 $currentMonth = date('m');
5486 $currentDay = date('d');
5488 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5490 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5491 (int) $config->fiscalYearStart
['d'] > $currentDay
5494 $year = date('Y') - 1;
5499 $nextYear = $year +
1;
5501 if ($config->fiscalYearStart
) {
5502 $newFiscalYearStart = $config->fiscalYearStart
;
5503 if ($newFiscalYearStart['M'] < 10) {
5504 // This is just a clumsy way of adding padding.
5505 // @todo next round look for a nicer way.
5506 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5508 if ($newFiscalYearStart['d'] < 10) {
5509 // This is just a clumsy way of adding padding.
5510 // @todo next round look for a nicer way.
5511 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5513 $config->fiscalYearStart
= $newFiscalYearStart;
5514 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5517 // First of January.
5520 $startDate = "$year$monthDay";
5521 $endDate = "$nextYear$monthDay";
5524 'contact_id' => 'IN (' . $contactIDs . ')',
5525 'is_test' => ' = 0',
5526 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5528 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5529 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5532 foreach ($whereClauses as $key => $clause) {
5533 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5535 $whereClauseString = implode(' AND ', $clauses);
5537 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5538 // this group by + having on contribution_status_id improves performance
5540 SELECT COUNT(*) as count,
5541 SUM(total_amount) as amount,
5542 AVG(total_amount) as average,
5544 FROM civicrm_contribution b
5545 WHERE " . $whereClauseString . "
5546 GROUP BY currency, contribution_status_id
5547 HAVING $havingClause
5553 * Assign Test Value.
5555 * @param string $fieldName
5556 * @param array $fieldDef
5557 * @param int $counter
5559 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5560 if ($fieldName == 'tax_amount') {
5561 $this->{$fieldName} = "0.00";
5563 elseif ($fieldName == 'net_amount') {
5564 $this->{$fieldName} = "2.00";
5566 elseif ($fieldName == 'total_amount') {
5567 $this->{$fieldName} = "3.00";
5569 elseif ($fieldName == 'fee_amount') {
5570 $this->{$fieldName} = "1.00";
5573 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5578 * Check if contribution has participant/membership payment.
5580 * @param int $contributionId
5585 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5586 // get line item for contribution
5587 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5588 // check if line item is for membership or participant
5589 foreach ($lineItems as $items) {
5590 if ($items['entity_table'] == 'civicrm_participant') {
5594 elseif ($items['entity_table'] == 'civicrm_membership') {
5606 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5608 * @param array $trxnParams
5609 * Financial trxn params
5610 * @param array $contributionParams
5611 * Contribution Params
5615 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5616 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5619 $statusId = $contributionParams['contribution']->contribution_status_id
;
5620 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5621 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5622 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5623 // Return if contribution status is not completed.
5624 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5625 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5626 && $contributionParams['prevContribution']->is_pay_later
== 0
5632 $params = $trxnParams;
5633 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5634 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5635 $params['to_financial_account_id'] = $arAccountId;
5636 $params['status_id'] = array_search('Pending', $contributionStatuses);
5637 $params['is_payment'] = FALSE;
5638 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5639 self
::$_trxnIDs[] = $trxn->id
;
5640 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5644 * Calculate financial item amount when contribution is updated.
5646 * @param array $params
5647 * contribution params
5648 * @param array $amountParams
5650 * @param string $context
5654 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5655 if (!empty($params['is_quick_config'])) {
5656 $amount = $amountParams['item_amount'];
5658 $amount = $params['total_amount'];
5659 if ($context === NULL) {
5660 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5665 $amount = $amountParams['line_total'];
5666 if ($context == 'changedAmount') {
5667 $amount -= $amountParams['previous_line_total'];
5669 $amount *= $amountParams['diff'];
5675 * Retrieve Sales Tax Financial Accounts.
5681 public static function getSalesTaxFinancialAccounts() {
5682 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5683 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5684 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5685 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5686 $queryParams = [1 => [$accountRel, 'Integer']];
5687 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5688 $financialAccount = [];
5689 while ($dao->fetch()) {
5690 $financialAccount[$dao->id
] = $dao->id
;
5692 return $financialAccount;
5696 * Create tax entry in civicrm_entity_financial_trxn table.
5698 * @param array $entityParams
5700 * @param array $eftParams
5702 * @throws \CiviCRM_API3_Exception
5704 public static function createProportionalEntry($entityParams, $eftParams) {
5706 if ($entityParams['contribution_total_amount'] != 0) {
5707 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5709 // Record Entity Financial Trxn; CRM-20145
5710 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5711 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5715 * Create array of last financial item id's.
5717 * @param int $contributionId
5721 public static function getLastFinancialItemIds($contributionId) {
5722 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5723 FROM civicrm_financial_item fi
5724 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5725 WHERE li.contribution_id = %1";
5726 $dao = CRM_Core_DAO
::executeQuery($sql, [
5732 $ftIds = $taxItems = [];
5733 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5734 while ($dao->fetch()) {
5735 /* if sales tax item*/
5736 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5737 $taxItems[$dao->price_field_value_id
] = [
5738 'financial_item_id' => $dao->id
,
5739 'amount' => $dao->tax_amount
,
5743 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5746 return [$ftIds, $taxItems];
5750 * Create proportional entries in civicrm_entity_financial_trxn.
5752 * @param array $entityParams
5754 * @param array $lineItems
5756 * @param array $ftIds
5758 * @param array $taxItems
5760 * @throws \CiviCRM_API3_Exception
5762 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5764 'entity_table' => 'civicrm_financial_item',
5765 'financial_trxn_id' => $entityParams['trxn_id'],
5767 foreach ($lineItems as $key => $value) {
5768 if ($value['qty'] == 0) {
5771 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5772 $entityParams['line_item_amount'] = $value['line_total'];
5773 self
::createProportionalEntry($entityParams, $eftParams);
5774 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5775 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5776 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5777 self
::createProportionalEntry($entityParams, $eftParams);
5783 * Load entities related to the contribution into $this->_relatedObjects.
5787 * @throws \CRM_Core_Exception
5789 protected function loadRelatedEntitiesByID($ids) {
5791 'contact' => 'CRM_Contact_BAO_Contact',
5792 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5793 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5794 'financialType' => 'CRM_Financial_BAO_FinancialType',
5795 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5797 foreach ($entities as $entity => $bao) {
5798 if (!empty($ids[$entity])) {
5799 $this->_relatedObjects
[$entity] = new $bao();
5800 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5801 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5802 throw new CRM_Core_Exception($entity . ' could not be loaded');
5809 * Should an email receipt be sent for this contribution when complete.
5811 * @param array $input
5815 protected function isEmailReceipt($input) {
5816 if (isset($input['is_email_receipt'])) {
5817 return $input['is_email_receipt'];
5819 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5820 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5826 * Function to replace contribution tokens.
5828 * @param array $contributionIds
5830 * @param string $subject
5832 * @param array $subjectToken
5834 * @param string $text
5836 * @param string $html
5838 * @param array $messageToken
5840 * @param bool $escapeSmarty
5843 * @throws \CiviCRM_API3_Exception
5845 public static function replaceContributionTokens(
5854 if (empty($contributionIds)) {
5857 $contributionDetails = [];
5858 foreach ($contributionIds as $id) {
5859 $result = self
::getContributionTokenValues($id, $messageToken);
5860 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5861 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5862 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5864 return $contributionDetails;
5868 * Get the contribution fields for $id and display labels where
5869 * appropriate (if the token is present).
5872 * @param array $messageToken
5875 public static function getContributionTokenValues($id, $messageToken) {
5879 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5880 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5881 if (!empty($messageToken)) {
5882 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5883 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5884 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5892 * Get invoice_number for contribution.
5894 * @param int $contributionID
5898 public static function getInvoiceNumber($contributionID) {
5899 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5900 return $invoicePrefix . $contributionID;
5907 * Load the values needed for the event message.
5909 * @param int $eventID
5910 * @param int $participantID
5911 * @param int|null $contributionID
5914 * @throws \CRM_Core_Exception
5916 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5921 $values = ['event' => []];
5923 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5924 // add custom fields for event
5925 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5927 $eventCustomGroup = [];
5928 foreach ($eventGroupTree as $key => $group) {
5929 if ($key === 'info') {
5933 foreach ($group['fields'] as $k => $customField) {
5934 $groupLabel = $group['title'];
5935 if (!empty($customField['customValue'])) {
5936 foreach ($customField['customValue'] as $customFieldValues) {
5937 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5942 $values['event']['customGroup'] = $eventCustomGroup;
5944 //get participant details
5945 $participantParams = [
5946 'id' => $participantID,
5949 $values['participant'] = [];
5951 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5952 // add custom fields for event
5953 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5954 $participantCustomGroup = [];
5955 foreach ($participantGroupTree as $key => $group) {
5956 if ($key === 'info') {
5960 foreach ($group['fields'] as $k => $customField) {
5961 $groupLabel = $group['title'];
5962 if (!empty($customField['customValue'])) {
5963 foreach ($customField['customValue'] as $customFieldValues) {
5964 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5969 $values['participant']['customGroup'] = $participantCustomGroup;
5971 //get location details
5973 'entity_id' => $eventID,
5974 'entity_table' => 'civicrm_event',
5976 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5979 'entity_table' => 'civicrm_event',
5980 'entity_id' => $eventID,
5981 'module' => 'CiviEvent',
5984 list($custom_pre_id,
5986 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5988 $values['custom_pre_id'] = $custom_pre_id;
5989 $values['custom_post_id'] = $custom_post_ids;
5991 // set lineItem for event contribution
5992 if ($contributionID) {
5993 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5994 if (!empty($participantIds)) {
5995 foreach ($participantIds as $pIDs) {
5996 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5997 if (!CRM_Utils_System
::isNull($lineItem)) {
5998 $values['lineItem'][] = $lineItem;