3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 public static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 public static $_exportableFields = NULL;
50 * Static field to hold financial trxn id's.
54 public static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
59 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
61 public $_relatedObjects = [];
64 * Field for the component - either 'event' (participant) or 'contribute'
65 * (any item related to a contribution page e.g. membership, pledge, contribution)
66 * This is used for composing messages because they have dependency on the
67 * contribution_page or event page - although over time we may eliminate that
69 * @var "contribution"\"event"
71 public $_component = NULL;
74 * Possibly obsolete variable.
76 * If you use it please explain why it is set in the create function here.
80 public $trxn_result_code;
85 public function __construct() {
86 parent
::__construct();
90 * Takes an associative array and creates a contribution object.
92 * the function extract all the params it needs to initialize the create a
93 * contribution object. the params array could contain additional unused name/value
96 * @param array $params
97 * (reference ) an assoc array of name/value pairs.
99 * The array that holds all the db ids.
101 * @return \CRM_Contribute_BAO_Contribution
102 * @throws \CRM_Core_Exception
103 * @throws \CiviCRM_API3_Exception
105 public static function add(&$params, $ids = []) {
106 if (empty($params)) {
109 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
110 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
112 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
113 $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)]);
114 throw new CRM_Core_Exception($message);
117 // first clean up all the money fields
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
130 // @todo put a deprecated here - this should be done in the form layer.
131 $params['skipCleanMoney'] = FALSE;
132 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
135 foreach ($moneyFields as $field) {
136 if (isset($params[$field])) {
137 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
141 //set defaults in create mode
142 if (!$contributionID) {
143 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
145 if (empty($params['invoice_number'])) {
146 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
147 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
151 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
152 //if contribution is created with cancelled or refunded status, add credit note id
153 if (!empty($params['contribution_status_id'])) {
154 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
155 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
156 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
158 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
159 $params['creditnote_id'] = self
::createCreditNoteId();
164 // Since the fee amount is expecting this (later on) ensure it is always set.
165 // It would only not be set for an update where it is unchanged.
166 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
167 'id' => $contributionID,
168 'return' => 'contribution_status_id',
173 && CRM_Utils_Array
::value('membership_id', $params)
174 && Civi
::settings()->get('deferred_revenue_enabled')
176 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
177 if ($memberStartDate) {
178 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
181 self
::calculateMissingAmountParams($params, $contributionID);
183 if (!empty($params['payment_instrument_id'])) {
184 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
185 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
186 $params['check_number'] = 'null';
190 $setPrevContribution = TRUE;
191 // CRM-13964 partial payment
192 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
193 $partialAmtTotal = $params['partial_payment_total'];
194 $partialAmtPay = $params['partial_amount_to_pay'];
195 $params['total_amount'] = $partialAmtTotal;
196 if ($partialAmtPay < $partialAmtTotal) {
197 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
198 $params['is_pay_later'] = 0;
199 $setPrevContribution = FALSE;
202 if ($contributionID && $setPrevContribution) {
203 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
206 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
207 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
208 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
210 unset($params['revenue_recognition_date']);
213 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
214 isset($params['financial_type_id']))) {
215 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
218 if ($contributionID) {
219 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
222 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
224 $contribution = new CRM_Contribute_BAO_Contribution();
225 $contribution->copyValues($params);
227 $contribution->id
= $contributionID;
229 if (empty($contribution->id
)) {
230 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
231 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
232 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
236 $result = $contribution->save();
238 // Add financial_trxn details as part of fix for CRM-4724
239 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
240 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
242 //add Account details
243 $params['contribution'] = $contribution;
244 if (empty($params['is_post_payment_create'])) {
245 // If this is being called from the Payment.create api/ BAO then that Entity
246 // takes responsibility for the financial transactions. In fact calling Payment.create
247 // to add payments & having it call completetransaction and / or contribution.create
248 // to update related entities is the preferred flow.
249 // Note that leveraging this parameter for any other code flow is not supported and
250 // is likely to break in future and / or cause serious problems in your data.
251 // https://github.com/civicrm/civicrm-core/pull/14673
252 self
::recordFinancialAccounts($params);
255 if (self
::isUpdateToRecurringContribution($params)) {
256 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
257 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
258 $contributionStatus[$params['contribution_status_id']],
259 CRM_Utils_Array
::value('receive_date', $params)
263 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
265 if ($contributionID) {
266 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
269 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
276 * Is this contribution updating an existing recurring contribution.
278 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
279 * pending payment is being confirmed (or failing).
281 * @param array $params
285 public static function isUpdateToRecurringContribution($params) {
286 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
289 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
292 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
295 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
296 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
303 * Get defaults for new entity.
307 public static function getDefaults() {
309 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
310 FALSE, FALSE, FALSE, 'AND is_default = 1')
312 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
313 'receive_date' => date('Y-m-d H:i:s'),
318 * Fetch the object and store the values in the values array.
320 * @param array $params
321 * Input parameters to find object.
322 * @param array $values
323 * Output values of the object.
325 * The array that holds all the db ids.
327 * @return CRM_Contribute_BAO_Contribution|null
328 * The found object or null
330 public static function getValues($params, &$values = [], &$ids = []) {
331 if (empty($params)) {
334 $contribution = new CRM_Contribute_BAO_Contribution();
336 $contribution->copyValues($params);
338 if ($contribution->find(TRUE)) {
339 $ids['contribution'] = $contribution->id
;
341 CRM_Core_DAO
::storeValues($contribution, $values);
343 return $contribution;
345 // return by reference
351 * Get the values and resolve the most common mappings.
353 * Since contribution status is resolved in almost every function that calls getValues it makes
354 * sense to have an extra function to resolve it rather than repeat the code.
356 * Think carefully before adding more mappings to be resolved as there could be performance implications
357 * if this function starts to be called from more iterative functions.
359 * @param array $params
360 * Input parameters to find object.
363 * Array of the found contribution.
364 * @throws CRM_Core_Exception
366 public static function getValuesWithMappings($params) {
368 $contribution = self
::getValues($params, $values, $ids);
369 if (is_null($contribution)) {
370 throw new CRM_Core_Exception('No contribution found');
372 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
377 * Calculate net_amount & fee_amount if they are not set.
379 * Net amount should be total - fee.
380 * This should only be called for new contributions.
382 * @param array $params
383 * Params for a new contribution before they are saved.
384 * @param int|null $contributionID
385 * Contribution ID if we are dealing with an update.
387 * @throws \CiviCRM_API3_Exception
389 public static function calculateMissingAmountParams(&$params, $contributionID) {
390 if (!$contributionID && !isset($params['fee_amount'])) {
391 if (isset($params['total_amount']) && isset($params['net_amount'])) {
392 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
395 $params['fee_amount'] = 0;
398 if (!isset($params['net_amount'])) {
399 if (!$contributionID) {
400 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
403 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
404 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
405 // net_amount may need adjusting.
406 $contribution = civicrm_api3('Contribution', 'getsingle', [
407 'id' => $contributionID,
408 'return' => ['total_amount', 'net_amount', 'fee_amount'],
410 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
411 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
412 $params['net_amount'] = $totalAmount - $feeAmount;
420 * @param $billingLocationTypeID
424 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
425 $hasBillingField = FALSE;
434 //build address array
436 $addressParams['location_type_id'] = $billingLocationTypeID;
437 $addressParams['is_billing'] = 1;
439 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
440 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
441 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
442 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
444 foreach ($billingFields as $value) {
445 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
446 if (!empty($addressParams[$value])) {
447 $hasBillingField = TRUE;
450 return [$hasBillingField, $addressParams];
454 * Get address params ready to be passed to the payment processor.
456 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
457 * To create an address we need state_province_id.
459 * @param array $params
460 * @param int $billingLocationTypeID
464 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
465 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
466 foreach ($addressParams as $name => $field) {
467 if (substr($name, 0, 8) == 'billing_') {
468 $addressParams[substr($name, 9)] = $addressParams[$field];
471 return [$hasBillingField, $addressParams];
475 * Get the number of terms for this contribution for a given membership type
476 * based on querying the line item table and relevant price field values
477 * Note that any one contribution should only be able to have one line item relating to a particular membership
480 * @param int $membershipTypeID
482 * @param int $contributionID
486 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
487 $numTerms = CRM_Core_DAO
::singleValueQuery("
488 SELECT membership_num_terms FROM civicrm_line_item li
489 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
490 WHERE contribution_id = %1 AND membership_type_id = %2",
491 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
493 // default of 1 is precautionary
494 return empty($numTerms) ?
1 : $numTerms;
498 * Takes an associative array and creates a contribution object.
500 * @param array $params
501 * (reference ) an assoc array of name/value pairs.
503 * The array that holds all the db ids.
505 * @return CRM_Contribute_BAO_Contribution
507 public static function create(&$params, $ids = []) {
508 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
509 $action = $contributionID ?
'edit' : 'create';
516 'revenue_recognition_date',
518 foreach ($dateFields as $df) {
519 if (isset($params[$df])) {
520 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
524 $transaction = new CRM_Core_Transaction();
527 $contribution = self
::add($params, $ids);
529 catch (CRM_Core_Exception
$e) {
530 $transaction->rollback();
534 $params['contribution_id'] = $contribution->id
;
536 if (!empty($params['custom']) &&
537 is_array($params['custom'])
539 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
542 $session = CRM_Core_Session
::singleton();
544 if (!empty($params['note'])) {
546 'entity_table' => 'civicrm_contribution',
547 'note' => $params['note'],
548 'entity_id' => $contribution->id
,
549 'contact_id' => $session->get('userID'),
550 'modified_date' => date('Ymd'),
552 if (!$noteParams['contact_id']) {
553 $noteParams['contact_id'] = $params['contact_id'];
555 CRM_Core_BAO_Note
::add($noteParams);
558 // make entry in batch entity batch table
559 if (!empty($params['batch_id'])) {
560 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
567 $retrieveRequired = 0;
568 foreach ($titleFields as $titleField) {
569 if (!isset($contribution->$titleField)) {
570 $retrieveRequired = 1;
574 if ($retrieveRequired == 1) {
575 $contribution->find(TRUE);
579 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
581 $transaction->commit();
583 $activity = civicrm_api3('Activity', 'get', [
584 'source_record_id' => $contribution->id
,
585 'options' => ['limit' => 1],
587 'activity_type_id' => 'Contribution',
588 'return' => ['id', 'campaign'],
591 //CRM-18406: Update activity when edit contribution.
592 if ($activity['count']) {
593 // CRM-13237 : if activity record found, update it with campaign id of contribution
594 // @todo compare campaign ids first.
595 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
596 $contribution->activity_id
= $activity['id'];
599 if (empty($contribution->contact_id
)) {
600 $contribution->find(TRUE);
602 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
604 // do not add to recent items for import, CRM-4399
605 if (empty($params['skipRecentView'])) {
606 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
607 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
609 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
616 $retrieveRequired = 0;
617 foreach ($titleFields as $titleField) {
618 if (!isset($contribution->$titleField)) {
619 $retrieveRequired = 1;
623 if ($retrieveRequired == 1) {
624 $contribution->find(TRUE);
626 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
627 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
630 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
631 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
632 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
636 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
637 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
638 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
642 // add the recently created Contribution
643 CRM_Utils_Recent
::add($title,
647 $contribution->contact_id
,
653 return $contribution;
657 * Get the values for pseudoconstants for name->value and reverse.
659 * @param array $defaults
660 * (reference) the default values, some of which need to be resolved.
661 * @param bool $reverse
662 * True if we want to resolve the values in the reverse direction (value -> name).
664 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
665 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
666 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
667 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
668 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
672 * Convert associative array names to values and vice-versa.
674 * This function is used by both the web form layer and the api. Note that
675 * the api needs the name => value conversion, also the view layer typically
676 * requires value => name conversion
678 * @param array $defaults
679 * @param string $property
680 * @param array $lookup
681 * @param bool $reverse
685 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
686 $id = $property . '_id';
688 $src = $reverse ?
$property : $id;
689 $dst = $reverse ?
$id : $property;
691 if (!array_key_exists($src, $defaults)) {
695 $look = $reverse ?
array_flip($lookup) : $lookup;
697 if (is_array($look)) {
698 if (!array_key_exists($defaults[$src], $look)) {
702 $defaults[$dst] = $look[$defaults[$src]];
707 * Retrieve DB object based on input parameters.
709 * It also stores all the retrieved values in the default array.
711 * @param array $params
712 * (reference ) an assoc array of name/value pairs.
713 * @param array $defaults
714 * (reference ) an assoc array to hold the name / value pairs.
715 * in a hierarchical manner
717 * (reference) the array that holds all the db ids.
719 * @return CRM_Contribute_BAO_Contribution
721 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
722 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
723 return $contribution;
727 * Combine all the importable fields from the lower levels object.
729 * The ordering is important, since currently we do not have a weight
730 * scheme. Adding weight is super important and should be done in the
731 * next week or so, before this can be called complete.
733 * @param string $contactType
734 * @param bool $status
737 * array of importable Fields
739 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
740 if (!self
::$_importableFields) {
741 if (!self
::$_importableFields) {
742 self
::$_importableFields = [];
746 $fields = ['' => ['title' => ts('- do not import -')]];
749 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
752 $note = CRM_Core_DAO_Note
::import();
753 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
754 unset($tmpFields['option_value']);
755 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
756 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
758 // Using new Dedupe rule.
760 'contact_type' => $contactType,
761 'used' => 'Unsupervised',
763 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
764 $tmpContactField = [];
765 if (is_array($fieldsArray)) {
766 foreach ($fieldsArray as $value) {
767 //skip if there is no dupe rule
768 if ($value == 'none') {
771 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
776 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
777 $tmpContactField[trim($value)] = $contactFields[trim($value)];
779 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
782 $title = $tmpContactField[trim($value)]['title'];
784 $tmpContactField[trim($value)]['title'] = $title;
788 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
789 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
790 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
791 $fields = array_merge($fields, $tmpContactField);
792 $fields = array_merge($fields, $tmpFields);
793 $fields = array_merge($fields, $note);
794 $fields = array_merge($fields, $optionFields);
795 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
796 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
797 self
::$_importableFields = $fields;
799 return self
::$_importableFields;
803 * Combine all the exportable fields from the lower level objects.
805 * @param bool $checkPermission
808 * array of exportable Fields
810 public static function &exportableFields($checkPermission = TRUE) {
811 if (!self
::$_exportableFields) {
812 if (!self
::$_exportableFields) {
813 self
::$_exportableFields = [];
816 $fields = CRM_Contribute_DAO_Contribution
::export();
817 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
818 $fields = array_merge(
820 CRM_Contribute_DAO_Product
::export(),
821 CRM_Contribute_DAO_ContributionProduct
::export(),
822 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
824 'contribution_product_id' => [
825 'title' => ts('Premium'),
826 'name' => 'contribution_product_id',
827 'where' => 'civicrm_product.id',
828 'data_type' => CRM_Utils_Type
::T_INT
,
834 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
836 $contributionPage = [
837 'contribution_page' => [
838 'title' => ts('Contribution Page'),
839 'name' => 'contribution_page',
840 'where' => 'civicrm_contribution_page.title',
841 'data_type' => CRM_Utils_Type
::T_STRING
,
845 $contributionNote = [
846 'contribution_note' => [
847 'title' => ts('Contribution Note'),
848 'name' => 'contribution_note',
849 'data_type' => CRM_Utils_Type
::T_TEXT
,
854 'contribution_batch' => [
855 'title' => ts('Batch Name'),
861 'contribution_campaign_title' => [
862 'title' => ts('Campaign Title'),
863 'name' => 'campaign_title',
864 'where' => 'civicrm_campaign.title',
865 'data_type' => CRM_Utils_Type
::T_STRING
,
868 $softCreditFields = [
869 'contribution_soft_credit_name' => [
870 'name' => 'contribution_soft_credit_name',
871 'title' => ts('Soft Credit For'),
872 'where' => 'civicrm_contact_d.display_name',
873 'data_type' => CRM_Utils_Type
::T_STRING
,
875 'contribution_soft_credit_amount' => [
876 'name' => 'contribution_soft_credit_amount',
877 'title' => ts('Soft Credit Amount'),
878 'where' => 'civicrm_contribution_soft.amount',
879 'data_type' => CRM_Utils_Type
::T_MONEY
,
881 'contribution_soft_credit_type' => [
882 'name' => 'contribution_soft_credit_type',
883 'title' => ts('Soft Credit Type'),
884 'where' => 'contribution_softcredit_type.label',
885 'data_type' => CRM_Utils_Type
::T_STRING
,
887 'contribution_soft_credit_contribution_id' => [
888 'name' => 'contribution_soft_credit_contribution_id',
889 'title' => ts('Soft Credit For Contribution ID'),
890 'where' => 'civicrm_contribution_soft.contribution_id',
891 'data_type' => CRM_Utils_Type
::T_INT
,
893 'contribution_soft_credit_contact_id' => [
894 'name' => 'contribution_soft_credit_contact_id',
895 'title' => ts('Soft Credit For Contact ID'),
896 'where' => 'civicrm_contact_d.id',
897 'data_type' => CRM_Utils_Type
::T_INT
,
901 $fields = array_merge($fields, $contributionPage,
902 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
903 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
906 self
::$_exportableFields = $fields;
909 return self
::$_exportableFields;
913 * Record an activity when a payment is received.
915 * @todo this is intended to be moved to payment BAO class as a protected function
916 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
917 * merit it's own function as it makes the code less rather than more readable.
919 * @param int $contributionId
920 * @param int $participantId
921 * @param string $totalAmount
922 * @param string $currency
923 * @param string $trxnDate
925 * @throws \CRM_Core_Exception
926 * @throws \CiviCRM_API3_Exception
928 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
929 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
931 if ($participantId) {
932 $inputParams['id'] = $participantId;
935 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
936 $entityObj = $entityObj[$participantId];
937 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
940 $entityObj = new CRM_Contribute_BAO_Contribution();
941 $entityObj->id
= $contributionId;
942 $entityObj->find(TRUE);
943 $title = ts('Contribution');
945 // @todo per block above this is not a logical splitting off of functionality.
946 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
950 * Get the value for the To Financial Account.
952 * @param $contribution
957 public static function getToFinancialAccount($contribution, $params) {
958 if (!empty($params['payment_processor'])) {
959 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
961 if (!empty($params['payment_instrument_id'])) {
962 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
965 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
966 $queryParams = [1 => [$relationTypeId, 'Integer']];
967 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
972 * Get memberships realted to the contribution.
974 * @param int $contributionID
978 protected static function getRelatedMemberships($contributionID) {
979 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
980 'return' => 'membership_id',
981 'contribution_id' => (int) $contributionID,
984 foreach ($membershipPayments as $membershipPayment) {
985 $membershipIDs[] = $membershipPayment['membership_id'];
987 if (empty($membershipIDs)) {
990 // We could combine this with the MembershipPayment.get - we'd
991 // need to re-wrangle the params (here or in the calling function)
992 // as they would then me membership.contact_id, membership.is_test etc
993 return civicrm_api3('Membership', 'get', [
994 'id' => ['IN' => $membershipIDs],
995 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
1000 * Cancel contribution.
1002 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
1004 * @param $processContributionObject
1005 * @param $memberships
1006 * @param $contributionId
1007 * @param $membershipStatuses
1008 * @param $updateResult
1009 * @param $participant
1011 * @param $pledgePayment
1013 * @param $pledgePaymentIDs
1014 * @param $contributionStatusId
1018 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
1019 // @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
1020 $processContribution = FALSE;
1021 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1022 if (is_array($memberships)) {
1023 foreach ($memberships as $membership) {
1025 //Update Membership status if there is no other completed contribution associated with the membership.
1026 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1027 foreach ($relatedContributions as $contriId) {
1028 if ($contriId == $contributionId) {
1031 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1032 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1036 if ($membership && $update) {
1037 $newStatus = array_search('Cancelled', $membershipStatuses);
1040 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1042 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1043 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1044 'target_contact_id' => $membership->contact_id
,
1045 'source_record_id' => $membership->id
,
1046 'activity_type_id' => 'Change Membership Status',
1047 'status_id' => 'Completed',
1048 'priority_id' => 'Normal',
1049 'activity_date_time' => 'now',
1052 $membership->status_id
= $newStatus;
1053 $membership->is_override
= TRUE;
1054 $membership->status_override_end_date
= 'null';
1055 $membership->save();
1056 civicrm_api3('activity', 'create', $activityParam);
1058 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1059 if ($processContributionObject) {
1060 $processContribution = TRUE;
1067 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1068 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1070 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1071 if ($processContributionObject) {
1072 $processContribution = TRUE;
1076 if ($pledgePayment) {
1077 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1079 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1080 if ($processContributionObject) {
1081 $processContribution = TRUE;
1084 return [$updateResult, $processContribution];
1088 * Do any accounting updates required as a result of a contribution status change.
1090 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1091 * this may attempt to add a payment. We need to resolve that....
1093 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1094 * then updates the contribution but this process should not also record another financial trxn.
1095 * Currently we have weak detection fot that scenario & where it is detected the first returned
1096 * value is FALSE - meaning 'do not continue'.
1098 * We should also look at the fact that the calling function - updateFinancialAccounts
1099 * bunches together some disparate processes rather than having separate appropriate
1102 * @param array $params
1103 * @param string $context
1104 * @param array $previousContributionStatus
1105 * @param string $currentContributionStatus
1108 * Return indicates whether the updateFinancialAccounts function should continue & whether this is a refund.
1110 private static function updateFinancialAccountsOnContributionStatusChange(&$params, $context, $previousContributionStatus, $currentContributionStatus) {
1112 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1113 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1114 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1115 // why it is here or where it is handled instead.
1116 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1117 && $currentContributionStatus == 'Partially paid'))
1119 return [FALSE, $isARefund];
1121 if ($context == 'changedStatus') {
1122 if ($previousContributionStatus == 'Completed'
1123 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
1126 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1127 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1128 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
1129 $creditNoteId = self
::createCreditNoteId();
1130 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1133 elseif (($previousContributionStatus == 'Pending'
1134 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1136 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1137 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1139 if ($currentContributionStatus == 'Cancelled') {
1140 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1141 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1142 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1143 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
1144 $creditNoteId = self
::createCreditNoteId();
1145 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1149 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1150 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1154 if (($previousContributionStatus == 'Pending'
1155 ||
$previousContributionStatus == 'In Progress')
1156 && ($currentContributionStatus == 'Completed')
1158 if (empty($params['line_item'])) {
1160 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1161 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1162 // & this can be removed
1163 return [FALSE, $isARefund];
1165 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1166 // This is an update so original currency if none passed in.
1167 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1169 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1170 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1171 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1172 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1173 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1174 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1177 'entity_table' => 'civicrm_financial_item',
1179 foreach ($params['line_item'] as $fieldId => $fields) {
1180 foreach ($fields as $fieldValueId => $lineItemDetails) {
1183 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1186 2 => [$lineItemDetails['id'], 'Integer'],
1188 CRM_Core_DAO
::executeQuery($query, $fparams);
1190 1 => [$lineItemDetails['id'], 'Integer'],
1192 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1193 while ($financialItem->fetch()) {
1194 $entityParams['entity_id'] = $financialItem->id
;
1195 $entityParams['amount'] = $financialItem->amount
;
1196 foreach (self
::$_trxnIDs as $tID) {
1197 $entityParams['financial_trxn_id'] = $tID;
1198 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1203 return [FALSE, $isARefund];
1206 return [TRUE, $isARefund];
1212 public function addSelectWhereClause() {
1213 $whereClauses = parent
::addSelectWhereClause();
1214 if ($whereClauses !== []) {
1215 // In this case permisssions have been applied & we assume the
1216 // financialaclreport is applying these
1217 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1218 return $whereClauses;
1221 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1222 return $whereClauses;
1224 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1225 if (empty($types)) {
1226 $whereClauses['financial_type_id'] = 'IN (0)';
1229 $whereClauses['financial_type_id'] = [
1230 'IN (' . implode(',', array_keys($types)) . ')',
1233 return $whereClauses;
1237 * @param null $status
1238 * @param null $startDate
1239 * @param null $endDate
1241 * @return array|null
1243 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1247 $where[] = 'contribution_status_id = 1';
1251 $where[] = 'contribution_status_id = 3';
1256 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1259 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1261 $financialTypeACLJoin = '';
1262 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1263 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1264 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1265 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1266 if ($financialTypes) {
1267 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1268 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1271 $where[] = "c.financial_type_id IN (0)";
1275 $whereCond = implode(' AND ', $where);
1278 SELECT sum( total_amount ) as total_amount,
1279 count( c.id ) as total_count,
1281 FROM civicrm_contribution c
1282 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1283 $financialTypeACLJoin
1285 AND ( is_test = 0 OR is_test IS NULL )
1286 AND contact.is_deleted = 0
1290 $dao = CRM_Core_DAO
::executeQuery($query);
1293 while ($dao->fetch()) {
1294 $count +
= $dao->total_count
;
1295 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1299 'amount' => implode(', ', $amount),
1307 * Delete the indirect records associated with this contribution first.
1311 * @return mixed|null
1312 * $results no of deleted Contribution on success, false otherwise
1314 public static function deleteContribution($id) {
1315 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1317 $transaction = new CRM_Core_Transaction();
1320 //delete activity record
1322 'source_record_id' => $id,
1323 // activity type id for contribution
1324 'activity_type_id' => 6,
1327 CRM_Activity_BAO_Activity
::deleteActivity($params);
1329 //delete billing address if exists for this contribution.
1330 self
::deleteAddress($id);
1332 //update pledge and pledge payment, CRM-3961
1333 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1335 // remove entry from civicrm_price_set_entity, CRM-5095
1336 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1337 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1339 // cleanup line items.
1340 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1342 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1343 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1345 if ($participantId) {
1346 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1349 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1353 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1354 $noteId = key($note);
1356 CRM_Core_BAO_Note
::del($noteId, FALSE);
1359 $dao = new CRM_Contribute_DAO_Contribution();
1362 $results = $dao->delete();
1364 $transaction->commit();
1366 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1368 // delete the recently created Contribution
1369 $contributionRecent = [
1371 'type' => 'Contribution',
1373 CRM_Utils_Recent
::del($contributionRecent);
1379 * React to a financial transaction (payment) failure.
1381 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1382 * payments is important for forensic and outreach reasons.
1384 * @param int $contributionID
1385 * @param int $contactID
1386 * @param string $message
1388 * @throws \CiviCRM_API3_Exception
1390 public static function failPayment($contributionID, $contactID, $message) {
1391 civicrm_api3('activity', 'create', [
1392 'activity_type_id' => 'Failed Payment',
1393 'details' => $message,
1394 'subject' => ts('Payment failed at payment processor'),
1395 'source_record_id' => $contributionID,
1396 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1399 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1400 civicrm_api3('contribution', 'create', [
1401 'id' => $contributionID,
1402 'contribution_status_id' => 'Failed',
1407 * Check if there is a contribution with the same trxn_id or invoice_id.
1409 * @param array $input
1410 * An assoc array of name/value pairs.
1411 * @param array $duplicates
1412 * (reference) store ids of duplicate contribs.
1416 * true if duplicate, false otherwise
1418 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1420 $id = CRM_Utils_Array
::value('id', $input);
1422 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1423 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1429 $clause[] = "trxn_id = %1";
1430 $input[1] = [$trxn_id, 'String'];
1434 $clause[] = "invoice_id = %2";
1435 $input[2] = [$invoice_id, 'String'];
1438 if (empty($clause)) {
1442 $clause = implode(' OR ', $clause);
1444 $clause = "( $clause ) AND id != %3";
1445 $input[3] = [$id, 'Integer'];
1448 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1449 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1451 while ($dao->fetch()) {
1452 $duplicates[] = $dao->id
;
1459 * Takes an associative array and creates a contribution_product object.
1461 * the function extract all the params it needs to initialize the create a
1462 * contribution_product object. the params array could contain additional unused name/value
1465 * @param array $params
1466 * (reference) an assoc array of name/value pairs.
1468 * @return CRM_Contribute_DAO_ContributionProduct
1470 public static function addPremium(&$params) {
1471 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1472 $contributionProduct->copyValues($params);
1473 return $contributionProduct->save();
1477 * Get list of contribution fields for profile.
1478 * For now we only allow custom contribution fields to be in
1481 * @param bool $addExtraFields
1482 * True if special fields needs to be added.
1485 * the list of contribution fields
1487 public static function getContributionFields($addExtraFields = TRUE) {
1488 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1489 // @todo remove this - this line was added because payment_instrument_id was not
1490 // set to exportable - but now it is.
1491 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1493 if ($addExtraFields) {
1494 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1497 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1499 foreach ($contributionFields as $key => $var) {
1500 if ($key == 'contribution_contact_id') {
1503 elseif ($key == 'contribution_campaign_id') {
1504 $var['title'] = ts('Campaign');
1506 $fields[$key] = $var;
1509 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1514 * Add extra fields specific to contribution.
1516 public static function getSpecialContributionFields() {
1518 'contribution_soft_credit_name' => [
1519 'name' => 'contribution_soft_credit_name',
1520 'title' => ts('Soft Credit Name'),
1521 'headerPattern' => '/^soft_credit_name$/i',
1522 'where' => 'civicrm_contact_d.display_name',
1524 'contribution_soft_credit_email' => [
1525 'name' => 'contribution_soft_credit_email',
1526 'title' => ts('Soft Credit Email'),
1527 'headerPattern' => '/^soft_credit_email$/i',
1528 'where' => 'soft_email.email',
1530 'contribution_soft_credit_phone' => [
1531 'name' => 'contribution_soft_credit_phone',
1532 'title' => ts('Soft Credit Phone'),
1533 'headerPattern' => '/^soft_credit_phone$/i',
1534 'where' => 'soft_phone.phone',
1536 'contribution_soft_credit_contact_id' => [
1537 'name' => 'contribution_soft_credit_contact_id',
1538 'title' => ts('Soft Credit Contact ID'),
1539 'headerPattern' => '/^soft_credit_contact_id$/i',
1540 'where' => 'civicrm_contribution_soft.contact_id',
1542 'contribution_pcp_title' => [
1543 'name' => 'contribution_pcp_title',
1544 'title' => ts('Personal Campaign Page Title'),
1545 'headerPattern' => '/^contribution_pcp_title$/i',
1546 'where' => 'contribution_pcp.title',
1550 return $extraFields;
1554 * @param int $pageID
1558 public static function getCurrentandGoalAmount($pageID) {
1560 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1561 FROM civicrm_contribution_page p,
1562 civicrm_contribution c
1563 WHERE p.id = c.contribution_page_id
1565 AND c.cancel_date is null
1569 $config = CRM_Core_Config
::singleton();
1570 $params = [1 => [$pageID, 'Integer']];
1571 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1573 if ($dao->fetch()) {
1574 return [$dao->goal
, $dao->total
];
1577 return [NULL, NULL];
1582 * Get list of contributions which credit the passed in contact ID.
1584 * The returned array provides details about the original contribution & donor.
1586 * @param int $honorId
1587 * In Honor of Contact ID.
1590 * list of contribution fields
1591 * @todo - this is a confusing function called from one place. It has a test. It would be
1592 * nice to deprecate it.
1595 public static function getHonorContacts($honorId) {
1597 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1598 $honorDAO->contact_id
= $honorId;
1601 $type = CRM_Contribute_PseudoConstant
::financialType();
1603 while ($honorDAO->fetch()) {
1604 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1605 $contributionDAO->id
= $honorDAO->contribution_id
;
1607 if ($contributionDAO->find(TRUE)) {
1608 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1609 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1610 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1611 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1612 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1613 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1614 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1615 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1616 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1624 * Get the sort name of a contact for a particular contribution.
1627 * Id of the contribution.
1629 * @return null|string
1630 * sort name of the contact if found
1632 public static function sortName($id) {
1633 $id = CRM_Utils_Type
::escape($id, 'Integer');
1636 SELECT civicrm_contact.sort_name
1637 FROM civicrm_contribution, civicrm_contact
1638 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1639 AND civicrm_contribution.id = {$id}
1641 return CRM_Core_DAO
::singleValueQuery($query);
1645 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1647 * @param int|array $contactIDs
1651 public static function annual($contactIDs) {
1652 if (!is_array($contactIDs)) {
1653 // In practice I can't fine any evidence that this function is ever called with
1654 // anything other than a single contact id, but left like this due to .... fear.
1655 $contactIDs = explode(',', $contactIDs);
1658 $query = self
::getAnnualQuery($contactIDs);
1659 $dao = CRM_Core_DAO
::executeQuery($query);
1661 $amount = $average = [];
1662 while ($dao->fetch()) {
1663 if ($dao->count
> 0 && $dao->amount
> 0) {
1664 $count +
= $dao->count
;
1665 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1666 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1672 implode(', ', $amount),
1673 implode(', ', $average),
1680 * Check if there is a contribution with the params passed in.
1682 * Used for trxn_id,invoice_id and contribution_id
1684 * @param array $params
1685 * An assoc array of name/value pairs.
1688 * contribution id if success else NULL
1690 public static function checkDuplicateIds($params) {
1691 $dao = new CRM_Contribute_DAO_Contribution();
1695 foreach ($params as $k => $v) {
1697 $clause[] = "$k = '$v'";
1700 $clause = implode(' AND ', $clause);
1701 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1702 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1704 while ($dao->fetch()) {
1712 * Get the contribution details for component export.
1714 * @param int $exportMode
1716 * @param array $componentIds
1722 public static function getContributionDetails($exportMode, $componentIds) {
1723 $paymentDetails = [];
1724 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1726 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1727 $componentSelect = " civicrm_participant_payment.participant_id id";
1728 $additionalClause = "
1729 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1730 AND civicrm_participant_payment.participant_id {$componentClause} )
1733 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1734 $componentSelect = " civicrm_membership_payment.membership_id id";
1735 $additionalClause = "
1736 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1737 AND civicrm_membership_payment.membership_id {$componentClause} )
1740 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1741 $componentSelect = " civicrm_pledge_payment.id id";
1742 $additionalClause = "
1743 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1744 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1748 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1749 trxn_id, {$componentSelect}
1750 FROM civicrm_contribution
1751 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1752 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1753 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1754 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1755 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1756 AND option_group_contribution_status.id = contribution_status.option_group_id )
1760 $dao = CRM_Core_DAO
::executeQuery($query);
1762 while ($dao->fetch()) {
1763 $paymentDetails[$dao->id
] = [
1764 'total_amount' => $dao->total_amount
,
1765 'contribution_status' => $dao->status
,
1766 'receive_date' => $dao->receive_date
,
1767 'pay_instru' => $dao->payment_instrument
,
1768 'trxn_id' => $dao->trxn_id
,
1772 return $paymentDetails;
1776 * Create address associated with contribution record.
1778 * As long as there is one or more billing field in the parameters we will create the address.
1780 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1783 * @param array $params
1784 * @param int $billingLocationTypeID
1789 public static function createAddress($params, $billingLocationTypeID) {
1790 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1791 if ($hasBillingField) {
1792 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1793 return $address->id
;
1800 * Delete billing address record related contribution.
1802 * @param int $contributionId
1803 * @param int $contactId
1805 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1807 $contactJoin = NULL;
1809 if ($contributionId) {
1810 $clauses[] = "cc.id = {$contributionId}";
1814 $clauses[] = "cco.id = {$contactId}";
1815 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1818 if (empty($clauses)) {
1819 CRM_Core_Error
::fatal();
1822 $condition = implode(' OR ', $clauses);
1826 FROM civicrm_address ca
1827 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1831 $dao = CRM_Core_DAO
::executeQuery($query);
1833 while ($dao->fetch()) {
1834 $params = ['id' => $dao->id
];
1835 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1840 * This function check online pending contribution associated w/
1841 * Online Event Registration or Online Membership signup.
1843 * @param int $componentId
1844 * Participant/membership id.
1845 * @param string $componentName
1849 * pending contribution id.
1851 public static function checkOnlinePendingContribution($componentId, $componentName) {
1852 $contributionId = NULL;
1853 if (!$componentId ||
1854 !in_array($componentName, ['Event', 'Membership'])
1856 return $contributionId;
1859 if ($componentName == 'Event') {
1860 $idName = 'participant_id';
1861 $componentTable = 'civicrm_participant';
1862 $paymentTable = 'civicrm_participant_payment';
1863 $source = ts('Online Event Registration');
1866 if ($componentName == 'Membership') {
1867 $idName = 'membership_id';
1868 $componentTable = 'civicrm_membership';
1869 $paymentTable = 'civicrm_membership_payment';
1870 $source = ts('Online Contribution');
1873 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1876 SELECT component.id as {$idName},
1877 componentPayment.contribution_id as contribution_id,
1878 contribution.source source,
1879 contribution.contribution_status_id as contribution_status_id,
1880 contribution.is_pay_later as is_pay_later
1881 FROM $componentTable component
1882 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1883 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1884 WHERE component.id = {$componentId}";
1886 $dao = CRM_Core_DAO
::executeQuery($query);
1888 while ($dao->fetch()) {
1889 if ($dao->contribution_id
&&
1890 $dao->is_pay_later
&&
1891 $dao->contribution_status_id
== $pendingStatusId &&
1892 strpos($dao->source
, $source) !== FALSE
1894 $contributionId = $dao->contribution_id
;
1898 return $contributionId;
1902 * Update contribution as well as related objects.
1904 * This function by-passes hooks - to address this - don't use this function.
1906 * @param array $params
1907 * @param bool $processContributionObject
1910 * @throws \Exception
1913 * Use api contribute.completetransaction
1914 * For failures use failPayment (preferably exposing by api in the process).
1917 public static function transitionComponents($params, $processContributionObject = FALSE) {
1918 // get minimum required values.
1919 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1920 $componentId = CRM_Utils_Array
::value('component_id', $params);
1921 $componentName = CRM_Utils_Array
::value('componentName', $params);
1922 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1923 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1925 // if we already processed contribution object pass previous status id.
1926 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1930 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1932 // we process only ( Completed, Cancelled, or Failed ) contributions.
1933 if (!$contributionId ||
1934 !in_array($contributionStatusId, [
1935 array_search('Completed', $contributionStatuses),
1936 array_search('Cancelled', $contributionStatuses),
1937 array_search('Failed', $contributionStatuses),
1940 return $updateResult;
1943 if (!$componentName ||
!$componentId) {
1944 // get the related component details.
1945 $componentDetails = self
::getComponentDetails($contributionId);
1948 $componentDetails['contact_id'] = $contactId;
1949 $componentDetails['component'] = $componentName;
1951 if ($componentName == 'event') {
1952 $componentDetails['participant'] = $componentId;
1955 $componentDetails['membership'] = $componentId;
1959 if (!empty($componentDetails['contact_id'])) {
1960 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1966 // do check for required ids.
1967 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1968 return $updateResult;
1971 //now we are ready w/ required ids, start processing.
1973 $baseIPN = new CRM_Core_Payment_BaseIPN();
1975 $input = $ids = $objects = [];
1977 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1978 $ids['contribution'] = $contributionId;
1979 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1980 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1981 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1982 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1983 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1984 $ids['contributionRecur'] = NULL;
1985 $ids['contributionPage'] = NULL;
1987 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1988 CRM_Core_Error
::fatal();
1991 $memberships = &$objects['membership'];
1992 $participant = &$objects['participant'];
1993 $pledgePayment = &$objects['pledge_payment'];
1994 $contribution = &$objects['contribution'];
1995 $pledgeID = $oldStatus = NULL;
1996 $pledgePaymentIDs = [];
1997 if ($pledgePayment) {
1998 foreach ($pledgePayment as $key => $object) {
1999 $pledgePaymentIDs[] = $object->id
;
2001 $pledgeID = $pledgePayment[0]->pledge_id
;
2004 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2007 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2008 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2013 // we might want to process contribution object.
2014 $processContribution = FALSE;
2015 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2016 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2017 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2019 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2020 if (is_array($memberships)) {
2021 foreach ($memberships as $membership) {
2023 //Update Membership status if there is no other completed contribution associated with the membership.
2024 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2025 foreach ($relatedContributions as $contriId) {
2026 if ($contriId == $contributionId) {
2029 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2030 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2034 if ($membership && $update) {
2035 $membership->status_id
= array_search('Expired', $membershipStatuses);
2036 $membership->is_override
= TRUE;
2037 $membership->status_override_end_date
= 'null';
2038 $membership->save();
2040 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2041 if ($processContributionObject) {
2042 $processContribution = TRUE;
2048 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2049 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2051 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2052 if ($processContributionObject) {
2053 $processContribution = TRUE;
2057 if ($pledgePayment) {
2058 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2060 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2061 if ($processContributionObject) {
2062 $processContribution = TRUE;
2066 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2068 // only pending contribution related object processed.
2069 if ($previousContriStatusId &&
2070 !in_array($contributionStatuses[$previousContriStatusId], [
2075 // this is case when we already processed contribution object.
2076 return $updateResult;
2078 elseif (!$previousContriStatusId &&
2079 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2084 // this is case when we are going to process contribution object later.
2085 return $updateResult;
2088 if (is_array($memberships)) {
2089 foreach ($memberships as $membership) {
2094 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2095 $membership->membership_type_id
,
2096 $membership->is_test
, $membership->id
2099 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2100 // this picks up membership type changes during renewals
2102 SELECT membership_type_id
2103 FROM civicrm_membership_log
2104 WHERE membership_id=$membership->id
2107 $dao = new CRM_Core_DAO();
2109 if ($dao->fetch()) {
2110 if (!empty($dao->membership_type_id
)) {
2111 $membership->membership_type_id
= $dao->membership_type_id
;
2112 $membership->save();
2115 // else fall back to using current membership type
2116 // Figure out number of terms
2118 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2119 foreach ($lineitems as $lineitem) {
2120 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2121 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2123 // in case membership_num_terms comes through as null or zero
2124 $numterms = $numterms >= 1 ?
$numterms : 1;
2129 // CRM-15735-to update the membership status as per the contribution receive date
2131 $oldStatus = $membership->status_id
;
2132 if (!empty($params['receive_date'])) {
2133 $joinDate = $params['receive_date'];
2134 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2135 $membership->end_date
,
2136 $membership->join_date
,
2137 $params['receive_date'],
2139 $membership->membership_type_id
,
2142 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2143 $membership->save();
2146 if ($currentMembership) {
2147 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2148 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2149 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2152 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2155 //get the status for membership.
2156 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2158 $dates['join_date'],
2161 $membership->membership_type_id
,
2165 $formattedParams = [
2166 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2167 array_search('Current', $membershipStatuses)
2169 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2170 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2171 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2174 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2176 $membership->copyValues($formattedParams);
2177 $membership->save();
2179 //updating the membership log
2180 $membershipLog = [];
2181 $membershipLog = $formattedParams;
2182 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2183 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2185 $membershipLog['start_date'] = $logStartDate;
2186 $membershipLog['membership_id'] = $membership->id
;
2187 $membershipLog['modified_id'] = $membership->contact_id
;
2188 $membershipLog['modified_date'] = date('Ymd');
2189 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2191 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2193 //update related Memberships.
2194 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2196 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2197 $scheduledActivityID = CRM_Utils_Array
::value('id',
2198 civicrm_api3('Activity', 'Get',
2200 'source_record_id' => $membership->id
,
2201 'activity_type_id' => $activityType,
2202 'status_id' => 'Scheduled',
2205 'sort' => 'id DESC',
2210 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2211 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2212 if ($scheduledActivityID) {
2213 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2218 // track membership status change if any
2219 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2220 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2221 CRM_Activity_BAO_Activity
::addActivity($membership,
2222 'Change Membership Status',
2225 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2226 'source_contact_id' => $membershipLog['modified_id'],
2227 'priority_id' => 'Normal',
2232 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2233 if ($processContributionObject) {
2234 $processContribution = TRUE;
2237 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2243 $updatedStatusId = array_search('Registered', $participantStatuses);
2244 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2246 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2247 if ($processContributionObject) {
2248 $processContribution = TRUE;
2252 if ($pledgePayment) {
2253 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2255 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2256 if ($processContributionObject) {
2257 $processContribution = TRUE;
2262 // process contribution object.
2263 if ($processContribution) {
2264 $contributionParams = [];
2271 'payment_instrument_id',
2274 'financial_type_id',
2275 'contribution_status_id',
2276 'non_deductible_amount',
2280 foreach ($fields as $field) {
2281 if (empty($params[$field])) {
2284 $contributionParams[$field] = $params[$field];
2287 $ids = ['contribution' => $contributionId];
2288 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2291 return $updateResult;
2295 * Returns all contribution related object ids.
2297 * @param $contributionId
2301 public static function getComponentDetails($contributionId) {
2302 $componentDetails = $pledgePayment = [];
2303 if (!$contributionId) {
2304 return $componentDetails;
2308 SELECT c.id as contribution_id,
2309 c.contact_id as contact_id,
2310 c.contribution_recur_id,
2311 mp.membership_id as membership_id,
2312 m.membership_type_id as membership_type_id,
2313 pp.participant_id as participant_id,
2314 p.event_id as event_id,
2315 pgp.id as pledge_payment_id
2316 FROM civicrm_contribution c
2317 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2318 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2319 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2320 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2321 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2322 WHERE c.id = $contributionId";
2324 $dao = CRM_Core_DAO
::executeQuery($query);
2325 $componentDetails = [];
2327 while ($dao->fetch()) {
2328 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2329 $componentDetails['contact_id'] = $dao->contact_id
;
2330 if ($dao->event_id
) {
2331 $componentDetails['event'] = $dao->event_id
;
2333 if ($dao->participant_id
) {
2334 $componentDetails['participant'] = $dao->participant_id
;
2336 if ($dao->membership_id
) {
2337 if (!isset($componentDetails['membership'])) {
2338 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2340 $componentDetails['membership'][] = $dao->membership_id
;
2341 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2343 if ($dao->pledge_payment_id
) {
2344 $pledgePayment[] = $dao->pledge_payment_id
;
2346 if ($dao->contribution_recur_id
) {
2347 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2351 if ($pledgePayment) {
2352 $componentDetails['pledge_payment'] = $pledgePayment;
2355 return $componentDetails;
2359 * @param int $contactId
2360 * @param bool $includeSoftCredit
2362 * @return null|string
2364 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2368 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2369 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2370 $liWhere = " AND i.financial_type_id IN (0)";
2371 if (!empty($financialTypes)) {
2372 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2373 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2375 $contactContributionsSQL = "
2376 SELECT contribution.id AS id
2377 FROM civicrm_contribution contribution
2378 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2379 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2383 $contactSoftCreditContributionsSQL = "
2384 SELECT contribution.id
2385 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2386 ON ( contribution.id = softContribution.contribution_id )
2387 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2388 $query = "SELECT count( x.id ) count FROM ( ";
2389 $query .= $contactContributionsSQL;
2391 if ($includeSoftCredit) {
2392 $query .= " UNION ";
2393 $query .= $contactSoftCreditContributionsSQL;
2398 return CRM_Core_DAO
::singleValueQuery($query);
2402 * Repeat a transaction as part of a recurring series.
2404 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2405 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2406 * subsequent call to the contribution.completetransaction api.
2408 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2410 * @param CRM_Contribute_BAO_Contribution $contribution
2411 * @param array $input
2412 * @param array $contributionParams
2413 * @param int $paymentProcessorID
2416 * @throws CiviCRM_API3_Exception
2418 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2419 if (!empty($contribution->id
)) {
2422 if (empty($contribution->id
)) {
2423 // Unclear why this would only be set for repeats.
2424 if (!empty($input['amount'])) {
2425 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2428 if (!empty($contributionParams['contribution_recur_id'])) {
2429 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2430 'id' => $contributionParams['contribution_recur_id'],
2432 if (!empty($recurringContribution['campaign_id'])) {
2433 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2434 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2436 if (!empty($recurringContribution['financial_type_id'])) {
2437 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2438 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2441 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2442 $contributionParams['contribution_recur_id'],
2443 array_intersect_key($contributionParams, [
2444 'total_amount' => TRUE,
2445 'financial_type_id' => TRUE,
2448 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2450 $contributionParams['status_id'] = 'Pending';
2451 if (isset($contributionParams['financial_type_id'])) {
2452 // Give precedence to passed in type.
2453 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2456 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2458 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2459 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2461 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2462 //do not create CC or BCC emails or profile notifications.
2463 //The if is just to be safe. Not sure if we can ever arrive with this unset
2464 // but per CRM-19478 it seems it can be 'null'
2465 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2466 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2469 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2470 $contribution->id
= $createContribution['id'];
2471 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2477 * Get individual id for onbehalf contribution.
2479 * @param int $contributionId
2481 * @param int $contributorId
2485 * containing organization id and individual id
2487 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2491 if (!$contributionId) {
2495 // fetch contributor id if null
2496 if (!$contributorId) {
2497 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2498 $contributionId, 'contact_id'
2502 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2503 $activityTypeId = array_search('Contribution', $activityTypeIds);
2505 if ($activityTypeId && $contributorId) {
2507 SELECT civicrm_activity_contact.contact_id
2508 FROM civicrm_activity_contact
2509 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2510 WHERE civicrm_activity.activity_type_id = %1
2511 AND civicrm_activity.source_record_id = %2
2512 AND civicrm_activity_contact.record_type_id = %3
2515 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2516 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2519 1 => [$activityTypeId, 'Integer'],
2520 2 => [$contributionId, 'Integer'],
2521 3 => [$sourceID, 'Integer'],
2524 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2526 // for on behalf contribution source is individual and contributor is organization
2527 if ($sourceContactId && $sourceContactId != $contributorId) {
2528 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2529 // get rel type id for employee of relation
2530 foreach ($relationshipTypeIds as $id => $typeVals) {
2531 if ($typeVals['name_a_b'] == 'Employee of') {
2532 $relationshipTypeId = $id;
2537 $rel = new CRM_Contact_DAO_Relationship();
2538 $rel->relationship_type_id
= $relationshipTypeId;
2539 $rel->contact_id_a
= $sourceContactId;
2540 $rel->contact_id_b
= $contributorId;
2541 if ($rel->find(TRUE)) {
2542 $ids['individual_id'] = $rel->contact_id_a
;
2543 $ids['organization_id'] = $rel->contact_id_b
;
2554 public static function getContributionDates() {
2555 $config = CRM_Core_Config
::singleton();
2556 $currentMonth = date('m');
2557 $currentDay = date('d');
2558 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2559 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2560 (int ) $config->fiscalYearStart
['d'] > $currentDay
2563 $year = date('Y') - 1;
2568 $year = ['Y' => $year];
2569 $yearDate = $config->fiscalYearStart
;
2570 $yearDate = array_merge($year, $yearDate);
2571 $yearDate = CRM_Utils_Date
::format($yearDate);
2573 $monthDate = date('Ym') . '01';
2579 'yearDate' => $yearDate,
2580 'monthDate' => $monthDate,
2585 * Load objects relations to contribution object.
2586 * Objects are stored in the $_relatedObjects property
2587 * In the first instance we are just moving functionality from BASEIpn -
2589 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2591 * Note that the unit test for the BaseIPN class tests this function
2593 * @param array $input
2594 * Input as delivered from Payment Processor.
2596 * Ids as Loaded by Payment Processor.
2597 * @param bool $loadAll
2598 * Load all related objects - even where id not passed in? (allows API to call this).
2603 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2604 // @todo deprecate this function - the steps should be
2605 // 1) add additional functions like 'getRelatedMemberships'
2606 // 2) switch all calls that refer to ->_relatedObjects to
2607 // using the helper functions
2608 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2609 // 4) make ->_relatedObjects protected
2610 // 5) hone up the individual functions to not use rely on this having been called
2611 // 6) deprecate like mad
2613 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2614 if (empty($ids['contact']) && isset($this->contact_id
)) {
2615 $ids['contact'] = $this->contact_id
;
2618 if (empty($this->_component
)) {
2619 if (!empty($ids['event'])) {
2620 $this->_component
= 'event';
2623 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2627 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2628 // refactoring than anything else, and has unit test coverage.
2629 if (empty($this->financial_type_id
)) {
2633 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2638 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2639 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2640 $this->contribution_page_id
,
2643 if ($paymentProcessorID) {
2644 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2648 $ids['contributionType'] = $this->financial_type_id
;
2649 $ids['financialType'] = $this->financial_type_id
;
2650 if ($this->contribution_page_id
) {
2651 $ids['contributionPage'] = $this->contribution_page_id
;
2654 $this->loadRelatedEntitiesByID($ids);
2656 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2657 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2660 if (!empty($ids['pledge_payment'])) {
2661 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2662 if (empty($paymentID)) {
2665 $payment = new CRM_Pledge_BAO_PledgePayment();
2666 $payment->id
= $paymentID;
2667 if (!$payment->find(TRUE)) {
2668 throw new Exception("Could not find pledge payment record: " . $paymentID);
2670 $this->_relatedObjects
['pledge_payment'][] = $payment;
2674 // These are probably no longer accessed from anywhere
2675 // @todo remove this line, after ensuring not used.
2676 $ids = $this->loadRelatedMembershipObjects($ids);
2678 if ($this->_component
!= 'contribute') {
2679 // we are in event mode
2680 // make sure event exists and is valid
2681 $event = new CRM_Event_BAO_Event();
2682 $event->id
= $ids['event'];
2683 if ($ids['event'] &&
2686 throw new Exception("Could not find event: " . $ids['event']);
2689 $this->_relatedObjects
['event'] = &$event;
2691 $participant = new CRM_Event_BAO_Participant();
2692 $participant->id
= $ids['participant'];
2693 if ($ids['participant'] &&
2694 !$participant->find(TRUE)
2696 throw new Exception("Could not find participant: " . $ids['participant']);
2698 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2700 $this->_relatedObjects
['participant'] = &$participant;
2702 // get the payment processor id from event - this is inaccurate see CRM-16923
2703 // in future we should look at throwing an exception here rather than an dubious guess.
2704 if (!$paymentProcessorID) {
2705 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2706 if ($paymentProcessorID) {
2707 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2712 if ($paymentProcessorID) {
2713 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2714 $this->is_test ?
'test' : 'live'
2716 $ids['paymentProcessor'] = $paymentProcessorID;
2717 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2720 // Add contribution id to $ids. CRM-20401
2721 $ids['contribution'] = $this->id
;
2726 * Create array of message information - ie. return html version, txt version, to field
2728 * @param array $input
2729 * Incoming information.
2730 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2731 * just check presence of recur object but maintaining legacy approach
2734 * IDs of related objects.
2735 * @param array $values
2736 * Any values that may have already been compiled by calling process.
2737 * This is augmented by values 'gathered' by gatherMessageValues
2738 * @param bool $returnMessageText
2739 * Distinguishes between whether to send message or return.
2740 * message text. We are working towards this function ALWAYS returning message text & calling
2741 * function doing emails / pdfs with it
2747 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2748 $this->loadRelatedObjects($input, $ids);
2750 if (empty($this->_component
)) {
2751 $this->_component
= CRM_Utils_Array
::value('component', $input);
2754 //not really sure what params might be passed in but lets merge em into values
2755 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2756 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2757 if (!empty($input['receipt_date'])) {
2758 $values['receipt_date'] = $input['receipt_date'];
2761 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2762 //what does recur 'mean here - to do with payment processor return functionality but
2763 // what is the importance
2764 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2765 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2767 $entityID = $entity = NULL;
2768 if (isset($ids['contribution'])) {
2769 $entity = 'contribution';
2770 $entityID = $ids['contribution'];
2772 if (!empty($ids['membership'])) {
2773 //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
2774 // 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
2775 // line having loaded an array
2776 $ids['membership'] = (array) $ids['membership'];
2777 $entity = 'membership';
2778 $entityID = $ids['membership'][0];
2781 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2782 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2783 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2785 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2786 //direct mode showing billing block, so use directIPN for temporary
2787 $template->assign('contributeMode', 'directIPN');
2790 // todo remove strtolower - check consistency
2791 if (strtolower($this->_component
) == 'event') {
2792 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2793 $values['event'] = [];
2795 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2797 //get location details
2799 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2800 'entity_table' => 'civicrm_event',
2802 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2805 'entity_table' => 'civicrm_event',
2806 'entity_id' => $ids['event'],
2807 'module' => 'CiviEvent',
2810 list($custom_pre_id,
2812 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2814 $values['custom_pre_id'] = $custom_pre_id;
2815 $values['custom_post_id'] = $custom_post_ids;
2816 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2817 //and cases involving status updation through ipn
2818 // whatever that means!
2819 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2820 // perhaps we should throw an e-notice if amount is set & force total_amount?
2821 if (!empty($input['amount'])) {
2822 $values['totalAmount'] = $input['amount'];
2824 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2825 if ($values['event']['is_email_confirm']) {
2826 $values['is_email_receipt'] = 1;
2829 if (!empty($ids['contribution'])) {
2830 $values['contributionId'] = $ids['contribution'];
2833 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2834 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2838 $values['contribution_id'] = $this->id
;
2839 if (!empty($ids['related_contact'])) {
2840 $values['related_contact'] = $ids['related_contact'];
2841 if (isset($ids['onbehalf_dupe_alert'])) {
2842 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2845 'contact_id' => $ids['contact'],
2846 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2847 'Home', 'id', 'name'
2850 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2851 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2854 if ($this->is_test
) {
2857 if (!empty($this->_relatedObjects
['membership'])) {
2858 foreach ($this->_relatedObjects
['membership'] as $membership) {
2859 if ($membership->id
) {
2860 $values['membership_id'] = $membership->id
;
2861 $values['isMembership'] = TRUE;
2862 $values['membership_assign'] = TRUE;
2864 // need to set the membership values here
2865 $template->assign('membership_name',
2866 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2868 $template->assign('mem_start_date', $membership->start_date
);
2869 $template->assign('mem_join_date', $membership->join_date
);
2870 $template->assign('mem_end_date', $membership->end_date
);
2871 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2872 $template->assign('mem_status', $membership_status);
2873 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2874 $values['is_pay_later'] = 1;
2876 // Pass amount to floatval as string '0.00' is considered a
2877 // valid amount and includes Fee section in the mail.
2878 if (isset($values['amount'])) {
2879 $values['amount'] = floatval($values['amount']);
2882 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2883 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2884 $template->assign('cancelSubscriptionUrl', $url);
2885 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2886 $template->assign('updateSubscriptionBillingUrl', $url);
2887 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2888 $template->assign('updateSubscriptionUrl', $url);
2891 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2894 // otherwise if its about sending emails, continue sending without return, as we
2895 // don't want to exit the loop.
2900 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2906 * Gather values for contribution mail - this function has been created
2907 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2908 * Values related to the contribution in question are gathered
2910 * @param array $input
2911 * Input into function (probably from payment processor).
2912 * @param array $values
2914 * The set of ids related to the input.
2917 * @throws \CRM_Core_Exception
2919 public function _gatherMessageValues($input, &$values, $ids = []) {
2920 // set display address of contributor
2921 if ($this->address_id
) {
2922 $addressParams = ['id' => $this->address_id
];
2923 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2924 $addressDetails = array_values($addressDetails);
2926 // Else we assign the billing address of the contribution contact.
2928 $addressParams = ['contact_id' => $this->contact_id
, 'is_billing' => 1];
2929 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2930 $addressDetails = array_values($addressDetails);
2933 if (!empty($addressDetails[0]['display'])) {
2934 $values['address'] = $addressDetails[0]['display'];
2937 if ($this->_component
== 'contribute') {
2938 //get soft contributions
2939 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2940 if (!empty($softContributions)) {
2941 $values['softContributions'] = $softContributions['soft_credit'];
2943 if (isset($this->contribution_page_id
)) {
2944 // This is a call we want to use less, in favour of loading related objects.
2945 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2946 if ($this->contribution_page_id
) {
2947 // This is precautionary as there are some legacy flows, but it should really be
2949 if (!isset($this->_relatedObjects
['contributionPage'])) {
2950 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2952 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
2955 // no contribution page -probably back office
2957 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2958 $values['title'] = 'Contribution';
2960 // set lineItem for contribution
2962 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2963 if (!empty($lineItems)) {
2964 $firstLineItem = reset($lineItems);
2966 if (!empty($firstLineItem['price_set_id'])) {
2967 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
2968 'id' => $firstLineItem['price_set_id'],
2969 'return' => 'is_quick_config, id',
2971 $values['priceSetID'] = $priceSet['id'];
2973 foreach ($lineItems as &$eachItem) {
2974 if (isset($this->_relatedObjects
['membership'])
2975 && is_array($this->_relatedObjects
['membership'])
2976 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2977 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2978 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2979 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2981 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2982 // However, that does create upgrade pain so would be better to be phased in.
2983 $values['useForMember'] = empty($priceSet['is_quick_config']);
2985 $values['lineItem'][0] = $lineItems;
2989 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2993 // if this is onbehalf of contribution then set related contact
2994 if (!empty($relatedContact['individual_id'])) {
2995 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2999 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3002 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3005 foreach ($groupTree as $key => $group) {
3006 if ($key === 'info') {
3010 foreach ($group['fields'] as $k => $customField) {
3011 $groupLabel = $group['title'];
3012 if (!empty($customField['customValue'])) {
3013 foreach ($customField['customValue'] as $customFieldValues) {
3014 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3019 $values['customGroup'] = $customGroup;
3021 $values['is_pay_later'] = $this->is_pay_later
;
3027 * Assign message variables to template but try to break the habit.
3029 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3030 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3031 * multiple recurring payments for processors like IATS that use tokens.
3033 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3034 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3035 * Note we send directly from this function in some cases because it is only partly refactored.
3037 * Don't call this function directly as the signature will change.
3041 * @param bool $returnMessageText
3045 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3046 // @todo - this should have a better separation of concerns - ie.
3047 // gatherMessageValues should build an array of values to be assigned to the template
3048 // and this function should assign them (assigning null if not set).
3049 // the way the pcpParams & honor Params section works is a baby-step towards this.
3050 $template = CRM_Core_Smarty
::singleton();
3051 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3052 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3053 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3055 // For some unit tests contribution cannot contain paymentProcessor information
3056 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3057 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3059 //assign honor information to receipt message
3060 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3063 'soft_credit_type' => NULL,
3064 'honor_block_is_active' => NULL,
3066 if (isset($softRecord['soft_credit'])) {
3067 //if id of contribution page is present
3068 if (!empty($values['id'])) {
3069 $values['honor'] = [
3070 'honor_profile_values' => [],
3071 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3072 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3075 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3076 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3079 //offline contribution
3080 $softCreditTypes = $softCredits = [];
3081 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3082 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3083 $softCredits[$key] = [
3084 'Name' => $softCredit['contact_name'],
3085 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3088 $template->assign('softCreditTypes', $softCreditTypes);
3089 $template->assign('softCredits', $softCredits);
3093 $dao = new CRM_Contribute_DAO_ContributionProduct();
3094 $dao->contribution_id
= $this->id
;
3095 if ($dao->find(TRUE)) {
3096 $premiumId = $dao->product_id
;
3097 $template->assign('option', $dao->product_option
);
3099 $productDAO = new CRM_Contribute_DAO_Product();
3100 $productDAO->id
= $premiumId;
3101 $productDAO->find(TRUE);
3102 $template->assign('selectPremium', TRUE);
3103 $template->assign('product_name', $productDAO->name
);
3104 $template->assign('price', $productDAO->price
);
3105 $template->assign('sku', $productDAO->sku
);
3107 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3108 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3109 if (!$values['amount'] && isset($this->total_amount
)) {
3110 $values['amount'] = $this->total_amount
;
3115 'pcp_display_in_roll' => NULL,
3116 'pcp_roll_nickname' => NULL,
3117 'pcp_personal_note' => NULL,
3121 if (strtolower($this->_component
) == 'contribute') {
3123 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3124 $softDAO->contribution_id
= $this->id
;
3125 if ($softDAO->find(TRUE)) {
3126 $pcpParams['pcpBlock'] = TRUE;
3127 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3128 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3129 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3131 //assign the pcp page title for email subject
3132 $pcpDAO = new CRM_PCP_DAO_PCP();
3133 $pcpDAO->id
= $softDAO->pcp_id
;
3134 if ($pcpDAO->find(TRUE)) {
3135 $pcpParams['title'] = $pcpDAO->title
;
3139 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3140 $template->assign($templateKey, $templateValue);
3143 if ($this->financial_type_id
) {
3144 $values['financial_type_id'] = $this->financial_type_id
;
3147 $template->assign('trxn_id', $this->trxn_id
);
3148 $template->assign('receive_date',
3149 CRM_Utils_Date
::processDate($this->receive_date
)
3151 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3152 $template->assign('action', $this->is_test ?
1024 : 1);
3153 $template->assign('receipt_text',
3154 CRM_Utils_Array
::value('receipt_text',
3158 $template->assign('is_monetary', 1);
3159 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3160 $template->assign('currency', $this->currency
);
3161 $template->assign('address', CRM_Utils_Address
::format($input));
3162 if (!empty($values['customGroup'])) {
3163 $template->assign('customGroup', $values['customGroup']);
3165 if (!empty($values['softContributions'])) {
3166 $template->assign('softContributions', $values['softContributions']);
3168 if ($this->_component
== 'event') {
3169 $template->assign('title', $values['event']['title']);
3170 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3172 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3173 $viewRoles[] = $participantRoles[$v];
3175 $values['event']['participant_role'] = implode(', ', $viewRoles);
3176 $template->assign('event', $values['event']);
3177 $template->assign('participant', $values['participant']);
3178 $template->assign('location', $values['location']);
3179 $template->assign('customPre', $values['custom_pre_id']);
3180 $template->assign('customPost', $values['custom_post_id']);
3183 if ($this->_relatedObjects
['participant']->is_test
) {
3187 $values['params'] = [];
3188 //to get email of primary participant.
3189 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3190 $primaryAmount[] = [
3191 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3192 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3194 //build an array of cId/pId of participants
3195 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3196 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3197 //send receipt to additional participant if exists
3198 if (count($additionalIDs)) {
3199 $template->assign('isPrimary', 0);
3200 $template->assign('customProfile', NULL);
3201 //set additionalParticipant true
3202 $values['params']['additionalParticipant'] = TRUE;
3203 foreach ($additionalIDs as $pId => $cId) {
3205 //to change the status pending to completed
3206 $additional = new CRM_Event_DAO_Participant();
3207 $additional->id
= $pId;
3208 $additional->contact_id
= $cId;
3209 $additional->find(TRUE);
3210 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3211 $additional->status_id
= 1;
3212 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3213 //if additional participant dont have email
3215 if (!$additionalParticipantInfo) {
3216 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3219 'label' => $additional->fee_level
,
3220 'amount' => $additional->fee_amount
,
3222 $primaryAmount[] = [
3223 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3224 'amount' => $additional->fee_amount
,
3226 $additional->save();
3227 $template->assign('amount', $amount);
3228 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3232 //build an array of custom profile and assigning it to template
3233 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3235 if (count($customProfile)) {
3236 $template->assign('customProfile', $customProfile);
3239 // for primary contact
3240 $values['params']['additionalParticipant'] = FALSE;
3241 $template->assign('isPrimary', 1);
3242 $template->assign('amount', $primaryAmount);
3243 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3244 if ($this->payment_instrument_id
) {
3245 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3246 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3248 // carry paylater, since we did not created billing,
3249 // so need to pull email from primary location, CRM-4395
3250 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3256 * Check whether payment processor supports
3257 * cancellation of contribution subscription
3259 * @param int $contributionId
3262 * @param bool $isNotCancelled
3266 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3267 $cacheKeyString = "$contributionId";
3268 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3270 static $supportsCancel = [];
3272 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3273 $supportsCancel[$cacheKeyString] = FALSE;
3274 $isCancelled = FALSE;
3276 if ($isNotCancelled) {
3277 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3280 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3281 if (!empty($paymentObject)) {
3282 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3285 return $supportsCancel[$cacheKeyString];
3289 * Check whether subscription is already cancelled.
3291 * @param int $contributionId
3295 * contribution status
3297 public static function isSubscriptionCancelled($contributionId) {
3299 SELECT cr.contribution_status_id
3300 FROM civicrm_contribution_recur cr
3301 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3302 WHERE con.id = %1 LIMIT 1";
3303 $params = [1 => [$contributionId, 'Integer']];
3304 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3305 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3306 if ($status == 'Cancelled') {
3313 * Create all financial accounts entry.
3315 * @param array $params
3316 * Contribution object, line item array and params for trxn.
3319 * @param array $financialTrxnValues
3321 * @return null|\CRM_Core_BAO_FinancialTrxn
3323 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3324 $skipRecords = $update = $return = $isRelatedId = FALSE;
3326 $additionalParticipantId = [];
3327 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3328 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3330 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3331 $entityId = $params['participant_id'];
3332 $entityTable = 'civicrm_participant';
3333 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3335 elseif (!empty($params['membership_id'])) {
3336 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3337 // are created off one contribution should be handled elsewhere
3338 $entityId = $params['membership_id'];
3339 $entityTable = 'civicrm_membership';
3342 $entityId = $params['contribution']->id
;
3343 $entityTable = 'civicrm_contribution';
3346 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3347 $isRelatedId = TRUE;
3350 $entityID[] = $entityId;
3351 if (!empty($additionalParticipantId)) {
3352 $entityID +
= $additionalParticipantId;
3354 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3355 if (empty($params['prevContribution'])) {
3362 $statusId = $params['contribution']->contribution_status_id
;
3363 // CRM-13964 partial payment
3364 if ($contributionStatus == 'Partially paid'
3365 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3367 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3368 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3370 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3371 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3372 $params['total_amount'] = $partialAmtPay;
3374 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3375 if (empty($balanceTrxnInfo['trxn_id'])) {
3376 // create new balance transaction record
3377 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3379 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3380 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3381 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3382 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3383 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3384 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3385 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3386 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3387 $balanceTrxnParams['status_id'] = $statusId;
3388 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3389 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3390 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3391 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3392 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3393 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3395 $balanceTrxnParams['is_payment'] = 1;
3397 if (!empty($params['payment_processor'])) {
3398 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3400 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3404 // build line item array if its not set in $params
3405 if (empty($params['line_item']) ||
$additionalParticipantId) {
3406 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3409 if ($contributionStatus != 'Failed' &&
3410 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3412 $skipRecords = TRUE;
3417 if (in_array($contributionStatus, $pendingStatus)) {
3418 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3419 $params['financial_type_id'],
3420 'Accounts Receivable Account is'
3423 elseif (!empty($params['payment_processor'])) {
3424 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3425 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3426 'id' => $params['payment_processor'],
3427 'return' => 'payment_instrument_id',
3430 elseif (!empty($params['payment_instrument_id'])) {
3431 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3434 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3435 $queryParams = [1 => [$relationTypeId, 'Integer']];
3436 $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);
3439 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3440 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3441 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3443 //build financial transaction params
3445 'contribution_id' => $params['contribution']->id
,
3446 'to_financial_account_id' => $params['to_financial_account_id'],
3447 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3448 'total_amount' => $totalAmount,
3449 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3450 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3451 'currency' => $params['contribution']->currency
,
3452 'trxn_id' => $params['contribution']->trxn_id
,
3453 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3454 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3455 // this should really default to completed (after discussion).
3456 'status_id' => $statusId,
3457 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3458 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3459 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3460 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3462 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3463 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3464 if (isset($params['refund_trxn_id'])) {
3465 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3466 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3469 //CRM-16259, set is_payment flag for non pending status
3470 if (!in_array($contributionStatus, $pendingStatus)) {
3471 $trxnParams['is_payment'] = 1;
3473 if (!empty($params['payment_processor'])) {
3474 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3477 if (isset($fromFinancialAccountId)) {
3478 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3481 // consider external values passed for recording transaction entry
3482 if (!empty($financialTrxnValues)) {
3483 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3485 if (empty($trxnParams['payment_processor_id'])) {
3486 unset($trxnParams['payment_processor_id']);
3489 $params['trxnParams'] = $trxnParams;
3491 if (!empty($params['prevContribution'])) {
3493 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3494 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3495 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3496 if (!isset($params['trxnParams']['trxn_id'])) {
3497 // Actually I have no idea why we are overwriting any values from the previous contribution.
3498 // (filling makes sense to me). However, only protecting this value as I really really know we
3499 // don't want this one overwritten.
3501 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3503 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3505 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3506 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3507 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3509 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3510 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3513 //if financial type is changed
3514 if (!empty($params['financial_type_id']) &&
3515 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3517 $accountRelationship = 'Income Account is';
3518 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3519 $accountRelationship = 'Deferred Revenue Account is';
3521 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3522 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3523 if ($oldFinancialAccount != $newFinancialAccount) {
3524 $params['total_amount'] = 0;
3525 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3526 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3527 $params['prevContribution']->financial_type_id
, $accountRelationship);
3530 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3531 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3532 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3535 self
::updateFinancialAccounts($params, 'changeFinancialType');
3536 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3537 $params['financial_account_id'] = $newFinancialAccount;
3538 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3539 self
::updateFinancialAccounts($params);
3540 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3542 $params['deferred_financial_account_id'] = $newFinancialAccount;
3546 //Update contribution status
3547 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3548 if (!isset($params['refund_trxn_id'])) {
3549 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3550 // gets preference over another so I am only 'protecting' a very specific tested flow
3551 // and letting natural justice take care of the rest.
3552 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3554 if (!empty($params['contribution_status_id']) &&
3555 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3557 //Update Financial Records
3558 self
::updateFinancialAccounts($params, 'changedStatus');
3562 // change Payment Instrument for a Completed contribution
3563 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3564 // instrument is null and now new payment instrument is added along with the payment
3565 if (!$params['contribution']->payment_instrument_id
) {
3566 $params['contribution']->find(TRUE);
3568 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3569 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3571 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3572 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3575 //if Change contribution amount
3576 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3577 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3578 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3579 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3580 if (isset($totalAmount) &&
3581 $totalAmount != $params['prevContribution']->total_amount
3583 //Update Financial Records
3584 $params['trxnParams']['from_financial_account_id'] = NULL;
3585 self
::updateFinancialAccounts($params, 'changedAmount');
3590 // Looks like we might have a data correction update.
3591 // This would be a case where a transaction id has been entered but it is incorrect &
3592 // the person goes back in & fixes it, as opposed to a new transaction.
3593 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3594 // the data fix scenario.
3596 if (isset($params['refund_trxn_id'])) {
3597 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3598 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3599 civicrm_api3('FinancialTrxn', 'create', [
3600 'id' => $refundIDs['financialTrxnId'],
3601 'trxn_id' => $params['refund_trxn_id'],
3605 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3606 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3607 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3612 // records finanical trxn and entity financial trxn
3613 // also make it available as return value
3614 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3615 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3616 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3617 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3618 $params['entity_id'] = $financialTxn->id
;
3619 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3620 self
::$_trxnIDs[] = $financialTxn->id
;
3624 // record line items and financial items
3625 if (empty($params['skipLineItem'])) {
3626 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3629 // create batch entry if batch_id is passed and
3630 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3631 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3633 'batch_id' => $params['batch_id'],
3634 'entity_table' => 'civicrm_financial_trxn',
3635 'entity_id' => $financialTxn->id
,
3637 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3640 // when a fee is charged
3641 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3642 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3645 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3646 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3648 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3649 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3650 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3652 unset($params['line_item']);
3653 self
::$_trxnIDs = NULL;
3658 * Update all financial accounts entry.
3660 * @param array $params
3661 * Contribution object, line item array and params for trxn.
3663 * @param string $context
3666 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3667 * adds unpredictability.
3670 public static function updateFinancialAccounts(&$params, $context = NULL) {
3672 $inputParams = $params;
3674 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
3675 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3677 if ($context == 'changedStatus') {
3678 list($continue, $isARefund) = self
::updateFinancialAccountsOnContributionStatusChange($params, $context, $previousContributionStatus, $currentContributionStatus);
3679 // @todo - it may be that this is always false & the parent function is just a confusing wrapper for the child fn.
3685 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3686 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3687 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3690 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3691 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3692 $params['entity_id'] = $trxn->id
;
3694 $itemParams['entity_table'] = 'civicrm_line_item';
3695 $trxnIds['id'] = $params['entity_id'];
3696 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3697 foreach ($params['line_item'] as $fieldId => $fields) {
3698 foreach ($fields as $fieldValueId => $lineItemDetails) {
3699 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3700 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3701 if ($params['contribution']->receive_date
) {
3702 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3705 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
3707 $currency = $params['prevContribution']->currency
;
3708 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3709 if ($params['contribution']->currency
) {
3710 $currency = $params['contribution']->currency
;
3712 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3714 'transaction_date' => $receiveDate,
3715 'contact_id' => $params['prevContribution']->contact_id
,
3716 'currency' => $currency,
3717 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
3718 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
3719 'status_id' => $prevFinancialItem['status_id'],
3720 'financial_account_id' => $financialAccount,
3721 'entity_table' => 'civicrm_line_item',
3722 'entity_id' => $lineItemDetails['id'],
3724 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3725 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3726 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3727 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3729 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
3730 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3731 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3732 $taxAmount = (float) $lineItemDetails['tax_amount'];
3733 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
3734 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
3735 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3737 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
3738 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3740 if ($taxAmount != 0) {
3741 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
3742 $itemParams['description'] = $taxTerm;
3743 if ($lineItemDetails['financial_type_id']) {
3744 $itemParams['financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3745 $lineItemDetails['financial_type_id'],
3746 'Sales Tax Account is'
3749 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3755 if ($context == 'changeFinancialType') {
3756 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3757 $params['skipLineItem'] = FALSE;
3758 foreach ($params['line_item'] as &$lineItems) {
3759 foreach ($lineItems as &$line) {
3760 $line['financial_type_id'] = $params['financial_type_id'];
3765 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3769 * Is this contribution status a reversal.
3771 * If so we would expect to record a negative value in the financial_trxn table.
3773 * @param int $status_id
3777 public static function isContributionStatusNegative($status_id) {
3778 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3779 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3783 * Check status validation on update of a contribution.
3785 * @param array $values
3786 * Previous form values before submit.
3788 * @param array $fields
3789 * The input form values.
3791 * @param array $errors
3796 public static function checkStatusValidation($values, &$fields, &$errors) {
3797 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3798 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3799 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3803 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3805 'Cancelled' => ['Completed', 'Refunded'],
3806 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3807 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3808 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3809 'Refunded' => ['Cancelled', 'Completed'],
3810 'Partially paid' => ['Completed'],
3811 'Pending refund' => ['Completed', 'Refunded'],
3814 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3815 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3817 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3818 1 => $contributionStatuses[$values['contribution_status_id']],
3819 2 => $contributionStatuses[$fields['contribution_status_id']],
3825 * Delete contribution of contact.
3829 * @param int $contactId
3833 public static function deleteContactContribution($contactId) {
3834 $contribution = new CRM_Contribute_DAO_Contribution();
3835 $contribution->contact_id
= $contactId;
3836 $contribution->find();
3837 while ($contribution->fetch()) {
3838 self
::deleteContribution($contribution->id
);
3843 * Get options for a given contribution field.
3845 * @param string $fieldName
3846 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3847 * @param array $props whatever is known about this dao object.
3849 * @return array|bool
3850 * @see CRM_Core_DAO::buildOptions
3853 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3854 $className = __CLASS__
;
3856 if (isset($props['orderColumn'])) {
3857 $params['orderColumn'] = $props['orderColumn'];
3859 switch ($fieldName) {
3860 // This field is not part of this object but the api supports it
3861 case 'payment_processor':
3862 $className = 'CRM_Contribute_BAO_ContributionPage';
3863 // Filter results by contribution page
3864 if (!empty($props['contribution_page_id'])) {
3865 $page = civicrm_api('contribution_page', 'getsingle', [
3867 'id' => ($props['contribution_page_id']),
3869 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3870 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3874 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3875 case 'honor_type_id':
3876 $className = 'CRM_Contribute_BAO_ContributionSoft';
3877 $fieldName = 'soft_credit_type_id';
3878 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3881 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3885 * Validate financial type.
3889 * @param int $financialTypeId
3890 * Financial Type id.
3892 * @param string $relationName
3894 * @return array|bool
3896 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3897 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3899 if (!$financialAccount) {
3900 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3906 * @param int $targetCid
3907 * @param $activityType
3908 * @param string $title
3909 * @param int $contributionId
3910 * @param string $totalAmount
3911 * @param string $currency
3912 * @param string $trxn_date
3914 * @throws \CRM_Core_Exception
3915 * @throws \CiviCRM_API3_Exception
3917 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3918 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3919 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3920 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3921 // source record id would be the contribution id
3922 $srcRecId = $contributionId;
3926 'source_contact_id' => $targetCid,
3927 'source_record_id' => $srcRecId,
3928 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3929 'subject' => $subject,
3930 'activity_date_time' => $date,
3931 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3932 'skipRecentView' => TRUE,
3935 // create activity with target contacts
3936 $session = CRM_Core_Session
::singleton();
3937 $id = $session->get('userID');
3939 $activityParams['source_contact_id'] = $id;
3940 $activityParams['target_contact_id'][] = $targetCid;
3942 civicrm_api3('Activity', 'create', $activityParams);
3946 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3950 * @param bool $getTrxnInfo
3951 * @param bool $usingLineTotal
3955 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3956 // @todo deprecate passing in component - always call with contribution.
3957 if ($component == 'event') {
3958 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3960 if (!$contributionId) {
3961 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3962 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3963 $id = $primaryParticipantId;
3965 if (!$contributionId) {
3970 elseif ($component == 'membership') {
3971 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3974 $contributionId = $id;
3977 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3978 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3980 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3981 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3983 if (empty($total['total_amount']) ||
$usingLineTotal) {
3984 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3987 $baseTrxnId = $total['trxn_id'];
3988 $total = $total['total_amount'];
3991 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3993 $contribution = civicrm_api3('Contribution', 'getsingle', [
3994 'id' => $contributionId,
3998 'contribution_status_id',
3999 'financial_type_id',
4003 $info['payLater'] = $contribution['is_pay_later'];
4004 $info['contribution_status'] = $contribution['contribution_status'];
4005 $info['currency'] = $contribution['currency'];
4007 $financialTypeId = $contribution['financial_type_id'];
4008 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4010 if ($paymentBalance == 0 && $info['payLater']) {
4011 // @todo - review - this looks very unlikely to be correct.
4012 // the balance should be correct based on payment transactions not
4014 $paymentBalance = $total;
4017 $info['total'] = $total;
4018 $info['paid'] = $total - $paymentBalance;
4019 $info['balance'] = $paymentBalance;
4021 $info['component'] = $component;
4023 if ($getTrxnInfo && $baseTrxnId) {
4024 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4026 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4028 ft.payment_instrument_id,
4029 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4031 FROM civicrm_contribution con
4032 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4033 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4034 AND ft.to_financial_account_id != %2
4035 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4036 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4037 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4039 WHERE con.id = %1 AND ft.is_payment = 1
4042 1 => [$contributionId, 'Integer'],
4043 2 => [$feeFinancialAccount, 'Integer'],
4045 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4046 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4048 while ($resultDAO->fetch()) {
4049 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4050 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4051 if ($resultDAO->card_type_id
) {
4052 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4053 $pantruncation = '';
4054 if ($resultDAO->pan_truncation
) {
4055 $pantruncation = ": {$resultDAO->pan_truncation}";
4057 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4060 // show payment edit link only for payments done via backoffice form
4061 $paymentEditLink = '';
4062 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4064 CRM_Core_Action
::UPDATE
=> [
4065 'name' => "<i class='crm-i fa-pencil'></i>",
4066 'url' => 'civicrm/payment/edit',
4067 'class' => 'medium-popup',
4068 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4069 'title' => ts('Edit Payment'),
4072 $paymentEditLink = CRM_Core_Action
::formLink(
4074 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4076 'id' => $resultDAO->id
,
4077 'contribution_id' => $contributionId,
4083 'id' => $resultDAO->id
,
4084 'total_amount' => $resultDAO->total_amount
,
4085 'financial_type' => $resultDAO->financial_account
,
4086 'payment_instrument' => $paidByLabel,
4087 'receive_date' => $resultDAO->trxn_date
,
4088 'trxn_id' => $resultDAO->trxn_id
,
4089 'status' => $statuses[$resultDAO->status_id
],
4090 'currency' => $resultDAO->currency
,
4091 'action' => $paymentEditLink,
4093 if ($paidByName == 'Check') {
4094 $val['check_number'] = $resultDAO->check_number
;
4098 $info['transaction'] = $rows;
4101 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4106 * Get the outstanding balance on a contribution.
4108 * @param int $contributionId
4109 * @param float $contributionTotal
4110 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4114 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4115 if ($contributionTotal === NULL) {
4116 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4119 return CRM_Utils_Money
::subtractCurrencies(
4121 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE) ?
: 0,
4122 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4127 * Get the tax amount (misnamed function).
4129 * @param array $params
4130 * @param bool $isLineItem
4134 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4135 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4137 // This function should be only called after standardisation (removal of
4138 // thousand separator & using a decimal point for cents separator.
4139 // However, we don't know if that is always true :-(
4140 // There is a deprecation notice tho :-)
4141 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4142 // Update contribution.
4143 if (!empty($params['id'])) {
4144 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4145 // there are no tax implications - early return.
4146 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4149 if (empty($params['prevContribution'])) {
4150 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4153 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4154 if (!isset($params[$field])) {
4155 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4156 // Tax amount gets added back on later....
4157 $params['total_amount'] = $params['prevContribution']->total_amount
-
4158 $params['prevContribution']->tax_amount
;
4161 $params[$field] = $params['prevContribution']->$field;
4162 if ($params[$field] != $params['prevContribution']->$field) {
4168 self
::calculateMissingAmountParams($params, $params['id']);
4169 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4170 // Assign tax Amount on update of contribution
4171 if (!empty($params['prevContribution']->tax_amount
)) {
4172 $params['tax_amount'] = 'null';
4173 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4174 foreach ($params['line_item'] as $setID => $priceField) {
4175 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4176 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4183 // New Contribution and update of contribution with tax rate financial type
4184 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4185 empty($params['skipLineItem']) && !$isLineItem
4187 $taxRateParams = $taxRates[$params['financial_type_id']];
4188 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4189 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4191 // Get Line Item on update of contribution
4192 if (isset($params['id'])) {
4193 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4196 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4198 foreach ($params['line_item'] as $setID => $priceField) {
4199 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4200 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4203 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4205 elseif (isset($params['api.line_item.create'])) {
4206 // Update total amount of contribution using lineItem
4207 $taxAmountArray = [];
4208 foreach ($params['api.line_item.create'] as $key => $value) {
4209 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4210 $taxRate = $taxRates[$value['financial_type_id']];
4211 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4212 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4215 $params['tax_amount'] = array_sum($taxAmountArray);
4216 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4219 // update line item of contrbution
4220 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4221 $taxRate = $taxRates[$params['financial_type_id']];
4222 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4223 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4230 * Check financial type validation on update of a contribution.
4232 * @param int $financialTypeId
4233 * Value of latest Financial Type.
4235 * @param int $contributionId
4238 * @param array $errors
4243 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4244 if (!empty($financialTypeId)) {
4245 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4246 if ($oldFinancialTypeId == $financialTypeId) {
4250 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4252 '1' => [$contributionId, 'Integer'],
4254 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4255 if ($result->N
> 1) {
4256 $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.');
4261 * Update related pledge payment payments.
4263 * This function has been refactored out of the back office contribution form and may
4264 * still overlap with other functions.
4266 * @param string $action
4267 * @param int $pledgePaymentID
4268 * @param int $contributionID
4269 * @param bool $adjustTotalAmount
4270 * @param float $total_amount
4271 * @param float $original_total_amount
4272 * @param int $contribution_status_id
4273 * @param int $original_contribution_status_id
4275 public static function updateRelatedPledge(
4281 $original_total_amount,
4282 $contribution_status_id,
4283 $original_contribution_status_id
4285 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4289 if ($pledgePaymentID) {
4290 //store contribution id in payment record.
4291 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4294 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4301 if (!$pledgePaymentID) {
4304 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4310 $updatePledgePaymentStatus = FALSE;
4312 // If either the status or the amount has changed we update the pledge status.
4313 if ($action & CRM_Core_Action
::ADD
) {
4314 $updatePledgePaymentStatus = TRUE;
4316 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4317 ($original_total_amount != $total_amount))
4319 $updatePledgePaymentStatus = TRUE;
4322 if ($updatePledgePaymentStatus) {
4323 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4325 $contribution_status_id,
4334 * Compute the stats values
4336 * @param string $stat either 'mode' or 'median'
4337 * @param string $sql
4338 * @param string $alias of civicrm_contribution
4340 * @return array|null
4344 public static function computeStats($stat, $sql, $alias = NULL) {
4345 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4350 * Is there only one line item attached to the contribution.
4356 * @throws \CiviCRM_API3_Exception
4358 public static function isSingleLineItem($id) {
4359 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4360 return ($lineItemCount == 1);
4364 * Complete an order.
4366 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4368 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4370 * Moving it out of the BaseIPN class is just the first step.
4372 * @param array $input
4374 * @param array $objects
4375 * @param CRM_Core_Transaction $transaction
4377 * @param CRM_Contribute_BAO_Contribution $contribution
4378 * @param bool $isPostPaymentCreate
4379 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4380 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4381 * transitioning related elements).
4384 * @throws \CRM_Core_Exception
4385 * @throws \CiviCRM_API3_Exception
4387 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isPostPaymentCreate = FALSE) {
4388 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4389 // The previous details are used when calculating line items so keep it before any code that 'does something'
4390 if (!empty($contribution->id
)) {
4391 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4393 $inputContributionWhiteList = [
4398 'payment_instrument_id',
4403 'contribution_status_id',
4407 if (self
::isSingleLineItem($primaryContributionID)) {
4408 $inputContributionWhiteList[] = 'financial_type_id';
4411 $participant = CRM_Utils_Array
::value('participant', $objects);
4412 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4413 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4414 $event = CRM_Utils_Array
::value('event', $objects);
4416 $paymentProcessorId = '';
4417 if (isset($objects['paymentProcessor'])) {
4418 if (is_array($objects['paymentProcessor'])) {
4419 $paymentProcessorId = $objects['paymentProcessor']['id'];
4422 $paymentProcessorId = $objects['paymentProcessor']->id
;
4426 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4428 $contributionParams = array_merge([
4429 'contribution_status_id' => $completedContributionStatusID,
4430 'source' => self
::getRecurringContributionDescription($contribution, $event),
4431 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4434 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4435 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4436 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4439 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4441 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4442 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4443 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4444 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4447 if ($recurringContributionID) {
4448 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4450 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4452 if (empty($contributionParams['receive_date']) && $changeDate) {
4453 $contributionParams['receive_date'] = $changeDate;
4456 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4457 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4460 if (isset($input['is_email_receipt'])) {
4461 $values['is_email_receipt'] = $input['is_email_receipt'];
4464 if ($input['component'] == 'contribute') {
4465 if ($contribution->contribution_page_id
) {
4466 // Figure out what we gain from this.
4467 // Note that we may have overwritten the is_email_receipt input, fix that below.
4468 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4470 elseif ($recurContrib && $recurringContributionID) {
4471 $values['amount'] = $recurContrib->amount
;
4472 $values['financial_type_id'] = $objects['contributionType']->id
;
4473 $values['title'] = $source = ts('Offline Recurring Contribution');
4476 if (isset($input['is_email_receipt'])) {
4477 // CRM-19601 - we may have overwritten this above.
4478 $values['is_email_receipt'] = $input['is_email_receipt'];
4480 elseif ($recurContrib && $recurringContributionID) {
4481 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4482 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4483 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4486 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4487 self
::updateMembershipBasedOnCompletionOfContribution(
4489 $primaryContributionID,
4495 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4496 if ($event->is_email_confirm
) {
4497 // @todo this should be set by the function that sends the mail after sending.
4498 $contributionParams['receipt_date'] = $changeDate;
4500 $participantParams['id'] = $participant->id
;
4501 $participantParams['status_id'] = 'Registered';
4502 civicrm_api3('Participant', 'create', $participantParams);
4506 $contributionParams['id'] = $contribution->id
;
4507 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4509 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4510 // unsetting it here does NOT cause any other contribution test to fail!
4511 unset($contributionParams['financial_type_id']);
4512 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4514 // Add new soft credit against current $contribution.
4515 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4516 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4519 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4520 'labelColumn' => 'name',
4523 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4524 $input['payment_processor'] = $paymentProcessorId;
4527 if (!empty($contribution->_relatedObjects
['participant'])) {
4528 $input['contribution_mode'] = 'participant';
4529 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4531 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4532 // @todo - use getRelatedMemberships instead
4533 $input['contribution_mode'] = 'membership';
4534 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4535 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4536 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4539 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4540 $transaction->commit();
4542 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4543 $contributionParams['contribution_status_id'], $input['amount']);
4545 // create an activity record
4546 if ($input['component'] == 'contribute') {
4548 $targetContactID = NULL;
4549 if (!empty($ids['related_contact'])) {
4550 $targetContactID = $contribution->contact_id
;
4551 $contribution->contact_id
= $ids['related_contact'];
4553 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4556 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4557 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4558 if (!array_key_exists('is_email_receipt', $values) ||
4559 $values['is_email_receipt'] == 1
4561 civicrm_api3('Contribution', 'sendconfirmation', [
4562 'id' => $contribution->id
,
4563 'payment_processor_id' => $paymentProcessorId,
4565 CRM_Core_Error
::debug_log_message("Receipt sent");
4568 CRM_Core_Error
::debug_log_message("Success: Database updated");
4569 return $contributionResult;
4573 * Send receipt from contribution.
4575 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4577 * Note that the compose message part has been moved to contribution
4578 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4580 * @param array $input
4581 * Incoming data from Payment processor.
4583 * Related object IDs.
4584 * @param int $contributionID
4585 * @param array $values
4586 * Values related to objects that have already been loaded.
4587 * @param bool $returnMessageText
4588 * Should text be returned instead of sent. This.
4589 * is because the function is also used to generate pdfs
4592 * @throws \CRM_Core_Exception
4593 * @throws \CiviCRM_API3_Exception
4595 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4596 $returnMessageText = FALSE) {
4598 $contribution = new CRM_Contribute_BAO_Contribution();
4599 $contribution->id
= $contributionID;
4600 if (!$contribution->find(TRUE)) {
4601 throw new CRM_Core_Exception('Contribution does not exist');
4603 $contribution->loadRelatedObjects($input, $ids, TRUE);
4604 // set receipt from e-mail and name in value
4605 if (!$returnMessageText) {
4606 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4608 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4609 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4610 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4611 civicrm_api3('Contribution', 'create', [
4612 'receipt_date' => 'now',
4613 'id' => $contribution->id
,
4620 * Generate From email and from name in an array values
4622 * @param array $input
4623 * @param \CRM_Contribute_BAO_Contribution $contribution
4627 public static function generateFromEmailAndName($input, $contribution) {
4628 // Use input value if supplied.
4629 if (!empty($input['receipt_from_email'])) {
4631 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4632 $input['receipt_from_email'],
4635 // if we are still empty see if we can use anything from a contribution page.
4637 if (!empty($contribution->contribution_page_id
)) {
4638 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4640 // if we are still empty see if we can use anything from a contribution page.
4641 if (!empty($pageValues['receipt_from_email'])) {
4643 $pageValues['receipt_from_name'],
4644 $pageValues['receipt_from_email'],
4647 // If we are still empty fall back to the domain or logged in user information.
4648 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4652 * Generate credit note id with next avaible number
4657 public static function createCreditNoteId() {
4658 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4660 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4661 $creditNoteId = NULL;
4665 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4666 $result = civicrm_api3('Contribution', 'getcount', [
4668 'creditnote_id' => $creditNoteId,
4670 } while ($result > 0);
4672 return $creditNoteId;
4676 * Load related memberships.
4680 * @return array $ids
4685 * Note that in theory it should be possible to retrieve these from the line_item table
4686 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4687 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4688 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4689 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4691 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4694 public function loadRelatedMembershipObjects($ids = []) {
4696 SELECT membership_id
4697 FROM civicrm_membership_payment
4698 WHERE contribution_id = %1 ";
4699 $params = [1 => [$this->id
, 'Integer']];
4700 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4702 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4703 while ($dao->fetch()) {
4704 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4705 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4709 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4710 foreach ($ids['membership'] as $id) {
4712 $membership = new CRM_Member_BAO_Membership();
4713 $membership->id
= $id;
4714 if (!$membership->find(TRUE)) {
4715 throw new Exception("Could not find membership record: $id");
4717 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4718 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4719 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4720 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4728 * This function is used to record partial payments for contribution
4730 * @param array $contribution
4732 * @param array $params
4734 * @return CRM_Financial_DAO_FinancialTrxn
4736 public static function recordPartialPayment($contribution, $params) {
4737 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4738 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4739 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4740 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4741 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4742 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4743 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4744 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4745 $balanceTrxnParams['currency'] = $contribution['currency'];
4746 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4747 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4748 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4749 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4750 $balanceTrxnParams['is_payment'] = 1;
4752 if (!empty($params['payment_processor'])) {
4753 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4754 // also anticipates it.
4755 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4756 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4758 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4762 * Get the description (source field) for the recurring contribution.
4764 * @param CRM_Contribute_BAO_Contribution $contribution
4765 * @param CRM_Event_DAO_Event|null $event
4768 * @throws \CiviCRM_API3_Exception
4770 protected static function getRecurringContributionDescription($contribution, $event) {
4771 if (!empty($contribution->source
)) {
4772 return $contribution->source
;
4774 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4775 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4776 'id' => $contribution->contribution_page_id
,
4777 'return' => 'title',
4779 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4782 return ts('Online Event Registration') . ': ' . $event->title
;
4784 elseif (!empty($contribution->contribution_recur_id
)) {
4785 return 'recurring contribution';
4791 * Function to add payments for contribution
4792 * for Partially Paid status
4794 * @param array $contributions
4795 * @param string $contributionStatusId
4798 public static function addPayments($contributions, $contributionStatusId = NULL) {
4799 // get financial trxn which is a payment
4800 $ftSql = "SELECT ft.id, ft.total_amount
4801 FROM civicrm_financial_trxn ft
4802 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4803 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4804 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4805 'labelColumn' => 'name',
4807 foreach ($contributions as $contribution) {
4808 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4809 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4813 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, [
4821 // store financial item Proportionaly.
4823 'total_amount' => $ftDao->total_amount
,
4824 'contribution_id' => $contribution->id
,
4826 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4831 * Function use to store line item proportionally in in entity financial trxn table
4833 * @param array $trxnParams
4835 * @param int $trxnId
4837 * @param float $contributionTotalAmount
4839 * @throws \CiviCRM_API3_Exception
4841 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4842 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4843 if (!empty($lineItems)) {
4844 // get financial item
4845 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4847 'contribution_total_amount' => $contributionTotalAmount,
4848 'trxn_total_amount' => $trxnParams['total_amount'],
4849 'trxn_id' => $trxnId,
4851 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4856 * Checks if line items total amounts
4857 * match the contribution total amount.
4859 * @param array $params
4860 * array of order params.
4862 * @throws \API_Exception
4864 public static function checkLineItems(&$params) {
4865 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4866 $lineItemAmount = 0;
4868 foreach ($params['line_items'] as &$lineItems) {
4869 foreach ($lineItems['line_item'] as &$item) {
4870 if (empty($item['financial_type_id'])) {
4871 $item['financial_type_id'] = $params['financial_type_id'];
4873 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4877 if (!isset($totalAmount)) {
4878 $params['total_amount'] = $lineItemAmount;
4881 $currency = CRM_Utils_Array
::value('currency', $params, '');
4883 if (empty($currency)) {
4884 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4887 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4888 throw new CRM_Contribute_Exception_CheckLineItemsException();
4894 * Get the financial account for the item associated with the new transaction.
4896 * @param array $params
4897 * @param int $default
4901 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4903 if (!empty($params['financial_account_id'])) {
4904 return $params['financial_account_id'];
4907 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4908 $preferredAccountsRelationships = [
4909 'Refunded' => 'Credit/Contra Revenue Account is',
4910 'Chargeback' => 'Chargeback Account is',
4913 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4914 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4915 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4917 $preferredAccountsRelationships[$contributionStatus]
4925 * ContributionPage values were being imposed onto values.
4927 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4928 * REALLY didn't want superimposed. The rest are left there in their overkill out
4931 * The rationale for making this explicit is that it was a case of carefully set values being
4932 * seemingly randonly overwritten without much care. In general I think array randomly setting
4933 * variables en mass is risky.
4935 * @param array $values
4939 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4940 $contributionPageValues = [];
4941 CRM_Contribute_BAO_ContributionPage
::setValues(
4942 $this->contribution_page_id
,
4943 $contributionPageValues
4946 // These are the values that I believe to be useful.
4949 'pay_later_receipt',
4951 'receipt_from_email',
4952 'receipt_from_name',
4956 'honoree_profile_id',
4957 'onbehalf_profile_id',
4958 'honor_block_is_active',
4959 // Kinda might be - but would be on the contribution...
4962 // Included for 'fear of regression' but can't justify any use for these....
4964 'payment_processor',
4965 'financial_type_id',
4966 'amount_block_is_active',
4971 'default_amount_id',
4975 'initial_amount_help_text',
4976 'initial_amount_label',
4978 'is_allow_other_amount',
4979 'is_billing_required',
4980 'is_confirm_enabled',
4981 'is_credit_card_only',
4983 'is_partial_payment',
4984 'is_recur_installments',
4985 'is_recur_interval',
4989 'min_initial_amount',
4990 'recur_frequency_unit',
4997 foreach ($valuesToCopy as $valueToCopy) {
4998 if (isset($contributionPageValues[$valueToCopy])) {
4999 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5006 * Get values of CiviContribute Settings
5007 * and check if its enabled or not.
5008 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5009 * in serialized form. Usually this should be stored as flat settings for each form fields
5010 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5011 * settings we will live with an inconsistency because it's too hard to change for now.
5012 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5015 * @param string $name
5016 * @param bool $checkInvoicing
5020 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5021 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5023 if ($checkInvoicing && empty($contributeSettings['invoicing'])) {
5028 return CRM_Utils_Array
::value($name, $contributeSettings);
5030 return $contributeSettings;
5034 * This function process contribution related objects.
5036 * @param int $contributionId
5037 * @param int $statusId
5038 * @param int|null $previousStatusId
5040 * @param string $receiveDate
5042 * @return null|string
5044 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5046 if (!$contributionId ||
!$statusId) {
5051 'contribution_id' => $contributionId,
5052 'contribution_status_id' => $statusId,
5053 'previous_contribution_status_id' => $previousStatusId,
5054 'receive_date' => $receiveDate,
5057 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5059 if (!is_array($updateResult) ||
5060 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5061 !is_array($updatedComponents) ||
5062 empty($updatedComponents)
5067 // get the user display name.
5069 SELECT display_name as displayName
5070 FROM civicrm_contact
5071 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5072 WHERE civicrm_contribution.id = {$contributionId}";
5073 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5075 // get the status message for user.
5076 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5078 if ($componentName == 'CiviMember') {
5079 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5080 CRM_Member_PseudoConstant
::membershipStatus()
5083 $statusNameMsgPart = 'updated';
5084 switch ($updatedStatusName) {
5087 $statusNameMsgPart = $updatedStatusName;
5091 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5092 1 => $userDisplayName,
5093 2 => $statusNameMsgPart,
5097 if ($componentName == 'CiviEvent') {
5098 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5099 CRM_Event_PseudoConstant
::participantStatus()
5101 if ($updatedStatusName == 'Cancelled') {
5102 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5104 elseif ($updatedStatusName == 'Registered') {
5105 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5109 if ($componentName == 'CiviPledge') {
5110 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5111 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5113 if ($updatedStatusName == 'Cancelled') {
5114 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5116 elseif ($updatedStatusName == 'Failed') {
5117 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5119 elseif ($updatedStatusName == 'Completed') {
5120 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5129 * Get the contribution as it is in the database before being updated.
5131 * @param int $contributionID
5133 * @return \CRM_Contribute_BAO_Contribution|null
5135 private static function getOriginalContribution($contributionID) {
5136 return self
::getValues(['id' => $contributionID]);
5140 * Get the amount for the financial item row.
5142 * Helper function to start to break down recordFinancialTransactions for readability.
5144 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5146 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5147 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5150 * @param array $params
5151 * Params as passed to contribution.create
5153 * @param string $context
5154 * changeFinancialType| changedAmount
5155 * @param array $lineItemDetails
5157 * @param bool $isARefund
5158 * Is this a refund / negative transaction.
5159 * @param int $previousLineItemTotal
5162 * @todo move recordFinancialAccounts & helper functions to their own class?
5165 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5166 if ($context == 'changedAmount') {
5167 $lineTotal = $lineItemDetails['line_total'];
5168 if ($lineTotal != $previousLineItemTotal) {
5169 $lineTotal -= $previousLineItemTotal;
5173 elseif ($context == 'changeFinancialType') {
5174 return -$lineItemDetails['line_total'];
5176 elseif ($context == 'changedStatus') {
5177 $cancelledTaxAmount = 0;
5179 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5181 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5183 elseif ($context === NULL) {
5184 // erm, yes because? but, hey, it's tested.
5185 return $lineItemDetails['line_total'];
5187 elseif (empty($lineItemDetails['line_total'])) {
5188 // follow legacy code path
5190 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5191 return $params['total_amount'];
5194 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5199 * Get the multiplier for adjusting rows.
5201 * If we are dealing with a refund or cancellation then it will be a negative
5202 * amount to reflect the negative transaction.
5204 * If we are changing Financial Type it will be a negative amount to
5205 * adjust down the old type.
5207 * @param int $contribution_status_id
5208 * @param string $context
5212 protected static function getMultiplier($contribution_status_id, $context) {
5213 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5220 * Does this transaction reflect a payment instrument change.
5222 * @param array $params
5223 * @param array $pendingStatuses
5227 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5228 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5230 if (array_key_exists('payment_instrument_id', $params)) {
5231 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5232 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5234 //check if status is changed from Pending to Completed
5235 // do not update payment instrument changes for Pending to Completed
5236 if (!($contributionStatus == 'Completed' &&
5237 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5242 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5243 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5244 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5248 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5249 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5251 // another special case when check number is changed, create new financial records
5252 // create financial trxn with negative amount
5260 * Update the memberships associated with a contribution if it has been completed.
5262 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5263 * load them in this function. Code clean up would compensate for any minor performance implication.
5265 * @param \CRM_Contribute_BAO_Contribution $contribution
5266 * @param int $primaryContributionID
5267 * @param string $changeDate
5269 * @throws \CRM_Core_Exception
5270 * @throws \CiviCRM_API3_Exception
5272 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5273 $memberships = self
::getRelatedMemberships($contribution->id
);
5274 foreach ($memberships as $membership) {
5275 $membershipParams = [
5276 'id' => $membership['id'],
5277 'contact_id' => $membership['contact_id'],
5278 'is_test' => $membership['is_test'],
5279 'membership_type_id' => $membership['membership_type_id'],
5280 'membership_activity_status' => 'Completed',
5283 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5284 $membershipParams['membership_type_id'],
5285 $membershipParams['is_test'],
5286 $membershipParams['id']
5289 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5290 // this picks up membership type changes during renewals
5291 // @todo this is almost certainly an obsolete sql call, the pre-change
5292 // membership is accessible via $this->_relatedObjects
5294 SELECT membership_type_id
5295 FROM civicrm_membership_log
5296 WHERE membership_id={$membershipParams['id']}
5299 $dao = CRM_Core_DAO
::executeQuery($sql);
5300 if ($dao->fetch()) {
5301 if (!empty($dao->membership_type_id
)) {
5302 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5305 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5306 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5307 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5308 // 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.
5309 // @todo once apiv4 ships with core switch to that & find sanity.
5310 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5311 $membershipParams['membership_type_id'],
5312 $primaryContributionID
5315 // @todo remove all this stuff in favour of letting the api call further down handle in
5316 // (it is a duplication of what the api does).
5317 $dates = array_fill_keys([
5322 if ($currentMembership) {
5324 * Fixed FOR CRM-4433
5325 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5326 * when Contribution mode is notify and membership is for renewal )
5328 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5330 // @todo - we should pass membership_type_id instead of null here but not
5331 // adding as not sure of testing
5332 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5333 $changeDate, NULL, $membershipParams['num_terms']
5335 $dates['join_date'] = $currentMembership['join_date'];
5338 //get the status for membership.
5339 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5341 $dates['join_date'],
5344 $membershipParams['membership_type_id'],
5348 unset($dates['end_date']);
5349 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5350 //we might be renewing membership,
5351 //so make status override false.
5352 $membershipParams['is_override'] = FALSE;
5353 $membershipParams['status_override_end_date'] = 'null';
5355 //CRM-17723 - reset static $relatedContactIds array()
5356 // @todo move it to Civi Statics.
5358 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5359 civicrm_api3('Membership', 'create', $membershipParams);
5364 * Get payment links as they relate to a contribution.
5366 * If a payment can be made then include a payment link & if a refund is appropriate
5367 * then a refund link.
5370 * @param float $balance
5371 * @param string $contributionStatus
5374 * $actionLinks Links array containing:
5378 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5379 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5380 // In general the balance is the best way to determine if a payment can be added or not,
5381 // but not for Failed contributions, where we don't accept additional payments at the moment.
5382 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5383 // do accept more payments agains them.
5387 if ((int) $balance > 0) {
5388 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5390 'url' => CRM_Utils_System
::url('civicrm/payment', [
5396 'title' => ts('Submit Credit Card payment'),
5400 'url' => CRM_Utils_System
::url('civicrm/payment', [
5405 'title' => ts('Record Payment'),
5408 elseif ((int) $balance < 0) {
5410 'url' => CRM_Utils_System
::url('civicrm/payment', [
5415 'title' => ts('Record Refund'),
5418 return $actionLinks;
5422 * Get a query to determine the amount donated by the contact/s in the current financial year.
5424 * @param array $contactIDs
5428 public static function getAnnualQuery($contactIDs) {
5429 $contactIDs = implode(',', $contactIDs);
5430 $config = CRM_Core_Config
::singleton();
5431 $currentMonth = date('m');
5432 $currentDay = date('d');
5434 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5436 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5437 (int) $config->fiscalYearStart
['d'] > $currentDay
5440 $year = date('Y') - 1;
5445 $nextYear = $year +
1;
5447 if ($config->fiscalYearStart
) {
5448 $newFiscalYearStart = $config->fiscalYearStart
;
5449 if ($newFiscalYearStart['M'] < 10) {
5450 // This is just a clumsy way of adding padding.
5451 // @todo next round look for a nicer way.
5452 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5454 if ($newFiscalYearStart['d'] < 10) {
5455 // This is just a clumsy way of adding padding.
5456 // @todo next round look for a nicer way.
5457 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5459 $config->fiscalYearStart
= $newFiscalYearStart;
5460 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5463 // First of January.
5466 $startDate = "$year$monthDay";
5467 $endDate = "$nextYear$monthDay";
5470 'contact_id' => 'IN (' . $contactIDs . ')',
5471 'is_test' => ' = 0',
5472 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5474 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5475 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5478 foreach ($whereClauses as $key => $clause) {
5479 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5481 $whereClauseString = implode(' AND ', $clauses);
5483 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5484 // this group by + having on contribution_status_id improves performance
5486 SELECT COUNT(*) as count,
5487 SUM(total_amount) as amount,
5488 AVG(total_amount) as average,
5490 FROM civicrm_contribution b
5491 WHERE " . $whereClauseString . "
5492 GROUP BY currency, contribution_status_id
5493 HAVING $havingClause
5499 * Assign Test Value.
5501 * @param string $fieldName
5502 * @param array $fieldDef
5503 * @param int $counter
5505 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5506 if ($fieldName == 'tax_amount') {
5507 $this->{$fieldName} = "0.00";
5509 elseif ($fieldName == 'net_amount') {
5510 $this->{$fieldName} = "2.00";
5512 elseif ($fieldName == 'total_amount') {
5513 $this->{$fieldName} = "3.00";
5515 elseif ($fieldName == 'fee_amount') {
5516 $this->{$fieldName} = "1.00";
5519 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5524 * Check if contribution has participant/membership payment.
5526 * @param int $contributionId
5531 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5532 // get line item for contribution
5533 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5534 // check if line item is for membership or participant
5535 foreach ($lineItems as $items) {
5536 if ($items['entity_table'] == 'civicrm_participant') {
5540 elseif ($items['entity_table'] == 'civicrm_membership') {
5552 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5554 * @param array $trxnParams
5555 * Financial trxn params
5556 * @param array $contributionParams
5557 * Contribution Params
5561 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5562 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5565 $statusId = $contributionParams['contribution']->contribution_status_id
;
5566 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5567 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5568 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5569 // Return if contribution status is not completed.
5570 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5571 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5572 && $contributionParams['prevContribution']->is_pay_later
== 0
5578 $params = $trxnParams;
5579 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5580 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5581 $params['to_financial_account_id'] = $arAccountId;
5582 $params['status_id'] = array_search('Pending', $contributionStatuses);
5583 $params['is_payment'] = FALSE;
5584 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5585 self
::$_trxnIDs[] = $trxn->id
;
5586 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5590 * Calculate financial item amount when contribution is updated.
5592 * @param array $params
5593 * contribution params
5594 * @param array $amountParams
5596 * @param string $context
5600 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5601 if (!empty($params['is_quick_config'])) {
5602 $amount = $amountParams['item_amount'];
5604 $amount = $params['total_amount'];
5605 if ($context === NULL) {
5606 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5611 $amount = $amountParams['line_total'];
5612 if ($context == 'changedAmount') {
5613 $amount -= $amountParams['previous_line_total'];
5615 $amount *= $amountParams['diff'];
5621 * Retrieve Sales Tax Financial Accounts.
5627 public static function getSalesTaxFinancialAccounts() {
5628 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5629 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5630 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5631 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5632 $queryParams = [1 => [$accountRel, 'Integer']];
5633 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5634 $financialAccount = [];
5635 while ($dao->fetch()) {
5636 $financialAccount[$dao->id
] = $dao->id
;
5638 return $financialAccount;
5642 * Create tax entry in civicrm_entity_financial_trxn table.
5644 * @param array $entityParams
5646 * @param array $eftParams
5648 * @throws \CiviCRM_API3_Exception
5650 public static function createProportionalEntry($entityParams, $eftParams) {
5652 if ($entityParams['contribution_total_amount'] != 0) {
5653 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5655 // Record Entity Financial Trxn; CRM-20145
5656 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5657 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5661 * Create array of last financial item id's.
5663 * @param int $contributionId
5667 public static function getLastFinancialItemIds($contributionId) {
5668 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5669 FROM civicrm_financial_item fi
5670 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5671 WHERE li.contribution_id = %1";
5672 $dao = CRM_Core_DAO
::executeQuery($sql, [
5678 $ftIds = $taxItems = [];
5679 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5680 while ($dao->fetch()) {
5681 /* if sales tax item*/
5682 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5683 $taxItems[$dao->price_field_value_id
] = [
5684 'financial_item_id' => $dao->id
,
5685 'amount' => $dao->tax_amount
,
5689 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5692 return [$ftIds, $taxItems];
5696 * Create proportional entries in civicrm_entity_financial_trxn.
5698 * @param array $entityParams
5700 * @param array $lineItems
5702 * @param array $ftIds
5704 * @param array $taxItems
5706 * @throws \CiviCRM_API3_Exception
5708 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5710 'entity_table' => 'civicrm_financial_item',
5711 'financial_trxn_id' => $entityParams['trxn_id'],
5713 foreach ($lineItems as $key => $value) {
5714 if ($value['qty'] == 0) {
5717 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5718 $entityParams['line_item_amount'] = $value['line_total'];
5719 self
::createProportionalEntry($entityParams, $eftParams);
5720 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5721 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5722 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5723 self
::createProportionalEntry($entityParams, $eftParams);
5729 * Load entities related to the contribution into $this->_relatedObjects.
5733 * @throws \CRM_Core_Exception
5735 protected function loadRelatedEntitiesByID($ids) {
5737 'contact' => 'CRM_Contact_BAO_Contact',
5738 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5739 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5740 'financialType' => 'CRM_Financial_BAO_FinancialType',
5741 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5743 foreach ($entities as $entity => $bao) {
5744 if (!empty($ids[$entity])) {
5745 $this->_relatedObjects
[$entity] = new $bao();
5746 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5747 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5748 throw new CRM_Core_Exception($entity . ' could not be loaded');
5755 * Should an email receipt be sent for this contribution when complete.
5757 * @param array $input
5761 protected function isEmailReceipt($input) {
5762 if (isset($input['is_email_receipt'])) {
5763 return $input['is_email_receipt'];
5765 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5766 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5772 * Function to replace contribution tokens.
5774 * @param array $contributionIds
5776 * @param string $subject
5778 * @param array $subjectToken
5780 * @param string $text
5782 * @param string $html
5784 * @param array $messageToken
5786 * @param bool $escapeSmarty
5789 * @throws \CiviCRM_API3_Exception
5791 public static function replaceContributionTokens(
5800 if (empty($contributionIds)) {
5803 $contributionDetails = [];
5804 foreach ($contributionIds as $id) {
5805 $result = self
::getContributionTokenValues($id, $messageToken);
5806 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5807 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5808 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5810 return $contributionDetails;
5814 * Get the contribution fields for $id and display labels where
5815 * appropriate (if the token is present).
5818 * @param array $messageToken
5821 public static function getContributionTokenValues($id, $messageToken) {
5825 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5826 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5827 if (!empty($messageToken)) {
5828 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5829 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5830 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5838 * Get invoice_number for contribution.
5840 * @param int $contributionID
5844 public static function getInvoiceNumber($contributionID) {
5845 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5846 return $invoicePrefix . $contributionID;
5853 * Load the values needed for the event message.
5855 * @param int $eventID
5856 * @param int $participantID
5857 * @param int|null $contributionID
5860 * @throws \CRM_Core_Exception
5862 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5867 $values = ['event' => []];
5869 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5870 // add custom fields for event
5871 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5873 $eventCustomGroup = [];
5874 foreach ($eventGroupTree as $key => $group) {
5875 if ($key === 'info') {
5879 foreach ($group['fields'] as $k => $customField) {
5880 $groupLabel = $group['title'];
5881 if (!empty($customField['customValue'])) {
5882 foreach ($customField['customValue'] as $customFieldValues) {
5883 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5888 $values['event']['customGroup'] = $eventCustomGroup;
5890 //get participant details
5891 $participantParams = [
5892 'id' => $participantID,
5895 $values['participant'] = [];
5897 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5898 // add custom fields for event
5899 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5900 $participantCustomGroup = [];
5901 foreach ($participantGroupTree as $key => $group) {
5902 if ($key === 'info') {
5906 foreach ($group['fields'] as $k => $customField) {
5907 $groupLabel = $group['title'];
5908 if (!empty($customField['customValue'])) {
5909 foreach ($customField['customValue'] as $customFieldValues) {
5910 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5915 $values['participant']['customGroup'] = $participantCustomGroup;
5917 //get location details
5919 'entity_id' => $eventID,
5920 'entity_table' => 'civicrm_event',
5922 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5925 'entity_table' => 'civicrm_event',
5926 'entity_id' => $eventID,
5927 'module' => 'CiviEvent',
5930 list($custom_pre_id,
5932 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5934 $values['custom_pre_id'] = $custom_pre_id;
5935 $values['custom_post_id'] = $custom_post_ids;
5937 // set lineItem for event contribution
5938 if ($contributionID) {
5939 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5940 if (!empty($participantIds)) {
5941 foreach ($participantIds as $pIDs) {
5942 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5943 if (!CRM_Utils_System
::isNull($lineItem)) {
5944 $values['lineItem'][] = $lineItem;