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: " . 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 self
::recordFinancialAccounts($params);
246 if (self
::isUpdateToRecurringContribution($params)) {
247 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
248 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
249 $contributionStatus[$params['contribution_status_id']],
250 CRM_Utils_Array
::value('receive_date', $params)
254 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
256 if ($contributionID) {
257 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
260 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
267 * Is this contribution updating an existing recurring contribution.
269 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
270 * pending payment is being confirmed (or failing).
272 * @param array $params
276 public static function isUpdateToRecurringContribution($params) {
277 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
280 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
283 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
286 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
287 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
294 * Get defaults for new entity.
298 public static function getDefaults() {
300 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
301 FALSE, FALSE, FALSE, 'AND is_default = 1')
303 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
304 'receive_date' => date('Y-m-d H:i:s'),
309 * Fetch the object and store the values in the values array.
311 * @param array $params
312 * Input parameters to find object.
313 * @param array $values
314 * Output values of the object.
316 * The array that holds all the db ids.
318 * @return CRM_Contribute_BAO_Contribution|null
319 * The found object or null
321 public static function getValues($params, &$values = [], &$ids = []) {
322 if (empty($params)) {
325 $contribution = new CRM_Contribute_BAO_Contribution();
327 $contribution->copyValues($params);
329 if ($contribution->find(TRUE)) {
330 $ids['contribution'] = $contribution->id
;
332 CRM_Core_DAO
::storeValues($contribution, $values);
334 return $contribution;
336 // return by reference
342 * Get the values and resolve the most common mappings.
344 * Since contribution status is resolved in almost every function that calls getValues it makes
345 * sense to have an extra function to resolve it rather than repeat the code.
347 * Think carefully before adding more mappings to be resolved as there could be performance implications
348 * if this function starts to be called from more iterative functions.
350 * @param array $params
351 * Input parameters to find object.
354 * Array of the found contribution.
355 * @throws CRM_Core_Exception
357 public static function getValuesWithMappings($params) {
359 $contribution = self
::getValues($params, $values, $ids);
360 if (is_null($contribution)) {
361 throw new CRM_Core_Exception('No contribution found');
363 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
368 * Calculate net_amount & fee_amount if they are not set.
370 * Net amount should be total - fee.
371 * This should only be called for new contributions.
373 * @param array $params
374 * Params for a new contribution before they are saved.
375 * @param int|null $contributionID
376 * Contribution ID if we are dealing with an update.
378 * @throws \CiviCRM_API3_Exception
380 public static function calculateMissingAmountParams(&$params, $contributionID) {
381 if (!$contributionID && !isset($params['fee_amount'])) {
382 if (isset($params['total_amount']) && isset($params['net_amount'])) {
383 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
386 $params['fee_amount'] = 0;
389 if (!isset($params['net_amount'])) {
390 if (!$contributionID) {
391 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
394 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
395 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
396 // net_amount may need adjusting.
397 $contribution = civicrm_api3('Contribution', 'getsingle', [
398 'id' => $contributionID,
399 'return' => ['total_amount', 'net_amount', 'fee_amount'],
401 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
402 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
403 $params['net_amount'] = $totalAmount - $feeAmount;
411 * @param $billingLocationTypeID
415 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
416 $hasBillingField = FALSE;
425 //build address array
427 $addressParams['location_type_id'] = $billingLocationTypeID;
428 $addressParams['is_billing'] = 1;
430 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
431 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
432 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
433 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
435 foreach ($billingFields as $value) {
436 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
437 if (!empty($addressParams[$value])) {
438 $hasBillingField = TRUE;
441 return [$hasBillingField, $addressParams];
445 * Get address params ready to be passed to the payment processor.
447 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
448 * To create an address we need state_province_id.
450 * @param array $params
451 * @param int $billingLocationTypeID
455 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
456 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
457 foreach ($addressParams as $name => $field) {
458 if (substr($name, 0, 8) == 'billing_') {
459 $addressParams[substr($name, 9)] = $addressParams[$field];
462 return [$hasBillingField, $addressParams];
466 * Get the number of terms for this contribution for a given membership type
467 * based on querying the line item table and relevant price field values
468 * Note that any one contribution should only be able to have one line item relating to a particular membership
471 * @param int $membershipTypeID
473 * @param int $contributionID
477 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
478 $numTerms = CRM_Core_DAO
::singleValueQuery("
479 SELECT membership_num_terms FROM civicrm_line_item li
480 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
481 WHERE contribution_id = %1 AND membership_type_id = %2",
482 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
484 // default of 1 is precautionary
485 return empty($numTerms) ?
1 : $numTerms;
489 * Takes an associative array and creates a contribution object.
491 * @param array $params
492 * (reference ) an assoc array of name/value pairs.
494 * The array that holds all the db ids.
496 * @return CRM_Contribute_BAO_Contribution
498 public static function create(&$params, $ids = []) {
499 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
500 $action = $contributionID ?
'edit' : 'create';
507 'revenue_recognition_date',
509 foreach ($dateFields as $df) {
510 if (isset($params[$df])) {
511 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
515 $transaction = new CRM_Core_Transaction();
518 $contribution = self
::add($params, $ids);
520 catch (CRM_Core_Exception
$e) {
521 $transaction->rollback();
525 $params['contribution_id'] = $contribution->id
;
527 if (!empty($params['custom']) &&
528 is_array($params['custom'])
530 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
533 $session = CRM_Core_Session
::singleton();
535 if (!empty($params['note'])) {
537 'entity_table' => 'civicrm_contribution',
538 'note' => $params['note'],
539 'entity_id' => $contribution->id
,
540 'contact_id' => $session->get('userID'),
541 'modified_date' => date('Ymd'),
543 if (!$noteParams['contact_id']) {
544 $noteParams['contact_id'] = $params['contact_id'];
546 CRM_Core_BAO_Note
::add($noteParams);
549 // make entry in batch entity batch table
550 if (!empty($params['batch_id'])) {
551 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
558 $retrieveRequired = 0;
559 foreach ($titleFields as $titleField) {
560 if (!isset($contribution->$titleField)) {
561 $retrieveRequired = 1;
565 if ($retrieveRequired == 1) {
566 $contribution->find(TRUE);
570 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
572 $transaction->commit();
574 $activity = civicrm_api3('Activity', 'get', [
575 'source_record_id' => $contribution->id
,
576 'options' => ['limit' => 1],
578 'activity_type_id' => 'Contribution',
579 'return' => ['id', 'campaign'],
582 //CRM-18406: Update activity when edit contribution.
583 if ($activity['count']) {
584 // CRM-13237 : if activity record found, update it with campaign id of contribution
585 // @todo compare campaign ids first.
586 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
587 $contribution->activity_id
= $activity['id'];
590 if (empty($contribution->contact_id
)) {
591 $contribution->find(TRUE);
593 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
595 // do not add to recent items for import, CRM-4399
596 if (empty($params['skipRecentView'])) {
597 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
598 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
600 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
607 $retrieveRequired = 0;
608 foreach ($titleFields as $titleField) {
609 if (!isset($contribution->$titleField)) {
610 $retrieveRequired = 1;
614 if ($retrieveRequired == 1) {
615 $contribution->find(TRUE);
617 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
618 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
621 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
622 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
623 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
627 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
628 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
629 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
633 // add the recently created Contribution
634 CRM_Utils_Recent
::add($title,
638 $contribution->contact_id
,
644 return $contribution;
648 * Get the values for pseudoconstants for name->value and reverse.
650 * @param array $defaults
651 * (reference) the default values, some of which need to be resolved.
652 * @param bool $reverse
653 * True if we want to resolve the values in the reverse direction (value -> name).
655 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
656 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
657 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
658 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
659 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
663 * Convert associative array names to values and vice-versa.
665 * This function is used by both the web form layer and the api. Note that
666 * the api needs the name => value conversion, also the view layer typically
667 * requires value => name conversion
669 * @param array $defaults
670 * @param string $property
671 * @param array $lookup
672 * @param bool $reverse
676 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
677 $id = $property . '_id';
679 $src = $reverse ?
$property : $id;
680 $dst = $reverse ?
$id : $property;
682 if (!array_key_exists($src, $defaults)) {
686 $look = $reverse ?
array_flip($lookup) : $lookup;
688 if (is_array($look)) {
689 if (!array_key_exists($defaults[$src], $look)) {
693 $defaults[$dst] = $look[$defaults[$src]];
698 * Retrieve DB object based on input parameters.
700 * It also stores all the retrieved values in the default array.
702 * @param array $params
703 * (reference ) an assoc array of name/value pairs.
704 * @param array $defaults
705 * (reference ) an assoc array to hold the name / value pairs.
706 * in a hierarchical manner
708 * (reference) the array that holds all the db ids.
710 * @return CRM_Contribute_BAO_Contribution
712 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
713 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
714 return $contribution;
718 * Combine all the importable fields from the lower levels object.
720 * The ordering is important, since currently we do not have a weight
721 * scheme. Adding weight is super important and should be done in the
722 * next week or so, before this can be called complete.
724 * @param string $contactType
725 * @param bool $status
728 * array of importable Fields
730 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
731 if (!self
::$_importableFields) {
732 if (!self
::$_importableFields) {
733 self
::$_importableFields = [];
737 $fields = ['' => ['title' => ts('- do not import -')]];
740 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
743 $note = CRM_Core_DAO_Note
::import();
744 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
745 unset($tmpFields['option_value']);
746 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
747 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
749 // Using new Dedupe rule.
751 'contact_type' => $contactType,
752 'used' => 'Unsupervised',
754 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
755 $tmpContactField = [];
756 if (is_array($fieldsArray)) {
757 foreach ($fieldsArray as $value) {
758 //skip if there is no dupe rule
759 if ($value == 'none') {
762 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
767 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
768 $tmpContactField[trim($value)] = $contactFields[trim($value)];
770 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
773 $title = $tmpContactField[trim($value)]['title'];
775 $tmpContactField[trim($value)]['title'] = $title;
779 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
780 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
781 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
782 $fields = array_merge($fields, $tmpContactField);
783 $fields = array_merge($fields, $tmpFields);
784 $fields = array_merge($fields, $note);
785 $fields = array_merge($fields, $optionFields);
786 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
787 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
788 self
::$_importableFields = $fields;
790 return self
::$_importableFields;
794 * Combine all the exportable fields from the lower level objects.
796 * @param bool $checkPermission
799 * array of exportable Fields
801 public static function &exportableFields($checkPermission = TRUE) {
802 if (!self
::$_exportableFields) {
803 if (!self
::$_exportableFields) {
804 self
::$_exportableFields = [];
807 $fields = CRM_Contribute_DAO_Contribution
::export();
808 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
809 $fields = array_merge(
811 CRM_Contribute_DAO_Product
::export(),
812 CRM_Contribute_DAO_ContributionProduct
::export(),
813 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
815 'contribution_product_id' => [
816 'title' => ts('Premium'),
817 'name' => 'contribution_product_id',
818 'where' => 'civicrm_product.id',
819 'data_type' => CRM_Utils_Type
::T_INT
,
825 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
827 $contributionPage = [
828 'contribution_page' => [
829 'title' => ts('Contribution Page'),
830 'name' => 'contribution_page',
831 'where' => 'civicrm_contribution_page.title',
832 'data_type' => CRM_Utils_Type
::T_STRING
,
836 $contributionNote = [
837 'contribution_note' => [
838 'title' => ts('Contribution Note'),
839 'name' => 'contribution_note',
840 'data_type' => CRM_Utils_Type
::T_TEXT
,
845 'contribution_batch' => [
846 'title' => ts('Batch Name'),
852 'contribution_campaign_title' => [
853 'title' => ts('Campaign Title'),
854 'name' => 'campaign_title',
855 'where' => 'civicrm_campaign.title',
856 'data_type' => CRM_Utils_Type
::T_STRING
,
859 $softCreditFields = [
860 'contribution_soft_credit_name' => [
861 'name' => 'contribution_soft_credit_name',
862 'title' => ts('Soft Credit For'),
863 'where' => 'civicrm_contact_d.display_name',
864 'data_type' => CRM_Utils_Type
::T_STRING
,
866 'contribution_soft_credit_amount' => [
867 'name' => 'contribution_soft_credit_amount',
868 'title' => ts('Soft Credit Amount'),
869 'where' => 'civicrm_contribution_soft.amount',
870 'data_type' => CRM_Utils_Type
::T_MONEY
,
872 'contribution_soft_credit_type' => [
873 'name' => 'contribution_soft_credit_type',
874 'title' => ts('Soft Credit Type'),
875 'where' => 'contribution_softcredit_type.label',
876 'data_type' => CRM_Utils_Type
::T_STRING
,
878 'contribution_soft_credit_contribution_id' => [
879 'name' => 'contribution_soft_credit_contribution_id',
880 'title' => ts('Soft Credit For Contribution ID'),
881 'where' => 'civicrm_contribution_soft.contribution_id',
882 'data_type' => CRM_Utils_Type
::T_INT
,
884 'contribution_soft_credit_contact_id' => [
885 'name' => 'contribution_soft_credit_contact_id',
886 'title' => ts('Soft Credit For Contact ID'),
887 'where' => 'civicrm_contact_d.id',
888 'data_type' => CRM_Utils_Type
::T_INT
,
892 $fields = array_merge($fields, $contributionPage,
893 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
894 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
897 self
::$_exportableFields = $fields;
900 return self
::$_exportableFields;
904 * Record an activity when a payment is received.
906 * @todo this is intended to be moved to payment BAO class as a protected function
907 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
908 * merit it's own function as it makes the code less rather than more readable.
910 * @param int $contributionId
911 * @param int $participantId
912 * @param string $totalAmount
913 * @param string $currency
914 * @param string $trxnDate
916 * @throws \CRM_Core_Exception
917 * @throws \CiviCRM_API3_Exception
919 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
920 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
922 if ($participantId) {
923 $inputParams['id'] = $participantId;
926 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
927 $entityObj = $entityObj[$participantId];
928 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
931 $entityObj = new CRM_Contribute_BAO_Contribution();
932 $entityObj->id
= $contributionId;
933 $entityObj->find(TRUE);
934 $title = ts('Contribution');
936 // @todo per block above this is not a logical splitting off of functionality.
937 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
941 * Get the value for the To Financial Account.
943 * @param $contribution
948 public static function getToFinancialAccount($contribution, $params) {
949 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
950 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
952 array_search('Pending', $contributionStatuses),
953 array_search('In Progress', $contributionStatuses),
955 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
956 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
958 elseif (!empty($params['payment_processor'])) {
959 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['payment_processor'], NULL, 'civicrm_payment_processor');
961 elseif (!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'],
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 $processContribution = FALSE;
1020 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1021 if (is_array($memberships)) {
1022 foreach ($memberships as $membership) {
1024 //Update Membership status if there is no other completed contribution associated with the membership.
1025 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1026 foreach ($relatedContributions as $contriId) {
1027 if ($contriId == $contributionId) {
1030 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1031 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1035 if ($membership && $update) {
1036 $newStatus = array_search('Cancelled', $membershipStatuses);
1039 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1041 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1042 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1043 'target_contact_id' => $membership->contact_id
,
1044 'source_record_id' => $membership->id
,
1045 'activity_type_id' => 'Change Membership Status',
1046 'status_id' => 'Completed',
1047 'priority_id' => 'Normal',
1048 'activity_date_time' => 'now',
1051 $membership->status_id
= $newStatus;
1052 $membership->is_override
= TRUE;
1053 $membership->status_override_end_date
= 'null';
1054 $membership->save();
1055 civicrm_api3('activity', 'create', $activityParam);
1057 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1058 if ($processContributionObject) {
1059 $processContribution = TRUE;
1066 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1067 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1069 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1070 if ($processContributionObject) {
1071 $processContribution = TRUE;
1075 if ($pledgePayment) {
1076 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1078 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1079 if ($processContributionObject) {
1080 $processContribution = TRUE;
1083 return [$updateResult, $processContribution];
1087 * Do any accounting updates required as a result of a contribution status change.
1089 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1090 * this may attempt to add a payment. We need to resolve that....
1092 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1093 * then updates the contribution but this process should not also record another financial trxn.
1094 * Currently we have weak detection fot that scenario & where it is detected the first returned
1095 * value is FALSE - meaning 'do not continue'.
1097 * We should also look at the fact that the calling function - updateFinancialAccounts
1098 * bunches together some disparate processes rather than having separate appropriate
1101 * @param array $params
1102 * @param string $context
1103 * @param array $previousContributionStatus
1104 * @param string $currentContributionStatus
1107 * Return indicates whether the updateFinancialAccounts function should continue & whether this is a refund.
1109 private static function updateFinancialAccountsOnContributionStatusChange(&$params, $context, $previousContributionStatus, $currentContributionStatus) {
1111 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1112 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1113 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1114 // why it is here or where it is handled instead.
1115 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1116 && $currentContributionStatus == 'Partially paid'))
1118 return [FALSE, $isARefund];
1120 if ($context == 'changedStatus') {
1121 if ($previousContributionStatus == 'Completed'
1122 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
1125 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1126 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1127 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
1128 $creditNoteId = self
::createCreditNoteId();
1129 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1132 elseif (($previousContributionStatus == 'Pending'
1133 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1135 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1136 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1138 if ($currentContributionStatus == 'Cancelled') {
1139 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1140 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1141 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1142 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
1143 $creditNoteId = self
::createCreditNoteId();
1144 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
1148 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1149 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1153 if (($previousContributionStatus == 'Pending'
1154 ||
$previousContributionStatus == 'In Progress')
1155 && ($currentContributionStatus == 'Completed')
1157 if (empty($params['line_item'])) {
1159 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1160 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1161 // & this can be removed
1162 return [FALSE, $isARefund];
1164 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1165 // This is an update so original currency if none passed in.
1166 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1168 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1169 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1170 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1171 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1172 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1173 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1176 'entity_table' => 'civicrm_financial_item',
1178 foreach ($params['line_item'] as $fieldId => $fields) {
1179 foreach ($fields as $fieldValueId => $lineItemDetails) {
1182 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1185 2 => [$lineItemDetails['id'], 'Integer'],
1187 CRM_Core_DAO
::executeQuery($query, $fparams);
1189 1 => [$lineItemDetails['id'], 'Integer'],
1191 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1192 while ($financialItem->fetch()) {
1193 $entityParams['entity_id'] = $financialItem->id
;
1194 $entityParams['amount'] = $financialItem->amount
;
1195 foreach (self
::$_trxnIDs as $tID) {
1196 $entityParams['financial_trxn_id'] = $tID;
1197 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1202 return [FALSE, $isARefund];
1205 return [TRUE, $isARefund];
1211 public function addSelectWhereClause() {
1212 $whereClauses = parent
::addSelectWhereClause();
1213 if ($whereClauses !== []) {
1214 // In this case permisssions have been applied & we assume the
1215 // financialaclreport is applying these
1216 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1217 return $whereClauses;
1220 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1221 return $whereClauses;
1223 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1224 if (empty($types)) {
1225 $whereClauses['financial_type_id'] = 'IN (0)';
1228 $whereClauses['financial_type_id'] = [
1229 'IN (' . implode(',', array_keys($types)) . ')',
1232 return $whereClauses;
1236 * @param null $status
1237 * @param null $startDate
1238 * @param null $endDate
1240 * @return array|null
1242 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1246 $where[] = 'contribution_status_id = 1';
1250 $where[] = 'contribution_status_id = 3';
1255 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1258 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1260 $financialTypeACLJoin = '';
1261 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1262 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1263 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1264 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1265 if ($financialTypes) {
1266 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1267 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1270 $where[] = "c.financial_type_id IN (0)";
1274 $whereCond = implode(' AND ', $where);
1277 SELECT sum( total_amount ) as total_amount,
1278 count( c.id ) as total_count,
1280 FROM civicrm_contribution c
1281 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1282 $financialTypeACLJoin
1284 AND ( is_test = 0 OR is_test IS NULL )
1285 AND contact.is_deleted = 0
1289 $dao = CRM_Core_DAO
::executeQuery($query);
1292 while ($dao->fetch()) {
1293 $count +
= $dao->total_count
;
1294 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1298 'amount' => implode(', ', $amount),
1306 * Delete the indirect records associated with this contribution first.
1310 * @return mixed|null
1311 * $results no of deleted Contribution on success, false otherwise
1313 public static function deleteContribution($id) {
1314 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1316 $transaction = new CRM_Core_Transaction();
1319 //delete activity record
1321 'source_record_id' => $id,
1322 // activity type id for contribution
1323 'activity_type_id' => 6,
1326 CRM_Activity_BAO_Activity
::deleteActivity($params);
1328 //delete billing address if exists for this contribution.
1329 self
::deleteAddress($id);
1331 //update pledge and pledge payment, CRM-3961
1332 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1334 // remove entry from civicrm_price_set_entity, CRM-5095
1335 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1336 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1338 // cleanup line items.
1339 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1341 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1342 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1344 if ($participantId) {
1345 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1348 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1352 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1353 $noteId = key($note);
1355 CRM_Core_BAO_Note
::del($noteId, FALSE);
1358 $dao = new CRM_Contribute_DAO_Contribution();
1361 $results = $dao->delete();
1363 $transaction->commit();
1365 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1367 // delete the recently created Contribution
1368 $contributionRecent = [
1370 'type' => 'Contribution',
1372 CRM_Utils_Recent
::del($contributionRecent);
1378 * React to a financial transaction (payment) failure.
1380 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1381 * payments is important for forensic and outreach reasons.
1383 * @param int $contributionID
1384 * @param int $contactID
1385 * @param string $message
1387 * @throws \CiviCRM_API3_Exception
1389 public static function failPayment($contributionID, $contactID, $message) {
1390 civicrm_api3('activity', 'create', [
1391 'activity_type_id' => 'Failed Payment',
1392 'details' => $message,
1393 'subject' => ts('Payment failed at payment processor'),
1394 'source_record_id' => $contributionID,
1395 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1398 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1399 civicrm_api3('contribution', 'create', [
1400 'id' => $contributionID,
1401 'contribution_status_id' => 'Failed',
1406 * Check if there is a contribution with the same trxn_id or invoice_id.
1408 * @param array $input
1409 * An assoc array of name/value pairs.
1410 * @param array $duplicates
1411 * (reference) store ids of duplicate contribs.
1415 * true if duplicate, false otherwise
1417 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1419 $id = CRM_Utils_Array
::value('id', $input);
1421 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1422 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1428 $clause[] = "trxn_id = %1";
1429 $input[1] = [$trxn_id, 'String'];
1433 $clause[] = "invoice_id = %2";
1434 $input[2] = [$invoice_id, 'String'];
1437 if (empty($clause)) {
1441 $clause = implode(' OR ', $clause);
1443 $clause = "( $clause ) AND id != %3";
1444 $input[3] = [$id, 'Integer'];
1447 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1448 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1450 while ($dao->fetch()) {
1451 $duplicates[] = $dao->id
;
1458 * Takes an associative array and creates a contribution_product object.
1460 * the function extract all the params it needs to initialize the create a
1461 * contribution_product object. the params array could contain additional unused name/value
1464 * @param array $params
1465 * (reference) an assoc array of name/value pairs.
1467 * @return CRM_Contribute_DAO_ContributionProduct
1469 public static function addPremium(&$params) {
1470 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1471 $contributionProduct->copyValues($params);
1472 return $contributionProduct->save();
1476 * Get list of contribution fields for profile.
1477 * For now we only allow custom contribution fields to be in
1480 * @param bool $addExtraFields
1481 * True if special fields needs to be added.
1484 * the list of contribution fields
1486 public static function getContributionFields($addExtraFields = TRUE) {
1487 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1488 // @todo remove this - this line was added because payment_instrument_id was not
1489 // set to exportable - but now it is.
1490 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1492 if ($addExtraFields) {
1493 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1496 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1498 foreach ($contributionFields as $key => $var) {
1499 if ($key == 'contribution_contact_id') {
1502 elseif ($key == 'contribution_campaign_id') {
1503 $var['title'] = ts('Campaign');
1505 $fields[$key] = $var;
1508 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1513 * Add extra fields specific to contribution.
1515 public static function getSpecialContributionFields() {
1517 'contribution_soft_credit_name' => [
1518 'name' => 'contribution_soft_credit_name',
1519 'title' => ts('Soft Credit Name'),
1520 'headerPattern' => '/^soft_credit_name$/i',
1521 'where' => 'civicrm_contact_d.display_name',
1523 'contribution_soft_credit_email' => [
1524 'name' => 'contribution_soft_credit_email',
1525 'title' => ts('Soft Credit Email'),
1526 'headerPattern' => '/^soft_credit_email$/i',
1527 'where' => 'soft_email.email',
1529 'contribution_soft_credit_phone' => [
1530 'name' => 'contribution_soft_credit_phone',
1531 'title' => ts('Soft Credit Phone'),
1532 'headerPattern' => '/^soft_credit_phone$/i',
1533 'where' => 'soft_phone.phone',
1535 'contribution_soft_credit_contact_id' => [
1536 'name' => 'contribution_soft_credit_contact_id',
1537 'title' => ts('Soft Credit Contact ID'),
1538 'headerPattern' => '/^soft_credit_contact_id$/i',
1539 'where' => 'civicrm_contribution_soft.contact_id',
1541 'contribution_pcp_title' => [
1542 'name' => 'contribution_pcp_title',
1543 'title' => ts('Personal Campaign Page Title'),
1544 'headerPattern' => '/^contribution_pcp_title$/i',
1545 'where' => 'contribution_pcp.title',
1549 return $extraFields;
1553 * @param int $pageID
1557 public static function getCurrentandGoalAmount($pageID) {
1559 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1560 FROM civicrm_contribution_page p,
1561 civicrm_contribution c
1562 WHERE p.id = c.contribution_page_id
1564 AND c.cancel_date is null
1568 $config = CRM_Core_Config
::singleton();
1569 $params = [1 => [$pageID, 'Integer']];
1570 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1572 if ($dao->fetch()) {
1573 return [$dao->goal
, $dao->total
];
1576 return [NULL, NULL];
1581 * Get list of contributions which credit the passed in contact ID.
1583 * The returned array provides details about the original contribution & donor.
1585 * @param int $honorId
1586 * In Honor of Contact ID.
1589 * list of contribution fields
1590 * @todo - this is a confusing function called from one place. It has a test. It would be
1591 * nice to deprecate it.
1594 public static function getHonorContacts($honorId) {
1596 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1597 $honorDAO->contact_id
= $honorId;
1600 $type = CRM_Contribute_PseudoConstant
::financialType();
1602 while ($honorDAO->fetch()) {
1603 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1604 $contributionDAO->id
= $honorDAO->contribution_id
;
1606 if ($contributionDAO->find(TRUE)) {
1607 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1608 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1609 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1610 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1611 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1612 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1613 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1614 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1615 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1623 * Get the sort name of a contact for a particular contribution.
1626 * Id of the contribution.
1628 * @return null|string
1629 * sort name of the contact if found
1631 public static function sortName($id) {
1632 $id = CRM_Utils_Type
::escape($id, 'Integer');
1635 SELECT civicrm_contact.sort_name
1636 FROM civicrm_contribution, civicrm_contact
1637 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1638 AND civicrm_contribution.id = {$id}
1640 return CRM_Core_DAO
::singleValueQuery($query);
1644 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1646 * @param int|array $contactIDs
1650 public static function annual($contactIDs) {
1651 if (!is_array($contactIDs)) {
1652 // In practice I can't fine any evidence that this function is ever called with
1653 // anything other than a single contact id, but left like this due to .... fear.
1654 $contactIDs = explode(',', $contactIDs);
1657 $query = self
::getAnnualQuery($contactIDs);
1658 $dao = CRM_Core_DAO
::executeQuery($query);
1660 $amount = $average = [];
1661 while ($dao->fetch()) {
1662 if ($dao->count
> 0 && $dao->amount
> 0) {
1663 $count +
= $dao->count
;
1664 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1665 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1671 implode(', ', $amount),
1672 implode(', ', $average),
1679 * Check if there is a contribution with the params passed in.
1681 * Used for trxn_id,invoice_id and contribution_id
1683 * @param array $params
1684 * An assoc array of name/value pairs.
1687 * contribution id if success else NULL
1689 public static function checkDuplicateIds($params) {
1690 $dao = new CRM_Contribute_DAO_Contribution();
1694 foreach ($params as $k => $v) {
1696 $clause[] = "$k = '$v'";
1699 $clause = implode(' AND ', $clause);
1700 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1701 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1703 while ($dao->fetch()) {
1711 * Get the contribution details for component export.
1713 * @param int $exportMode
1715 * @param array $componentIds
1721 public static function getContributionDetails($exportMode, $componentIds) {
1722 $paymentDetails = [];
1723 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1725 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1726 $componentSelect = " civicrm_participant_payment.participant_id id";
1727 $additionalClause = "
1728 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1729 AND civicrm_participant_payment.participant_id {$componentClause} )
1732 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1733 $componentSelect = " civicrm_membership_payment.membership_id id";
1734 $additionalClause = "
1735 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1736 AND civicrm_membership_payment.membership_id {$componentClause} )
1739 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1740 $componentSelect = " civicrm_pledge_payment.id id";
1741 $additionalClause = "
1742 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1743 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1747 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1748 trxn_id, {$componentSelect}
1749 FROM civicrm_contribution
1750 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1751 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1752 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1753 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1754 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1755 AND option_group_contribution_status.id = contribution_status.option_group_id )
1759 $dao = CRM_Core_DAO
::executeQuery($query);
1761 while ($dao->fetch()) {
1762 $paymentDetails[$dao->id
] = [
1763 'total_amount' => $dao->total_amount
,
1764 'contribution_status' => $dao->status
,
1765 'receive_date' => $dao->receive_date
,
1766 'pay_instru' => $dao->payment_instrument
,
1767 'trxn_id' => $dao->trxn_id
,
1771 return $paymentDetails;
1775 * Create address associated with contribution record.
1777 * As long as there is one or more billing field in the parameters we will create the address.
1779 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1782 * @param array $params
1783 * @param int $billingLocationTypeID
1788 public static function createAddress($params, $billingLocationTypeID) {
1789 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1790 if ($hasBillingField) {
1791 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1792 return $address->id
;
1799 * Delete billing address record related contribution.
1801 * @param int $contributionId
1802 * @param int $contactId
1804 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1806 $contactJoin = NULL;
1808 if ($contributionId) {
1809 $clauses[] = "cc.id = {$contributionId}";
1813 $clauses[] = "cco.id = {$contactId}";
1814 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1817 if (empty($clauses)) {
1818 CRM_Core_Error
::fatal();
1821 $condition = implode(' OR ', $clauses);
1825 FROM civicrm_address ca
1826 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1830 $dao = CRM_Core_DAO
::executeQuery($query);
1832 while ($dao->fetch()) {
1833 $params = ['id' => $dao->id
];
1834 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1839 * This function check online pending contribution associated w/
1840 * Online Event Registration or Online Membership signup.
1842 * @param int $componentId
1843 * Participant/membership id.
1844 * @param string $componentName
1848 * pending contribution id.
1850 public static function checkOnlinePendingContribution($componentId, $componentName) {
1851 $contributionId = NULL;
1852 if (!$componentId ||
1853 !in_array($componentName, ['Event', 'Membership'])
1855 return $contributionId;
1858 if ($componentName == 'Event') {
1859 $idName = 'participant_id';
1860 $componentTable = 'civicrm_participant';
1861 $paymentTable = 'civicrm_participant_payment';
1862 $source = ts('Online Event Registration');
1865 if ($componentName == 'Membership') {
1866 $idName = 'membership_id';
1867 $componentTable = 'civicrm_membership';
1868 $paymentTable = 'civicrm_membership_payment';
1869 $source = ts('Online Contribution');
1872 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1875 SELECT component.id as {$idName},
1876 componentPayment.contribution_id as contribution_id,
1877 contribution.source source,
1878 contribution.contribution_status_id as contribution_status_id,
1879 contribution.is_pay_later as is_pay_later
1880 FROM $componentTable component
1881 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1882 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1883 WHERE component.id = {$componentId}";
1885 $dao = CRM_Core_DAO
::executeQuery($query);
1887 while ($dao->fetch()) {
1888 if ($dao->contribution_id
&&
1889 $dao->is_pay_later
&&
1890 $dao->contribution_status_id
== $pendingStatusId &&
1891 strpos($dao->source
, $source) !== FALSE
1893 $contributionId = $dao->contribution_id
;
1897 return $contributionId;
1901 * Update contribution as well as related objects.
1903 * This function by-passes hooks - to address this - don't use this function.
1905 * @param array $params
1906 * @param bool $processContributionObject
1909 * @throws \Exception
1912 * Use api contribute.completetransaction
1913 * For failures use failPayment (preferably exposing by api in the process).
1916 public static function transitionComponents($params, $processContributionObject = FALSE) {
1917 // get minimum required values.
1918 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1919 $componentId = CRM_Utils_Array
::value('component_id', $params);
1920 $componentName = CRM_Utils_Array
::value('componentName', $params);
1921 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1922 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1924 // if we already processed contribution object pass previous status id.
1925 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1929 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1931 // we process only ( Completed, Cancelled, or Failed ) contributions.
1932 if (!$contributionId ||
1933 !in_array($contributionStatusId, [
1934 array_search('Completed', $contributionStatuses),
1935 array_search('Cancelled', $contributionStatuses),
1936 array_search('Failed', $contributionStatuses),
1939 return $updateResult;
1942 if (!$componentName ||
!$componentId) {
1943 // get the related component details.
1944 $componentDetails = self
::getComponentDetails($contributionId);
1947 $componentDetails['contact_id'] = $contactId;
1948 $componentDetails['component'] = $componentName;
1950 if ($componentName == 'event') {
1951 $componentDetails['participant'] = $componentId;
1954 $componentDetails['membership'] = $componentId;
1958 if (!empty($componentDetails['contact_id'])) {
1959 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1965 // do check for required ids.
1966 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1967 return $updateResult;
1970 //now we are ready w/ required ids, start processing.
1972 $baseIPN = new CRM_Core_Payment_BaseIPN();
1974 $input = $ids = $objects = [];
1976 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1977 $ids['contribution'] = $contributionId;
1978 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1979 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1980 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1981 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1982 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1983 $ids['contributionRecur'] = NULL;
1984 $ids['contributionPage'] = NULL;
1986 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1987 CRM_Core_Error
::fatal();
1990 $memberships = &$objects['membership'];
1991 $participant = &$objects['participant'];
1992 $pledgePayment = &$objects['pledge_payment'];
1993 $contribution = &$objects['contribution'];
1994 $pledgeID = $oldStatus = NULL;
1995 $pledgePaymentIDs = [];
1996 if ($pledgePayment) {
1997 foreach ($pledgePayment as $key => $object) {
1998 $pledgePaymentIDs[] = $object->id
;
2000 $pledgeID = $pledgePayment[0]->pledge_id
;
2003 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2006 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2007 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2012 // we might want to process contribution object.
2013 $processContribution = FALSE;
2014 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2015 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2016 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2018 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2019 if (is_array($memberships)) {
2020 foreach ($memberships as $membership) {
2022 //Update Membership status if there is no other completed contribution associated with the membership.
2023 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2024 foreach ($relatedContributions as $contriId) {
2025 if ($contriId == $contributionId) {
2028 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2029 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2033 if ($membership && $update) {
2034 $membership->status_id
= array_search('Expired', $membershipStatuses);
2035 $membership->is_override
= TRUE;
2036 $membership->status_override_end_date
= 'null';
2037 $membership->save();
2039 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2040 if ($processContributionObject) {
2041 $processContribution = TRUE;
2047 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2048 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2050 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2051 if ($processContributionObject) {
2052 $processContribution = TRUE;
2056 if ($pledgePayment) {
2057 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2059 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2060 if ($processContributionObject) {
2061 $processContribution = TRUE;
2065 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2067 // only pending contribution related object processed.
2068 if ($previousContriStatusId &&
2069 !in_array($contributionStatuses[$previousContriStatusId], [
2074 // this is case when we already processed contribution object.
2075 return $updateResult;
2077 elseif (!$previousContriStatusId &&
2078 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2083 // this is case when we are going to process contribution object later.
2084 return $updateResult;
2087 if (is_array($memberships)) {
2088 foreach ($memberships as $membership) {
2093 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2094 $membership->membership_type_id
,
2095 $membership->is_test
, $membership->id
2098 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2099 // this picks up membership type changes during renewals
2101 SELECT membership_type_id
2102 FROM civicrm_membership_log
2103 WHERE membership_id=$membership->id
2106 $dao = new CRM_Core_DAO();
2108 if ($dao->fetch()) {
2109 if (!empty($dao->membership_type_id
)) {
2110 $membership->membership_type_id
= $dao->membership_type_id
;
2111 $membership->save();
2114 // else fall back to using current membership type
2115 // Figure out number of terms
2117 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2118 foreach ($lineitems as $lineitem) {
2119 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2120 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2122 // in case membership_num_terms comes through as null or zero
2123 $numterms = $numterms >= 1 ?
$numterms : 1;
2128 // CRM-15735-to update the membership status as per the contribution receive date
2130 $oldStatus = $membership->status_id
;
2131 if (!empty($params['receive_date'])) {
2132 $joinDate = $params['receive_date'];
2133 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2134 $membership->end_date
,
2135 $membership->join_date
,
2136 $params['receive_date'],
2138 $membership->membership_type_id
,
2141 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2142 $membership->save();
2145 if ($currentMembership) {
2146 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2147 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2148 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2151 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2154 //get the status for membership.
2155 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2157 $dates['join_date'],
2160 $membership->membership_type_id
,
2164 $formattedParams = [
2165 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2166 array_search('Current', $membershipStatuses)
2168 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2169 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2170 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2173 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2175 $membership->copyValues($formattedParams);
2176 $membership->save();
2178 //updating the membership log
2179 $membershipLog = [];
2180 $membershipLog = $formattedParams;
2181 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2182 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2184 $membershipLog['start_date'] = $logStartDate;
2185 $membershipLog['membership_id'] = $membership->id
;
2186 $membershipLog['modified_id'] = $membership->contact_id
;
2187 $membershipLog['modified_date'] = date('Ymd');
2188 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2190 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2192 //update related Memberships.
2193 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2195 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2196 $scheduledActivityID = CRM_Utils_Array
::value('id',
2197 civicrm_api3('Activity', 'Get',
2199 'source_record_id' => $membership->id
,
2200 'activity_type_id' => $activityType,
2201 'status_id' => 'Scheduled',
2204 'sort' => 'id DESC',
2209 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2210 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2211 if ($scheduledActivityID) {
2212 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2217 // track membership status change if any
2218 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2219 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2220 CRM_Activity_BAO_Activity
::addActivity($membership,
2221 'Change Membership Status',
2224 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2225 'source_contact_id' => $membershipLog['modified_id'],
2226 'priority_id' => 'Normal',
2231 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2232 if ($processContributionObject) {
2233 $processContribution = TRUE;
2236 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2242 $updatedStatusId = array_search('Registered', $participantStatuses);
2243 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2245 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2246 if ($processContributionObject) {
2247 $processContribution = TRUE;
2251 if ($pledgePayment) {
2252 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2254 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2255 if ($processContributionObject) {
2256 $processContribution = TRUE;
2261 // process contribution object.
2262 if ($processContribution) {
2263 $contributionParams = [];
2270 'payment_instrument_id',
2273 'financial_type_id',
2274 'contribution_status_id',
2275 'non_deductible_amount',
2279 foreach ($fields as $field) {
2280 if (empty($params[$field])) {
2283 $contributionParams[$field] = $params[$field];
2286 $ids = ['contribution' => $contributionId];
2287 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2290 return $updateResult;
2294 * Returns all contribution related object ids.
2296 * @param $contributionId
2300 public static function getComponentDetails($contributionId) {
2301 $componentDetails = $pledgePayment = [];
2302 if (!$contributionId) {
2303 return $componentDetails;
2307 SELECT c.id as contribution_id,
2308 c.contact_id as contact_id,
2309 c.contribution_recur_id,
2310 mp.membership_id as membership_id,
2311 m.membership_type_id as membership_type_id,
2312 pp.participant_id as participant_id,
2313 p.event_id as event_id,
2314 pgp.id as pledge_payment_id
2315 FROM civicrm_contribution c
2316 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2317 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2318 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2319 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2320 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2321 WHERE c.id = $contributionId";
2323 $dao = CRM_Core_DAO
::executeQuery($query);
2324 $componentDetails = [];
2326 while ($dao->fetch()) {
2327 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2328 $componentDetails['contact_id'] = $dao->contact_id
;
2329 if ($dao->event_id
) {
2330 $componentDetails['event'] = $dao->event_id
;
2332 if ($dao->participant_id
) {
2333 $componentDetails['participant'] = $dao->participant_id
;
2335 if ($dao->membership_id
) {
2336 if (!isset($componentDetails['membership'])) {
2337 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2339 $componentDetails['membership'][] = $dao->membership_id
;
2340 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2342 if ($dao->pledge_payment_id
) {
2343 $pledgePayment[] = $dao->pledge_payment_id
;
2345 if ($dao->contribution_recur_id
) {
2346 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2350 if ($pledgePayment) {
2351 $componentDetails['pledge_payment'] = $pledgePayment;
2354 return $componentDetails;
2358 * @param int $contactId
2359 * @param bool $includeSoftCredit
2361 * @return null|string
2363 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2367 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2368 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2369 $liWhere = " AND i.financial_type_id IN (0)";
2370 if (!empty($financialTypes)) {
2371 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2372 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2374 $contactContributionsSQL = "
2375 SELECT contribution.id AS id
2376 FROM civicrm_contribution contribution
2377 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2378 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2382 $contactSoftCreditContributionsSQL = "
2383 SELECT contribution.id
2384 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2385 ON ( contribution.id = softContribution.contribution_id )
2386 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2387 $query = "SELECT count( x.id ) count FROM ( ";
2388 $query .= $contactContributionsSQL;
2390 if ($includeSoftCredit) {
2391 $query .= " UNION ";
2392 $query .= $contactSoftCreditContributionsSQL;
2397 return CRM_Core_DAO
::singleValueQuery($query);
2401 * Repeat a transaction as part of a recurring series.
2403 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2404 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2405 * subsequent call to the contribution.completetransaction api.
2407 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2409 * @param CRM_Contribute_BAO_Contribution $contribution
2410 * @param array $input
2411 * @param array $contributionParams
2412 * @param int $paymentProcessorID
2415 * @throws CiviCRM_API3_Exception
2417 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2418 if (!empty($contribution->id
)) {
2421 if (empty($contribution->id
)) {
2422 // Unclear why this would only be set for repeats.
2423 if (!empty($input['amount'])) {
2424 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2427 if (!empty($contributionParams['contribution_recur_id'])) {
2428 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2429 'id' => $contributionParams['contribution_recur_id'],
2431 if (!empty($recurringContribution['campaign_id'])) {
2432 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2433 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2435 if (!empty($recurringContribution['financial_type_id'])) {
2436 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2437 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2440 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2441 $contributionParams['contribution_recur_id'],
2442 array_intersect_key($contributionParams, [
2443 'total_amount' => TRUE,
2444 'financial_type_id' => TRUE,
2447 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2449 $contributionParams['status_id'] = 'Pending';
2450 if (isset($contributionParams['financial_type_id'])) {
2451 // Give precedence to passed in type.
2452 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2455 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2457 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2458 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2460 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2461 //do not create CC or BCC emails or profile notifications.
2462 //The if is just to be safe. Not sure if we can ever arrive with this unset
2463 // but per CRM-19478 it seems it can be 'null'
2464 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2465 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2468 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2469 $contribution->id
= $createContribution['id'];
2470 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2476 * Get individual id for onbehalf contribution.
2478 * @param int $contributionId
2480 * @param int $contributorId
2484 * containing organization id and individual id
2486 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2490 if (!$contributionId) {
2494 // fetch contributor id if null
2495 if (!$contributorId) {
2496 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2497 $contributionId, 'contact_id'
2501 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2502 $activityTypeId = array_search('Contribution', $activityTypeIds);
2504 if ($activityTypeId && $contributorId) {
2506 SELECT civicrm_activity_contact.contact_id
2507 FROM civicrm_activity_contact
2508 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2509 WHERE civicrm_activity.activity_type_id = %1
2510 AND civicrm_activity.source_record_id = %2
2511 AND civicrm_activity_contact.record_type_id = %3
2514 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2515 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2518 1 => [$activityTypeId, 'Integer'],
2519 2 => [$contributionId, 'Integer'],
2520 3 => [$sourceID, 'Integer'],
2523 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2525 // for on behalf contribution source is individual and contributor is organization
2526 if ($sourceContactId && $sourceContactId != $contributorId) {
2527 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2528 // get rel type id for employee of relation
2529 foreach ($relationshipTypeIds as $id => $typeVals) {
2530 if ($typeVals['name_a_b'] == 'Employee of') {
2531 $relationshipTypeId = $id;
2536 $rel = new CRM_Contact_DAO_Relationship();
2537 $rel->relationship_type_id
= $relationshipTypeId;
2538 $rel->contact_id_a
= $sourceContactId;
2539 $rel->contact_id_b
= $contributorId;
2540 if ($rel->find(TRUE)) {
2541 $ids['individual_id'] = $rel->contact_id_a
;
2542 $ids['organization_id'] = $rel->contact_id_b
;
2553 public static function getContributionDates() {
2554 $config = CRM_Core_Config
::singleton();
2555 $currentMonth = date('m');
2556 $currentDay = date('d');
2557 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2558 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2559 (int ) $config->fiscalYearStart
['d'] > $currentDay
2562 $year = date('Y') - 1;
2567 $year = ['Y' => $year];
2568 $yearDate = $config->fiscalYearStart
;
2569 $yearDate = array_merge($year, $yearDate);
2570 $yearDate = CRM_Utils_Date
::format($yearDate);
2572 $monthDate = date('Ym') . '01';
2578 'yearDate' => $yearDate,
2579 'monthDate' => $monthDate,
2584 * Load objects relations to contribution object.
2585 * Objects are stored in the $_relatedObjects property
2586 * In the first instance we are just moving functionality from BASEIpn -
2588 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2590 * Note that the unit test for the BaseIPN class tests this function
2592 * @param array $input
2593 * Input as delivered from Payment Processor.
2595 * Ids as Loaded by Payment Processor.
2596 * @param bool $loadAll
2597 * Load all related objects - even where id not passed in? (allows API to call this).
2602 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2603 // @todo deprecate this function - the steps should be
2604 // 1) add additional functions like 'getRelatedMemberships'
2605 // 2) switch all calls that refer to ->_relatedObjects to
2606 // using the helper functions
2607 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2608 // 4) make ->_relatedObjects protected
2609 // 5) hone up the individual functions to not use rely on this having been called
2610 // 6) deprecate like mad
2612 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2613 if (empty($ids['contact']) && isset($this->contact_id
)) {
2614 $ids['contact'] = $this->contact_id
;
2617 if (empty($this->_component
)) {
2618 if (!empty($ids['event'])) {
2619 $this->_component
= 'event';
2622 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2626 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2627 // refactoring than anything else, and has unit test coverage.
2628 if (empty($this->financial_type_id
)) {
2632 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2637 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2638 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2639 $this->contribution_page_id
,
2642 if ($paymentProcessorID) {
2643 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2647 $ids['contributionType'] = $this->financial_type_id
;
2648 $ids['financialType'] = $this->financial_type_id
;
2649 if ($this->contribution_page_id
) {
2650 $ids['contributionPage'] = $this->contribution_page_id
;
2653 $this->loadRelatedEntitiesByID($ids);
2655 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2656 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2659 if (!empty($ids['pledge_payment'])) {
2660 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2661 if (empty($paymentID)) {
2664 $payment = new CRM_Pledge_BAO_PledgePayment();
2665 $payment->id
= $paymentID;
2666 if (!$payment->find(TRUE)) {
2667 throw new Exception("Could not find pledge payment record: " . $paymentID);
2669 $this->_relatedObjects
['pledge_payment'][] = $payment;
2673 // These are probably no longer accessed from anywhere
2674 // @todo remove this line, after ensuring not used.
2675 $ids = $this->loadRelatedMembershipObjects($ids);
2677 if ($this->_component
!= 'contribute') {
2678 // we are in event mode
2679 // make sure event exists and is valid
2680 $event = new CRM_Event_BAO_Event();
2681 $event->id
= $ids['event'];
2682 if ($ids['event'] &&
2685 throw new Exception("Could not find event: " . $ids['event']);
2688 $this->_relatedObjects
['event'] = &$event;
2690 $participant = new CRM_Event_BAO_Participant();
2691 $participant->id
= $ids['participant'];
2692 if ($ids['participant'] &&
2693 !$participant->find(TRUE)
2695 throw new Exception("Could not find participant: " . $ids['participant']);
2697 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2699 $this->_relatedObjects
['participant'] = &$participant;
2701 // get the payment processor id from event - this is inaccurate see CRM-16923
2702 // in future we should look at throwing an exception here rather than an dubious guess.
2703 if (!$paymentProcessorID) {
2704 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2705 if ($paymentProcessorID) {
2706 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2711 if ($paymentProcessorID) {
2712 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2713 $this->is_test ?
'test' : 'live'
2715 $ids['paymentProcessor'] = $paymentProcessorID;
2716 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2719 // Add contribution id to $ids. CRM-20401
2720 $ids['contribution'] = $this->id
;
2725 * Create array of message information - ie. return html version, txt version, to field
2727 * @param array $input
2728 * Incoming information.
2729 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2730 * just check presence of recur object but maintaining legacy approach
2733 * IDs of related objects.
2734 * @param array $values
2735 * Any values that may have already been compiled by calling process.
2736 * This is augmented by values 'gathered' by gatherMessageValues
2737 * @param bool $returnMessageText
2738 * Distinguishes between whether to send message or return.
2739 * message text. We are working towards this function ALWAYS returning message text & calling
2740 * function doing emails / pdfs with it
2746 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2747 $this->loadRelatedObjects($input, $ids);
2749 if (empty($this->_component
)) {
2750 $this->_component
= CRM_Utils_Array
::value('component', $input);
2753 //not really sure what params might be passed in but lets merge em into values
2754 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2755 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2756 if (!empty($input['receipt_date'])) {
2757 $values['receipt_date'] = $input['receipt_date'];
2760 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2761 //what does recur 'mean here - to do with payment processor return functionality but
2762 // what is the importance
2763 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2764 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2766 $entityID = $entity = NULL;
2767 if (isset($ids['contribution'])) {
2768 $entity = 'contribution';
2769 $entityID = $ids['contribution'];
2771 if (!empty($ids['membership'])) {
2772 //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
2773 // 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
2774 // line having loaded an array
2775 $ids['membership'] = (array) $ids['membership'];
2776 $entity = 'membership';
2777 $entityID = $ids['membership'][0];
2780 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2781 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2782 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2784 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2785 //direct mode showing billing block, so use directIPN for temporary
2786 $template->assign('contributeMode', 'directIPN');
2789 // todo remove strtolower - check consistency
2790 if (strtolower($this->_component
) == 'event') {
2791 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2792 $values['event'] = [];
2794 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2796 //get location details
2798 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2799 'entity_table' => 'civicrm_event',
2801 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2804 'entity_table' => 'civicrm_event',
2805 'entity_id' => $ids['event'],
2806 'module' => 'CiviEvent',
2809 list($custom_pre_id,
2811 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2813 $values['custom_pre_id'] = $custom_pre_id;
2814 $values['custom_post_id'] = $custom_post_ids;
2815 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2816 //and cases involving status updation through ipn
2817 // whatever that means!
2818 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2819 // perhaps we should throw an e-notice if amount is set & force total_amount?
2820 if (!empty($input['amount'])) {
2821 $values['totalAmount'] = $input['amount'];
2823 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2824 if ($values['event']['is_email_confirm']) {
2825 $values['is_email_receipt'] = 1;
2828 if (!empty($ids['contribution'])) {
2829 $values['contributionId'] = $ids['contribution'];
2832 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2833 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2837 $values['contribution_id'] = $this->id
;
2838 if (!empty($ids['related_contact'])) {
2839 $values['related_contact'] = $ids['related_contact'];
2840 if (isset($ids['onbehalf_dupe_alert'])) {
2841 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2844 'contact_id' => $ids['contact'],
2845 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2846 'Home', 'id', 'name'
2849 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2850 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2853 if ($this->is_test
) {
2856 if (!empty($this->_relatedObjects
['membership'])) {
2857 foreach ($this->_relatedObjects
['membership'] as $membership) {
2858 if ($membership->id
) {
2859 $values['membership_id'] = $membership->id
;
2860 $values['isMembership'] = TRUE;
2861 $values['membership_assign'] = TRUE;
2863 // need to set the membership values here
2864 $template->assign('membership_name',
2865 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2867 $template->assign('mem_start_date', $membership->start_date
);
2868 $template->assign('mem_join_date', $membership->join_date
);
2869 $template->assign('mem_end_date', $membership->end_date
);
2870 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2871 $template->assign('mem_status', $membership_status);
2872 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2873 $values['is_pay_later'] = 1;
2875 // Pass amount to floatval as string '0.00' is considered a
2876 // valid amount and includes Fee section in the mail.
2877 if (isset($values['amount'])) {
2878 $values['amount'] = floatval($values['amount']);
2881 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2882 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2883 $template->assign('cancelSubscriptionUrl', $url);
2884 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2885 $template->assign('updateSubscriptionBillingUrl', $url);
2886 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2887 $template->assign('updateSubscriptionUrl', $url);
2890 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2893 // otherwise if its about sending emails, continue sending without return, as we
2894 // don't want to exit the loop.
2899 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2905 * Gather values for contribution mail - this function has been created
2906 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2907 * Values related to the contribution in question are gathered
2909 * @param array $input
2910 * Input into function (probably from payment processor).
2911 * @param array $values
2913 * The set of ids related to the input.
2917 public function _gatherMessageValues($input, &$values, $ids = []) {
2918 // set display address of contributor
2919 if ($this->address_id
) {
2920 $addressParams = ['id' => $this->address_id
];
2921 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2922 $addressDetails = array_values($addressDetails);
2924 // Else we assign the billing address of the contribution contact.
2926 $addressParams = ['contact_id' => $this->contact_id
, 'is_billing' => 1];
2927 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2928 $addressDetails = array_values($addressDetails);
2931 if (!empty($addressDetails[0]['display'])) {
2932 $values['address'] = $addressDetails[0]['display'];
2935 if ($this->_component
== 'contribute') {
2936 //get soft contributions
2937 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2938 if (!empty($softContributions)) {
2939 $values['softContributions'] = $softContributions['soft_credit'];
2941 if (isset($this->contribution_page_id
)) {
2942 // This is a call we want to use less, in favour of loading related objects.
2943 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2944 if ($this->contribution_page_id
) {
2945 // This is precautionary as there are some legacy flows, but it should really be
2947 if (!isset($this->_relatedObjects
['contributionPage'])) {
2948 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2950 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
2953 // no contribution page -probably back office
2955 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2956 $values['title'] = 'Contribution';
2958 // set lineItem for contribution
2960 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2961 if (!empty($lineItems)) {
2962 $firstLineItem = reset($lineItems);
2964 if (CRM_Utils_Array
::value('price_set_id', $firstLineItem)) {
2965 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
2966 'id' => $firstLineItem['price_set_id'],
2967 'return' => 'is_quick_config, id',
2969 $values['priceSetID'] = $priceSet['id'];
2971 foreach ($lineItems as &$eachItem) {
2972 if (isset($this->_relatedObjects
['membership'])
2973 && is_array($this->_relatedObjects
['membership'])
2974 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2975 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2976 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2977 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2979 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2980 // However, that does create upgrade pain so would be better to be phased in.
2981 $values['useForMember'] = empty($priceSet['is_quick_config']);
2983 $values['lineItem'][0] = $lineItems;
2987 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2991 // if this is onbehalf of contribution then set related contact
2992 if (!empty($relatedContact['individual_id'])) {
2993 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2999 'id' => $this->_relatedObjects
['event']->id
,
3001 $values['event'] = [];
3003 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
3004 // add custom fields for event
3005 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $this->_relatedObjects
['event']->id
);
3007 $eventCustomGroup = [];
3008 foreach ($eventGroupTree as $key => $group) {
3009 if ($key === 'info') {
3013 foreach ($group['fields'] as $k => $customField) {
3014 $groupLabel = $group['title'];
3015 if (!empty($customField['customValue'])) {
3016 foreach ($customField['customValue'] as $customFieldValues) {
3017 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3022 $values['event']['customGroup'] = $eventCustomGroup;
3024 //get participant details
3025 $participantParams = [
3026 'id' => $this->_relatedObjects
['participant']->id
,
3029 $values['participant'] = [];
3031 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
3032 // add custom fields for event
3033 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $this->_relatedObjects
['participant']->id
);
3034 $participantCustomGroup = [];
3035 foreach ($participantGroupTree as $key => $group) {
3036 if ($key === 'info') {
3040 foreach ($group['fields'] as $k => $customField) {
3041 $groupLabel = $group['title'];
3042 if (!empty($customField['customValue'])) {
3043 foreach ($customField['customValue'] as $customFieldValues) {
3044 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3049 $values['participant']['customGroup'] = $participantCustomGroup;
3051 //get location details
3053 'entity_id' => $this->_relatedObjects
['event']->id
,
3054 'entity_table' => 'civicrm_event',
3056 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
3059 'entity_table' => 'civicrm_event',
3060 'entity_id' => $ids['event'],
3061 'module' => 'CiviEvent',
3064 list($custom_pre_id,
3066 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
3068 $values['custom_pre_id'] = $custom_pre_id;
3069 $values['custom_post_id'] = $custom_post_ids;
3071 // set lineItem for event contribution
3073 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
3074 if (!empty($participantIds)) {
3075 foreach ($participantIds as $pIDs) {
3076 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
3077 if (!CRM_Utils_System
::isNull($lineItem)) {
3078 $values['lineItem'][] = $lineItem;
3085 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3088 foreach ($groupTree as $key => $group) {
3089 if ($key === 'info') {
3093 foreach ($group['fields'] as $k => $customField) {
3094 $groupLabel = $group['title'];
3095 if (!empty($customField['customValue'])) {
3096 foreach ($customField['customValue'] as $customFieldValues) {
3097 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3102 $values['customGroup'] = $customGroup;
3104 $values['is_pay_later'] = $this->is_pay_later
;
3110 * Assign message variables to template but try to break the habit.
3112 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3113 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3114 * multiple recurring payments for processors like IATS that use tokens.
3116 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3117 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3118 * Note we send directly from this function in some cases because it is only partly refactored.
3120 * Don't call this function directly as the signature will change.
3124 * @param bool $returnMessageText
3128 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3129 // @todo - this should have a better separation of concerns - ie.
3130 // gatherMessageValues should build an array of values to be assigned to the template
3131 // and this function should assign them (assigning null if not set).
3132 // the way the pcpParams & honor Params section works is a baby-step towards this.
3133 $template = CRM_Core_Smarty
::singleton();
3134 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3135 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3136 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3138 // For some unit tests contribution cannot contain paymentProcessor information
3139 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3140 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3142 //assign honor information to receipt message
3143 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3146 'soft_credit_type' => NULL,
3147 'honor_block_is_active' => NULL,
3149 if (isset($softRecord['soft_credit'])) {
3150 //if id of contribution page is present
3151 if (!empty($values['id'])) {
3152 $values['honor'] = [
3153 'honor_profile_values' => [],
3154 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3155 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3158 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3159 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3162 //offline contribution
3163 $softCreditTypes = $softCredits = [];
3164 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3165 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3166 $softCredits[$key] = [
3167 'Name' => $softCredit['contact_name'],
3168 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3171 $template->assign('softCreditTypes', $softCreditTypes);
3172 $template->assign('softCredits', $softCredits);
3176 $dao = new CRM_Contribute_DAO_ContributionProduct();
3177 $dao->contribution_id
= $this->id
;
3178 if ($dao->find(TRUE)) {
3179 $premiumId = $dao->product_id
;
3180 $template->assign('option', $dao->product_option
);
3182 $productDAO = new CRM_Contribute_DAO_Product();
3183 $productDAO->id
= $premiumId;
3184 $productDAO->find(TRUE);
3185 $template->assign('selectPremium', TRUE);
3186 $template->assign('product_name', $productDAO->name
);
3187 $template->assign('price', $productDAO->price
);
3188 $template->assign('sku', $productDAO->sku
);
3190 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3191 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3192 if (!$values['amount'] && isset($this->total_amount
)) {
3193 $values['amount'] = $this->total_amount
;
3198 'pcp_display_in_roll' => NULL,
3199 'pcp_roll_nickname' => NULL,
3200 'pcp_personal_note' => NULL,
3204 if (strtolower($this->_component
) == 'contribute') {
3206 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3207 $softDAO->contribution_id
= $this->id
;
3208 if ($softDAO->find(TRUE)) {
3209 $pcpParams['pcpBlock'] = TRUE;
3210 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3211 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3212 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3214 //assign the pcp page title for email subject
3215 $pcpDAO = new CRM_PCP_DAO_PCP();
3216 $pcpDAO->id
= $softDAO->pcp_id
;
3217 if ($pcpDAO->find(TRUE)) {
3218 $pcpParams['title'] = $pcpDAO->title
;
3222 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3223 $template->assign($templateKey, $templateValue);
3226 if ($this->financial_type_id
) {
3227 $values['financial_type_id'] = $this->financial_type_id
;
3230 $template->assign('trxn_id', $this->trxn_id
);
3231 $template->assign('receive_date',
3232 CRM_Utils_Date
::processDate($this->receive_date
)
3234 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3235 $template->assign('action', $this->is_test ?
1024 : 1);
3236 $template->assign('receipt_text',
3237 CRM_Utils_Array
::value('receipt_text',
3241 $template->assign('is_monetary', 1);
3242 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3243 $template->assign('currency', $this->currency
);
3244 $template->assign('address', CRM_Utils_Address
::format($input));
3245 if (!empty($values['customGroup'])) {
3246 $template->assign('customGroup', $values['customGroup']);
3248 if (!empty($values['softContributions'])) {
3249 $template->assign('softContributions', $values['softContributions']);
3251 if ($this->_component
== 'event') {
3252 $template->assign('title', $values['event']['title']);
3253 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3255 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3256 $viewRoles[] = $participantRoles[$v];
3258 $values['event']['participant_role'] = implode(', ', $viewRoles);
3259 $template->assign('event', $values['event']);
3260 $template->assign('participant', $values['participant']);
3261 $template->assign('location', $values['location']);
3262 $template->assign('customPre', $values['custom_pre_id']);
3263 $template->assign('customPost', $values['custom_post_id']);
3266 if ($this->_relatedObjects
['participant']->is_test
) {
3270 $values['params'] = [];
3271 //to get email of primary participant.
3272 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3273 $primaryAmount[] = [
3274 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3275 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3277 //build an array of cId/pId of participants
3278 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3279 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3280 //send receipt to additional participant if exists
3281 if (count($additionalIDs)) {
3282 $template->assign('isPrimary', 0);
3283 $template->assign('customProfile', NULL);
3284 //set additionalParticipant true
3285 $values['params']['additionalParticipant'] = TRUE;
3286 foreach ($additionalIDs as $pId => $cId) {
3288 //to change the status pending to completed
3289 $additional = new CRM_Event_DAO_Participant();
3290 $additional->id
= $pId;
3291 $additional->contact_id
= $cId;
3292 $additional->find(TRUE);
3293 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3294 $additional->status_id
= 1;
3295 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3296 //if additional participant dont have email
3298 if (!$additionalParticipantInfo) {
3299 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3302 'label' => $additional->fee_level
,
3303 'amount' => $additional->fee_amount
,
3305 $primaryAmount[] = [
3306 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3307 'amount' => $additional->fee_amount
,
3309 $additional->save();
3310 $template->assign('amount', $amount);
3311 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3315 //build an array of custom profile and assigning it to template
3316 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3318 if (count($customProfile)) {
3319 $template->assign('customProfile', $customProfile);
3322 // for primary contact
3323 $values['params']['additionalParticipant'] = FALSE;
3324 $template->assign('isPrimary', 1);
3325 $template->assign('amount', $primaryAmount);
3326 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3327 if ($this->payment_instrument_id
) {
3328 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3329 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3331 // carry paylater, since we did not created billing,
3332 // so need to pull email from primary location, CRM-4395
3333 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3339 * Check whether payment processor supports
3340 * cancellation of contribution subscription
3342 * @param int $contributionId
3345 * @param bool $isNotCancelled
3349 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3350 $cacheKeyString = "$contributionId";
3351 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3353 static $supportsCancel = [];
3355 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3356 $supportsCancel[$cacheKeyString] = FALSE;
3357 $isCancelled = FALSE;
3359 if ($isNotCancelled) {
3360 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3363 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3364 if (!empty($paymentObject)) {
3365 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3368 return $supportsCancel[$cacheKeyString];
3372 * Check whether subscription is already cancelled.
3374 * @param int $contributionId
3378 * contribution status
3380 public static function isSubscriptionCancelled($contributionId) {
3382 SELECT cr.contribution_status_id
3383 FROM civicrm_contribution_recur cr
3384 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3385 WHERE con.id = %1 LIMIT 1";
3386 $params = [1 => [$contributionId, 'Integer']];
3387 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3388 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3389 if ($status == 'Cancelled') {
3396 * Create all financial accounts entry.
3398 * @param array $params
3399 * Contribution object, line item array and params for trxn.
3402 * @param array $financialTrxnValues
3404 * @return null|\CRM_Core_BAO_FinancialTrxn
3406 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3407 $skipRecords = $update = $return = $isRelatedId = FALSE;
3409 $additionalParticipantId = [];
3410 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3411 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3413 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3414 $entityId = $params['participant_id'];
3415 $entityTable = 'civicrm_participant';
3416 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3418 elseif (!empty($params['membership_id'])) {
3419 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3420 // are created off one contribution should be handled elsewhere
3421 $entityId = $params['membership_id'];
3422 $entityTable = 'civicrm_membership';
3425 $entityId = $params['contribution']->id
;
3426 $entityTable = 'civicrm_contribution';
3429 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3430 $isRelatedId = TRUE;
3433 $entityID[] = $entityId;
3434 if (!empty($additionalParticipantId)) {
3435 $entityID +
= $additionalParticipantId;
3437 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3438 if (empty($params['prevContribution'])) {
3445 $statusId = $params['contribution']->contribution_status_id
;
3446 // CRM-13964 partial payment
3447 if ($contributionStatus == 'Partially paid'
3448 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3450 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3451 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3453 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3454 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3455 $params['total_amount'] = $partialAmtPay;
3457 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3458 if (empty($balanceTrxnInfo['trxn_id'])) {
3459 // create new balance transaction record
3460 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3462 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3463 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3464 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3465 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3466 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3467 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3468 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3469 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3470 $balanceTrxnParams['status_id'] = $statusId;
3471 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3472 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3473 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3474 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3475 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3476 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3478 $balanceTrxnParams['is_payment'] = 1;
3480 if (!empty($params['payment_processor'])) {
3481 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3483 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3487 // build line item array if its not set in $params
3488 if (empty($params['line_item']) ||
$additionalParticipantId) {
3489 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3492 if ($contributionStatus != 'Failed' &&
3493 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3495 $skipRecords = TRUE;
3500 if (in_array($contributionStatus, $pendingStatus)) {
3501 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3502 $params['financial_type_id'],
3503 'Accounts Receivable Account is'
3506 elseif (!empty($params['payment_processor'])) {
3507 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3508 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3509 'id' => $params['payment_processor'],
3510 'return' => 'payment_instrument_id',
3513 elseif (!empty($params['payment_instrument_id'])) {
3514 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3517 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3518 $queryParams = [1 => [$relationTypeId, 'Integer']];
3519 $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);
3522 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3523 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3524 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3526 //build financial transaction params
3528 'contribution_id' => $params['contribution']->id
,
3529 'to_financial_account_id' => $params['to_financial_account_id'],
3530 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3531 'total_amount' => $totalAmount,
3532 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3533 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3534 'currency' => $params['contribution']->currency
,
3535 'trxn_id' => $params['contribution']->trxn_id
,
3536 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3537 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3538 // this should really default to completed (after discussion).
3539 'status_id' => $statusId,
3540 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3541 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3542 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3543 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3545 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3546 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3547 if (isset($params['refund_trxn_id'])) {
3548 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3549 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3552 //CRM-16259, set is_payment flag for non pending status
3553 if (!in_array($contributionStatus, $pendingStatus)) {
3554 $trxnParams['is_payment'] = 1;
3556 if (!empty($params['payment_processor'])) {
3557 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3560 if (isset($fromFinancialAccountId)) {
3561 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3564 // consider external values passed for recording transaction entry
3565 if (!empty($financialTrxnValues)) {
3566 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3568 if (empty($trxnParams['payment_processor_id'])) {
3569 unset($trxnParams['payment_processor_id']);
3572 $params['trxnParams'] = $trxnParams;
3574 if (!empty($params['prevContribution'])) {
3576 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3577 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3578 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3579 if (!isset($params['trxnParams']['trxn_id'])) {
3580 // Actually I have no idea why we are overwriting any values from the previous contribution.
3581 // (filling makes sense to me). However, only protecting this value as I really really know we
3582 // don't want this one overwritten.
3584 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3586 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3588 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3589 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3590 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3592 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3593 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3596 //if financial type is changed
3597 if (!empty($params['financial_type_id']) &&
3598 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3600 $accountRelationship = 'Income Account is';
3601 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3602 $accountRelationship = 'Deferred Revenue Account is';
3604 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3605 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3606 if ($oldFinancialAccount != $newFinancialAccount) {
3607 $params['total_amount'] = 0;
3608 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3609 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3610 $params['prevContribution']->financial_type_id
, $accountRelationship);
3613 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3614 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3615 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3618 self
::updateFinancialAccounts($params, 'changeFinancialType');
3619 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3620 $params['financial_account_id'] = $newFinancialAccount;
3621 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3622 self
::updateFinancialAccounts($params);
3623 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3625 $params['deferred_financial_account_id'] = $newFinancialAccount;
3629 //Update contribution status
3630 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3631 if (!isset($params['refund_trxn_id'])) {
3632 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3633 // gets preference over another so I am only 'protecting' a very specific tested flow
3634 // and letting natural justice take care of the rest.
3635 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3637 if (!empty($params['contribution_status_id']) &&
3638 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3640 //Update Financial Records
3641 self
::updateFinancialAccounts($params, 'changedStatus');
3645 // change Payment Instrument for a Completed contribution
3646 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3647 // instrument is null and now new payment instrument is added along with the payment
3648 if (!$params['contribution']->payment_instrument_id
) {
3649 $params['contribution']->find(TRUE);
3651 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3652 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3654 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3655 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3658 //if Change contribution amount
3659 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3660 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3661 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3662 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3663 if (isset($totalAmount) &&
3664 $totalAmount != $params['prevContribution']->total_amount
3666 //Update Financial Records
3667 $params['trxnParams']['from_financial_account_id'] = NULL;
3668 self
::updateFinancialAccounts($params, 'changedAmount');
3673 // Looks like we might have a data correction update.
3674 // This would be a case where a transaction id has been entered but it is incorrect &
3675 // the person goes back in & fixes it, as opposed to a new transaction.
3676 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3677 // the data fix scenario.
3679 if (isset($params['refund_trxn_id'])) {
3680 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3681 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3682 civicrm_api3('FinancialTrxn', 'create', [
3683 'id' => $refundIDs['financialTrxnId'],
3684 'trxn_id' => $params['refund_trxn_id'],
3688 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3689 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3690 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3695 // records finanical trxn and entity financial trxn
3696 // also make it available as return value
3697 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3698 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3699 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3700 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3701 $params['entity_id'] = $financialTxn->id
;
3702 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3703 self
::$_trxnIDs[] = $financialTxn->id
;
3707 // record line items and financial items
3708 if (empty($params['skipLineItem'])) {
3709 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3712 // create batch entry if batch_id is passed and
3713 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3714 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3716 'batch_id' => $params['batch_id'],
3717 'entity_table' => 'civicrm_financial_trxn',
3718 'entity_id' => $financialTxn->id
,
3720 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3723 // when a fee is charged
3724 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3725 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3728 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3729 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3731 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3732 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3733 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3735 unset($params['line_item']);
3736 self
::$_trxnIDs = NULL;
3741 * Update all financial accounts entry.
3743 * @param array $params
3744 * Contribution object, line item array and params for trxn.
3746 * @param string $context
3749 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3750 * adds unpredictability.
3753 public static function updateFinancialAccounts(&$params, $context = NULL) {
3755 $inputParams = $params;
3757 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
3758 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3760 if ($context == 'changedStatus') {
3761 list($continue, $isARefund) = self
::updateFinancialAccountsOnContributionStatusChange($params, $context, $previousContributionStatus, $currentContributionStatus);
3762 // @todo - it may be that this is always false & the parent function is just a confusing wrapper for the child fn.
3768 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3769 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3770 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3773 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3774 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3775 $params['entity_id'] = $trxn->id
;
3777 $itemParams['entity_table'] = 'civicrm_line_item';
3778 $trxnIds['id'] = $params['entity_id'];
3779 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3780 foreach ($params['line_item'] as $fieldId => $fields) {
3781 foreach ($fields as $fieldValueId => $lineItemDetails) {
3782 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
3783 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3784 if ($params['contribution']->receive_date
) {
3785 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3788 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
3790 $currency = $params['prevContribution']->currency
;
3791 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3792 if ($params['contribution']->currency
) {
3793 $currency = $params['contribution']->currency
;
3795 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3797 'transaction_date' => $receiveDate,
3798 'contact_id' => $params['prevContribution']->contact_id
,
3799 'currency' => $currency,
3800 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
3801 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
3802 'status_id' => $prevFinancialItem['status_id'],
3803 'financial_account_id' => $financialAccount,
3804 'entity_table' => 'civicrm_line_item',
3805 'entity_id' => $lineItemDetails['id'],
3807 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3808 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3809 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
3810 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3812 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
3813 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3814 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3815 $taxAmount = (float) $lineItemDetails['tax_amount'];
3816 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
3817 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
3818 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3820 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
3821 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
3823 if ($taxAmount != 0) {
3824 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
3825 $itemParams['description'] = $taxTerm;
3826 if ($lineItemDetails['financial_type_id']) {
3827 $itemParams['financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(
3828 $lineItemDetails['financial_type_id'],
3829 'Sales Tax Account is'
3832 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3838 if ($context == 'changeFinancialType') {
3839 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3840 $params['skipLineItem'] = FALSE;
3841 foreach ($params['line_item'] as &$lineItems) {
3842 foreach ($lineItems as &$line) {
3843 $line['financial_type_id'] = $params['financial_type_id'];
3848 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3852 * Is this contribution status a reversal.
3854 * If so we would expect to record a negative value in the financial_trxn table.
3856 * @param int $status_id
3860 public static function isContributionStatusNegative($status_id) {
3861 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3862 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3866 * Check status validation on update of a contribution.
3868 * @param array $values
3869 * Previous form values before submit.
3871 * @param array $fields
3872 * The input form values.
3874 * @param array $errors
3879 public static function checkStatusValidation($values, &$fields, &$errors) {
3880 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3881 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3882 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3886 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3888 'Cancelled' => ['Completed', 'Refunded'],
3889 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3890 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3891 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3892 'Refunded' => ['Cancelled', 'Completed'],
3893 'Partially paid' => ['Completed'],
3894 'Pending refund' => ['Completed', 'Refunded'],
3897 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3898 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3900 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3901 1 => $contributionStatuses[$values['contribution_status_id']],
3902 2 => $contributionStatuses[$fields['contribution_status_id']],
3908 * Delete contribution of contact.
3912 * @param int $contactId
3916 public static function deleteContactContribution($contactId) {
3917 $contribution = new CRM_Contribute_DAO_Contribution();
3918 $contribution->contact_id
= $contactId;
3919 $contribution->find();
3920 while ($contribution->fetch()) {
3921 self
::deleteContribution($contribution->id
);
3926 * Get options for a given contribution field.
3928 * @param string $fieldName
3929 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3930 * @param array $props whatever is known about this dao object.
3932 * @return array|bool
3933 * @see CRM_Core_DAO::buildOptions
3936 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3937 $className = __CLASS__
;
3939 if (isset($props['orderColumn'])) {
3940 $params['orderColumn'] = $props['orderColumn'];
3942 switch ($fieldName) {
3943 // This field is not part of this object but the api supports it
3944 case 'payment_processor':
3945 $className = 'CRM_Contribute_BAO_ContributionPage';
3946 // Filter results by contribution page
3947 if (!empty($props['contribution_page_id'])) {
3948 $page = civicrm_api('contribution_page', 'getsingle', [
3950 'id' => ($props['contribution_page_id']),
3952 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3953 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3957 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3958 case 'honor_type_id':
3959 $className = 'CRM_Contribute_BAO_ContributionSoft';
3960 $fieldName = 'soft_credit_type_id';
3961 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3964 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3968 * Validate financial type.
3972 * @param int $financialTypeId
3973 * Financial Type id.
3975 * @param string $relationName
3977 * @return array|bool
3979 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3980 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3982 if (!$financialAccount) {
3983 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3989 * Function to record additional payment for partial and refund contributions.
3991 * @param int $contributionId
3992 * is the invoice contribution id (got created after processing participant payment).
3993 * @param array $trxnsData
3994 * to take user provided input of transaction details.
3995 * @param string $paymentType
3996 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3997 * @param int $participantId
3998 * @param bool $updateStatus
4002 * @throws \CRM_Core_Exception
4003 * @throws \CiviCRM_API3_Exception
4005 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
4007 if ($paymentType == 'owed') {
4008 $financialTrxn = CRM_Financial_BAO_Payment
::recordPayment($contributionId, $trxnsData, $participantId);
4009 if (!empty($financialTrxn)) {
4010 self
::recordPaymentActivity($contributionId, $participantId, $financialTrxn->total_amount
, $financialTrxn->currency
, $financialTrxn->trxn_date
);
4011 return $financialTrxn->id
;
4014 elseif ($paymentType == 'refund') {
4015 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
4016 $trxnsData['participant_id'] = $participantId;
4017 $trxnsData['contribution_id'] = $contributionId;
4018 return civicrm_api3('Payment', 'create', $trxnsData)['id'];
4023 * @param int $targetCid
4024 * @param $activityType
4025 * @param string $title
4026 * @param int $contributionId
4027 * @param string $totalAmount
4028 * @param string $currency
4029 * @param string $trxn_date
4031 * @throws \CRM_Core_Exception
4032 * @throws \CiviCRM_API3_Exception
4034 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4035 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
4036 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4037 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
4038 // source record id would be the contribution id
4039 $srcRecId = $contributionId;
4043 'source_contact_id' => $targetCid,
4044 'source_record_id' => $srcRecId,
4045 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4046 'subject' => $subject,
4047 'activity_date_time' => $date,
4048 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4049 'skipRecentView' => TRUE,
4052 // create activity with target contacts
4053 $session = CRM_Core_Session
::singleton();
4054 $id = $session->get('userID');
4056 $activityParams['source_contact_id'] = $id;
4057 $activityParams['target_contact_id'][] = $targetCid;
4059 civicrm_api3('Activity', 'create', $activityParams);
4063 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4067 * @param bool $getTrxnInfo
4068 * @param bool $usingLineTotal
4072 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4073 // @todo deprecate passing in component - always call with contribution.
4074 if ($component == 'event') {
4075 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4077 if (!$contributionId) {
4078 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4079 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4080 $id = $primaryParticipantId;
4082 if (!$contributionId) {
4087 elseif ($component == 'membership') {
4088 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4091 $contributionId = $id;
4094 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4095 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4097 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4098 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4100 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4101 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4104 $baseTrxnId = $total['trxn_id'];
4105 $total = $total['total_amount'];
4108 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4110 $contribution = civicrm_api3('Contribution', 'getsingle', [
4111 'id' => $contributionId,
4115 'contribution_status_id',
4116 'financial_type_id',
4120 $info['payLater'] = $contribution['is_pay_later'];
4121 $info['contribution_status'] = $contribution['contribution_status'];
4122 $info['currency'] = $contribution['currency'];
4124 $financialTypeId = $contribution['financial_type_id'];
4125 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4127 if ($paymentBalance == 0 && $info['payLater']) {
4128 // @todo - review - this looks very unlikely to be correct.
4129 // the balance should be correct based on payment transactions not
4131 $paymentBalance = $total;
4134 $info['total'] = $total;
4135 $info['paid'] = $total - $paymentBalance;
4136 $info['balance'] = $paymentBalance;
4138 $info['component'] = $component;
4140 if ($getTrxnInfo && $baseTrxnId) {
4141 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4143 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4145 ft.payment_instrument_id,
4146 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4148 FROM civicrm_contribution con
4149 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4150 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4151 AND ft.to_financial_account_id != %2
4152 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4153 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4154 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4156 WHERE con.id = %1 AND ft.is_payment = 1
4159 1 => [$contributionId, 'Integer'],
4160 2 => [$feeFinancialAccount, 'Integer'],
4162 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4163 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4165 while ($resultDAO->fetch()) {
4166 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4167 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4168 if ($resultDAO->card_type_id
) {
4169 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4170 $pantruncation = '';
4171 if ($resultDAO->pan_truncation
) {
4172 $pantruncation = ": {$resultDAO->pan_truncation}";
4174 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4177 // show payment edit link only for payments done via backoffice form
4178 $paymentEditLink = '';
4179 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4181 CRM_Core_Action
::UPDATE
=> [
4182 'name' => "<i class='crm-i fa-pencil'></i>",
4183 'url' => 'civicrm/payment/edit',
4184 'class' => 'medium-popup',
4185 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4186 'title' => ts('Edit Payment'),
4189 $paymentEditLink = CRM_Core_Action
::formLink(
4191 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4193 'id' => $resultDAO->id
,
4194 'contribution_id' => $contributionId,
4200 'id' => $resultDAO->id
,
4201 'total_amount' => $resultDAO->total_amount
,
4202 'financial_type' => $resultDAO->financial_account
,
4203 'payment_instrument' => $paidByLabel,
4204 'receive_date' => $resultDAO->trxn_date
,
4205 'trxn_id' => $resultDAO->trxn_id
,
4206 'status' => $statuses[$resultDAO->status_id
],
4207 'currency' => $resultDAO->currency
,
4208 'action' => $paymentEditLink,
4210 if ($paidByName == 'Check') {
4211 $val['check_number'] = $resultDAO->check_number
;
4215 $info['transaction'] = $rows;
4218 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4223 * Get the outstanding balance on a contribution.
4225 * @param int $contributionId
4226 * @param float $contributionTotal
4227 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4231 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4232 if ($contributionTotal === NULL) {
4233 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4236 return CRM_Utils_Money
::subtractCurrencies(
4238 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE) ?
: 0,
4239 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4244 * Get the tax amount (misnamed function).
4246 * @param array $params
4247 * @param bool $isLineItem
4251 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4252 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4254 // This function should be only called after standardisation (removal of
4255 // thousand separator & using a decimal point for cents separator.
4256 // However, we don't know if that is always true :-(
4257 // There is a deprecation notice tho :-)
4258 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4259 // Update contribution.
4260 if (!empty($params['id'])) {
4261 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4262 // there are no tax implications - early return.
4263 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4266 if (empty($params['prevContribution'])) {
4267 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4270 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4271 if (!isset($params[$field])) {
4272 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4273 // Tax amount gets added back on later....
4274 $params['total_amount'] = $params['prevContribution']->total_amount
-
4275 $params['prevContribution']->tax_amount
;
4278 $params[$field] = $params['prevContribution']->$field;
4279 if ($params[$field] != $params['prevContribution']->$field) {
4285 self
::calculateMissingAmountParams($params, $params['id']);
4286 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4287 // Assign tax Amount on update of contribution
4288 if (!empty($params['prevContribution']->tax_amount
)) {
4289 $params['tax_amount'] = 'null';
4290 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4291 foreach ($params['line_item'] as $setID => $priceField) {
4292 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4293 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4300 // New Contribution and update of contribution with tax rate financial type
4301 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4302 empty($params['skipLineItem']) && !$isLineItem
4304 $taxRateParams = $taxRates[$params['financial_type_id']];
4305 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4306 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4308 // Get Line Item on update of contribution
4309 if (isset($params['id'])) {
4310 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4313 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4315 foreach ($params['line_item'] as $setID => $priceField) {
4316 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4317 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4320 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4322 elseif (isset($params['api.line_item.create'])) {
4323 // Update total amount of contribution using lineItem
4324 $taxAmountArray = [];
4325 foreach ($params['api.line_item.create'] as $key => $value) {
4326 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4327 $taxRate = $taxRates[$value['financial_type_id']];
4328 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4329 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4332 $params['tax_amount'] = array_sum($taxAmountArray);
4333 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4336 // update line item of contrbution
4337 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4338 $taxRate = $taxRates[$params['financial_type_id']];
4339 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4340 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4347 * Check financial type validation on update of a contribution.
4349 * @param int $financialTypeId
4350 * Value of latest Financial Type.
4352 * @param int $contributionId
4355 * @param array $errors
4360 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4361 if (!empty($financialTypeId)) {
4362 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4363 if ($oldFinancialTypeId == $financialTypeId) {
4367 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4369 '1' => [$contributionId, 'Integer'],
4371 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4372 if ($result->N
> 1) {
4373 $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.');
4378 * Update related pledge payment payments.
4380 * This function has been refactored out of the back office contribution form and may
4381 * still overlap with other functions.
4383 * @param string $action
4384 * @param int $pledgePaymentID
4385 * @param int $contributionID
4386 * @param bool $adjustTotalAmount
4387 * @param float $total_amount
4388 * @param float $original_total_amount
4389 * @param int $contribution_status_id
4390 * @param int $original_contribution_status_id
4392 public static function updateRelatedPledge(
4398 $original_total_amount,
4399 $contribution_status_id,
4400 $original_contribution_status_id
4402 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4406 if ($pledgePaymentID) {
4407 //store contribution id in payment record.
4408 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4411 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4418 if (!$pledgePaymentID) {
4421 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4427 $updatePledgePaymentStatus = FALSE;
4429 // If either the status or the amount has changed we update the pledge status.
4430 if ($action & CRM_Core_Action
::ADD
) {
4431 $updatePledgePaymentStatus = TRUE;
4433 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4434 ($original_total_amount != $total_amount))
4436 $updatePledgePaymentStatus = TRUE;
4439 if ($updatePledgePaymentStatus) {
4440 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4442 $contribution_status_id,
4451 * Compute the stats values
4453 * @param string $stat either 'mode' or 'median'
4454 * @param string $sql
4455 * @param string $alias of civicrm_contribution
4457 * @return array|null
4461 public static function computeStats($stat, $sql, $alias = NULL) {
4462 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4467 * Is there only one line item attached to the contribution.
4473 * @throws \CiviCRM_API3_Exception
4475 public static function isSingleLineItem($id) {
4476 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4477 return ($lineItemCount == 1);
4481 * Complete an order.
4483 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4485 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4487 * Moving it out of the BaseIPN class is just the first step.
4489 * @param array $input
4491 * @param array $objects
4492 * @param CRM_Core_Transaction $transaction
4494 * @param CRM_Contribute_BAO_Contribution $contribution
4498 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution) {
4499 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4500 // The previous details are used when calculating line items so keep it before any code that 'does something'
4501 if (!empty($contribution->id
)) {
4502 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4504 $inputContributionWhiteList = [
4509 'payment_instrument_id',
4514 'contribution_status_id',
4518 if (self
::isSingleLineItem($primaryContributionID)) {
4519 $inputContributionWhiteList[] = 'financial_type_id';
4522 $participant = CRM_Utils_Array
::value('participant', $objects);
4523 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4524 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4525 $event = CRM_Utils_Array
::value('event', $objects);
4527 $paymentProcessorId = '';
4528 if (isset($objects['paymentProcessor'])) {
4529 if (is_array($objects['paymentProcessor'])) {
4530 $paymentProcessorId = $objects['paymentProcessor']['id'];
4533 $paymentProcessorId = $objects['paymentProcessor']->id
;
4537 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4539 $contributionParams = array_merge([
4540 'contribution_status_id' => $completedContributionStatusID,
4541 'source' => self
::getRecurringContributionDescription($contribution, $event),
4542 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4545 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4546 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4547 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4550 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4552 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4553 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4554 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4555 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4558 if ($recurringContributionID) {
4559 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4561 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4563 if (empty($contributionParams['receive_date']) && $changeDate) {
4564 $contributionParams['receive_date'] = $changeDate;
4567 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4568 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4571 if (isset($input['is_email_receipt'])) {
4572 $values['is_email_receipt'] = $input['is_email_receipt'];
4575 if ($input['component'] == 'contribute') {
4576 if ($contribution->contribution_page_id
) {
4577 // Figure out what we gain from this.
4578 // Note that we may have overwritten the is_email_receipt input, fix that below.
4579 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4581 elseif ($recurContrib && $recurringContributionID) {
4582 $values['amount'] = $recurContrib->amount
;
4583 $values['financial_type_id'] = $objects['contributionType']->id
;
4584 $values['title'] = $source = ts('Offline Recurring Contribution');
4587 if (isset($input['is_email_receipt'])) {
4588 // CRM-19601 - we may have overwritten this above.
4589 $values['is_email_receipt'] = $input['is_email_receipt'];
4591 elseif ($recurContrib && $recurringContributionID) {
4592 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4593 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4594 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4597 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4598 self
::updateMembershipBasedOnCompletionOfContribution(
4600 $primaryContributionID,
4606 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4607 if ($event->is_email_confirm
) {
4608 // @todo this should be set by the function that sends the mail after sending.
4609 $contributionParams['receipt_date'] = $changeDate;
4611 $participantParams['id'] = $participant->id
;
4612 $participantParams['status_id'] = 'Registered';
4613 civicrm_api3('Participant', 'create', $participantParams);
4617 $contributionParams['id'] = $contribution->id
;
4619 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4620 // unsetting it here does NOT cause any other contribution test to fail!
4621 unset($contributionParams['financial_type_id']);
4622 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4624 // Add new soft credit against current $contribution.
4625 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4626 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4629 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4630 'labelColumn' => 'name',
4633 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4634 $input['payment_processor'] = $paymentProcessorId;
4637 if (!empty($contribution->_relatedObjects
['participant'])) {
4638 $input['contribution_mode'] = 'participant';
4639 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4641 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4642 // @todo - use getRelatedMemberships instead
4643 $input['contribution_mode'] = 'membership';
4644 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4645 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4646 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4649 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4650 $transaction->commit();
4652 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4653 $contributionParams['contribution_status_id'], $input['amount']);
4655 // create an activity record
4656 if ($input['component'] == 'contribute') {
4658 $targetContactID = NULL;
4659 if (!empty($ids['related_contact'])) {
4660 $targetContactID = $contribution->contact_id
;
4661 $contribution->contact_id
= $ids['related_contact'];
4663 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4666 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4667 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4668 if (!array_key_exists('is_email_receipt', $values) ||
4669 $values['is_email_receipt'] == 1
4671 civicrm_api3('Contribution', 'sendconfirmation', [
4672 'id' => $contribution->id
,
4673 'payment_processor_id' => $paymentProcessorId,
4675 CRM_Core_Error
::debug_log_message("Receipt sent");
4678 CRM_Core_Error
::debug_log_message("Success: Database updated");
4679 return $contributionResult;
4683 * Send receipt from contribution.
4685 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4687 * Note that the compose message part has been moved to contribution
4688 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4690 * @param array $input
4691 * Incoming data from Payment processor.
4693 * Related object IDs.
4694 * @param int $contributionID
4695 * @param array $values
4696 * Values related to objects that have already been loaded.
4697 * @param bool $returnMessageText
4698 * Should text be returned instead of sent. This.
4699 * is because the function is also used to generate pdfs
4702 * @throws \CRM_Core_Exception
4703 * @throws \CiviCRM_API3_Exception
4705 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4706 $returnMessageText = FALSE) {
4708 $contribution = new CRM_Contribute_BAO_Contribution();
4709 $contribution->id
= $contributionID;
4710 if (!$contribution->find(TRUE)) {
4711 throw new CRM_Core_Exception('Contribution does not exist');
4713 $contribution->loadRelatedObjects($input, $ids, TRUE);
4714 // set receipt from e-mail and name in value
4715 if (!$returnMessageText) {
4716 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4718 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4719 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4720 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4721 civicrm_api3('Contribution', 'create', [
4722 'receipt_date' => 'now',
4723 'id' => $contribution->id
,
4730 * Generate From email and from name in an array values
4732 * @param array $input
4733 * @param \CRM_Contribute_BAO_Contribution $contribution
4737 public static function generateFromEmailAndName($input, $contribution) {
4738 // Use input value if supplied.
4739 if (!empty($input['receipt_from_email'])) {
4741 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4742 $input['receipt_from_email'],
4745 // if we are still empty see if we can use anything from a contribution page.
4747 if (!empty($contribution->contribution_page_id
)) {
4748 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4750 // if we are still empty see if we can use anything from a contribution page.
4751 if (!empty($pageValues['receipt_from_email'])) {
4753 $pageValues['receipt_from_name'],
4754 $pageValues['receipt_from_email'],
4757 // If we are still empty fall back to the domain or logged in user information.
4758 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4762 * Generate credit note id with next avaible number
4767 public static function createCreditNoteId() {
4768 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4770 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4771 $creditNoteId = NULL;
4775 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4776 $result = civicrm_api3('Contribution', 'getcount', [
4778 'creditnote_id' => $creditNoteId,
4780 } while ($result > 0);
4782 return $creditNoteId;
4786 * Load related memberships.
4790 * @return array $ids
4795 * Note that in theory it should be possible to retrieve these from the line_item table
4796 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4797 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4798 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4799 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4801 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4804 public function loadRelatedMembershipObjects($ids = []) {
4806 SELECT membership_id
4807 FROM civicrm_membership_payment
4808 WHERE contribution_id = %1 ";
4809 $params = [1 => [$this->id
, 'Integer']];
4810 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4812 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4813 while ($dao->fetch()) {
4814 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4815 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4819 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4820 foreach ($ids['membership'] as $id) {
4822 $membership = new CRM_Member_BAO_Membership();
4823 $membership->id
= $id;
4824 if (!$membership->find(TRUE)) {
4825 throw new Exception("Could not find membership record: $id");
4827 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4828 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4829 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4830 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4838 * This function is used to record partial payments for contribution
4840 * @param array $contribution
4842 * @param array $params
4844 * @return CRM_Financial_DAO_FinancialTrxn
4846 public static function recordPartialPayment($contribution, $params) {
4847 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4848 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4849 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4850 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4851 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4852 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4853 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4854 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4855 $balanceTrxnParams['currency'] = $contribution['currency'];
4856 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4857 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4858 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4859 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4860 $balanceTrxnParams['is_payment'] = 1;
4862 if (!empty($params['payment_processor'])) {
4863 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4864 // also anticipates it.
4865 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4866 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4868 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4872 * Get the description (source field) for the recurring contribution.
4874 * @param CRM_Contribute_BAO_Contribution $contribution
4875 * @param CRM_Event_DAO_Event|null $event
4878 * @throws \CiviCRM_API3_Exception
4880 protected static function getRecurringContributionDescription($contribution, $event) {
4881 if (!empty($contribution->source
)) {
4882 return $contribution->source
;
4884 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4885 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4886 'id' => $contribution->contribution_page_id
,
4887 'return' => 'title',
4889 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4892 return ts('Online Event Registration') . ': ' . $event->title
;
4894 elseif (!empty($contribution->contribution_recur_id
)) {
4895 return 'recurring contribution';
4901 * Function to add payments for contribution
4902 * for Partially Paid status
4904 * @param array $contributions
4905 * @param string $contributionStatusId
4908 public static function addPayments($contributions, $contributionStatusId = NULL) {
4909 // get financial trxn which is a payment
4910 $ftSql = "SELECT ft.id, ft.total_amount
4911 FROM civicrm_financial_trxn ft
4912 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4913 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4914 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4915 'labelColumn' => 'name',
4917 foreach ($contributions as $contribution) {
4918 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4919 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4923 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, [
4931 // store financial item Proportionaly.
4933 'total_amount' => $ftDao->total_amount
,
4934 'contribution_id' => $contribution->id
,
4936 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4941 * Function use to store line item proportionally in in entity financial trxn table
4943 * @param array $trxnParams
4945 * @param int $trxnId
4947 * @param float $contributionTotalAmount
4949 * @throws \CiviCRM_API3_Exception
4951 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4952 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4953 if (!empty($lineItems)) {
4954 // get financial item
4955 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4957 'contribution_total_amount' => $contributionTotalAmount,
4958 'trxn_total_amount' => $trxnParams['total_amount'],
4959 'trxn_id' => $trxnId,
4961 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4966 * Checks if line items total amounts
4967 * match the contribution total amount.
4969 * @param array $params
4970 * array of order params.
4972 * @throws \API_Exception
4974 public static function checkLineItems(&$params) {
4975 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4976 $lineItemAmount = 0;
4978 foreach ($params['line_items'] as &$lineItems) {
4979 foreach ($lineItems['line_item'] as &$item) {
4980 if (empty($item['financial_type_id'])) {
4981 $item['financial_type_id'] = $params['financial_type_id'];
4983 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4987 if (!isset($totalAmount)) {
4988 $params['total_amount'] = $lineItemAmount;
4991 $currency = CRM_Utils_Array
::value('currency', $params, '');
4993 if (empty($currency)) {
4994 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4997 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4998 throw new CRM_Contribute_Exception_CheckLineItemsException();
5004 * Get the financial account for the item associated with the new transaction.
5006 * @param array $params
5007 * @param int $default
5011 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
5013 if (!empty($params['financial_account_id'])) {
5014 return $params['financial_account_id'];
5017 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5018 $preferredAccountsRelationships = [
5019 'Refunded' => 'Credit/Contra Revenue Account is',
5020 'Chargeback' => 'Chargeback Account is',
5023 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5024 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5025 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5027 $preferredAccountsRelationships[$contributionStatus]
5035 * ContributionPage values were being imposed onto values.
5037 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5038 * REALLY didn't want superimposed. The rest are left there in their overkill out
5041 * The rationale for making this explicit is that it was a case of carefully set values being
5042 * seemingly randonly overwritten without much care. In general I think array randomly setting
5043 * variables en mass is risky.
5045 * @param array $values
5049 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5050 $contributionPageValues = [];
5051 CRM_Contribute_BAO_ContributionPage
::setValues(
5052 $this->contribution_page_id
,
5053 $contributionPageValues
5056 // These are the values that I believe to be useful.
5059 'pay_later_receipt',
5061 'receipt_from_email',
5062 'receipt_from_name',
5066 'honoree_profile_id',
5067 'onbehalf_profile_id',
5068 'honor_block_is_active',
5069 // Kinda might be - but would be on the contribution...
5072 // Included for 'fear of regression' but can't justify any use for these....
5074 'payment_processor',
5075 'financial_type_id',
5076 'amount_block_is_active',
5081 'default_amount_id',
5085 'initial_amount_help_text',
5086 'initial_amount_label',
5088 'is_allow_other_amount',
5089 'is_billing_required',
5090 'is_confirm_enabled',
5091 'is_credit_card_only',
5093 'is_partial_payment',
5094 'is_recur_installments',
5095 'is_recur_interval',
5099 'min_initial_amount',
5100 'recur_frequency_unit',
5107 foreach ($valuesToCopy as $valueToCopy) {
5108 if (isset($contributionPageValues[$valueToCopy])) {
5109 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5116 * Get values of CiviContribute Settings
5117 * and check if its enabled or not.
5118 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5119 * in serialized form. Usually this should be stored as flat settings for each form fields
5120 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5121 * settings we will live with an inconsistency because it's too hard to change for now.
5122 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5125 * @param string $name
5126 * @param bool $checkInvoicing
5130 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5131 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5133 if ($checkInvoicing && !CRM_Utils_Array
::value('invoicing', $contributeSettings)) {
5138 return CRM_Utils_Array
::value($name, $contributeSettings);
5140 return $contributeSettings;
5144 * This function process contribution related objects.
5146 * @param int $contributionId
5147 * @param int $statusId
5148 * @param int|null $previousStatusId
5150 * @param string $receiveDate
5152 * @return null|string
5154 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5156 if (!$contributionId ||
!$statusId) {
5161 'contribution_id' => $contributionId,
5162 'contribution_status_id' => $statusId,
5163 'previous_contribution_status_id' => $previousStatusId,
5164 'receive_date' => $receiveDate,
5167 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5169 if (!is_array($updateResult) ||
5170 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5171 !is_array($updatedComponents) ||
5172 empty($updatedComponents)
5177 // get the user display name.
5179 SELECT display_name as displayName
5180 FROM civicrm_contact
5181 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5182 WHERE civicrm_contribution.id = {$contributionId}";
5183 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5185 // get the status message for user.
5186 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5188 if ($componentName == 'CiviMember') {
5189 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5190 CRM_Member_PseudoConstant
::membershipStatus()
5193 $statusNameMsgPart = 'updated';
5194 switch ($updatedStatusName) {
5197 $statusNameMsgPart = $updatedStatusName;
5201 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5202 1 => $userDisplayName,
5203 2 => $statusNameMsgPart,
5207 if ($componentName == 'CiviEvent') {
5208 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5209 CRM_Event_PseudoConstant
::participantStatus()
5211 if ($updatedStatusName == 'Cancelled') {
5212 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5214 elseif ($updatedStatusName == 'Registered') {
5215 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5219 if ($componentName == 'CiviPledge') {
5220 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5221 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5223 if ($updatedStatusName == 'Cancelled') {
5224 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5226 elseif ($updatedStatusName == 'Failed') {
5227 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5229 elseif ($updatedStatusName == 'Completed') {
5230 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5239 * Get the contribution as it is in the database before being updated.
5241 * @param int $contributionID
5243 * @return \CRM_Contribute_BAO_Contribution|null
5245 private static function getOriginalContribution($contributionID) {
5246 return self
::getValues(['id' => $contributionID]);
5250 * Get the amount for the financial item row.
5252 * Helper function to start to break down recordFinancialTransactions for readability.
5254 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5256 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5257 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5260 * @param array $params
5261 * Params as passed to contribution.create
5263 * @param string $context
5264 * changeFinancialType| changedAmount
5265 * @param array $lineItemDetails
5267 * @param bool $isARefund
5268 * Is this a refund / negative transaction.
5269 * @param int $previousLineItemTotal
5272 * @todo move recordFinancialAccounts & helper functions to their own class?
5275 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5276 if ($context == 'changedAmount') {
5277 $lineTotal = $lineItemDetails['line_total'];
5278 if ($lineTotal != $previousLineItemTotal) {
5279 $lineTotal -= $previousLineItemTotal;
5283 elseif ($context == 'changeFinancialType') {
5284 return -$lineItemDetails['line_total'];
5286 elseif ($context == 'changedStatus') {
5287 $cancelledTaxAmount = 0;
5289 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5291 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5293 elseif ($context === NULL) {
5294 // erm, yes because? but, hey, it's tested.
5295 return $lineItemDetails['line_total'];
5297 elseif (empty($lineItemDetails['line_total'])) {
5298 // follow legacy code path
5300 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5301 return $params['total_amount'];
5304 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5309 * Get the multiplier for adjusting rows.
5311 * If we are dealing with a refund or cancellation then it will be a negative
5312 * amount to reflect the negative transaction.
5314 * If we are changing Financial Type it will be a negative amount to
5315 * adjust down the old type.
5317 * @param int $contribution_status_id
5318 * @param string $context
5322 protected static function getMultiplier($contribution_status_id, $context) {
5323 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5330 * Does this transaction reflect a payment instrument change.
5332 * @param array $params
5333 * @param array $pendingStatuses
5337 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5338 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5340 if (array_key_exists('payment_instrument_id', $params)) {
5341 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5342 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5344 //check if status is changed from Pending to Completed
5345 // do not update payment instrument changes for Pending to Completed
5346 if (!($contributionStatus == 'Completed' &&
5347 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5352 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5353 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5354 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5358 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5359 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5361 // another special case when check number is changed, create new financial records
5362 // create financial trxn with negative amount
5370 * Update the memberships associated with a contribution if it has been completed.
5372 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5373 * load them in this function. Code clean up would compensate for any minor performance implication.
5375 * @param \CRM_Contribute_BAO_Contribution $contribution
5376 * @param int $primaryContributionID
5377 * @param string $changeDate
5379 * @throws \CRM_Core_Exception
5380 * @throws \CiviCRM_API3_Exception
5382 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5383 $memberships = self
::getRelatedMemberships($contribution->id
);
5384 foreach ($memberships as $membership) {
5385 $membershipParams = [
5386 'id' => $membership['id'],
5387 'contact_id' => $membership['contact_id'],
5388 'is_test' => $membership['is_test'],
5389 'membership_type_id' => $membership['membership_type_id'],
5390 'membership_activity_status' => 'Completed',
5393 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5394 $membershipParams['membership_type_id'],
5395 $membershipParams['is_test'],
5396 $membershipParams['id']
5399 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5400 // this picks up membership type changes during renewals
5401 // @todo this is almost certainly an obsolete sql call, the pre-change
5402 // membership is accessible via $this->_relatedObjects
5404 SELECT membership_type_id
5405 FROM civicrm_membership_log
5406 WHERE membership_id={$membershipParams['id']}
5409 $dao = CRM_Core_DAO
::executeQuery($sql);
5410 if ($dao->fetch()) {
5411 if (!empty($dao->membership_type_id
)) {
5412 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5416 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5417 $membershipParams['membership_type_id'],
5418 $primaryContributionID
5420 // @todo remove all this stuff in favour of letting the api call further down handle in
5421 // (it is a duplication of what the api does).
5422 $dates = array_fill_keys([
5427 if ($currentMembership) {
5429 * Fixed FOR CRM-4433
5430 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5431 * when Contribution mode is notify and membership is for renewal )
5433 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5435 // @todo - we should pass membership_type_id instead of null here but not
5436 // adding as not sure of testing
5437 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5438 $changeDate, NULL, $membershipParams['num_terms']
5440 $dates['join_date'] = $currentMembership['join_date'];
5443 //get the status for membership.
5444 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5446 $dates['join_date'],
5449 $membershipParams['membership_type_id'],
5453 unset($dates['end_date']);
5454 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5455 //we might be renewing membership,
5456 //so make status override false.
5457 $membershipParams['is_override'] = FALSE;
5458 $membershipParams['status_override_end_date'] = 'null';
5460 //CRM-17723 - reset static $relatedContactIds array()
5461 // @todo move it to Civi Statics.
5463 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5464 civicrm_api3('Membership', 'create', $membershipParams);
5469 * Get payment links as they relate to a contribution.
5471 * If a payment can be made then include a payment link & if a refund is appropriate
5472 * then a refund link.
5475 * @param float $balance
5476 * @param string $contributionStatus
5479 * $actionLinks Links array containing:
5483 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5484 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5485 // In general the balance is the best way to determine if a payment can be added or not,
5486 // but not for Failed contributions, where we don't accept additional payments at the moment.
5487 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5488 // do accept more payments agains them.
5492 if ((int) $balance > 0) {
5493 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5495 'url' => CRM_Utils_System
::url('civicrm/payment', [
5501 'title' => ts('Submit Credit Card payment'),
5505 'url' => CRM_Utils_System
::url('civicrm/payment', [
5510 'title' => ts('Record Payment'),
5513 elseif ((int) $balance < 0) {
5515 'url' => CRM_Utils_System
::url('civicrm/payment', [
5520 'title' => ts('Record Refund'),
5523 return $actionLinks;
5527 * Get a query to determine the amount donated by the contact/s in the current financial year.
5529 * @param array $contactIDs
5533 public static function getAnnualQuery($contactIDs) {
5534 $contactIDs = implode(',', $contactIDs);
5535 $config = CRM_Core_Config
::singleton();
5536 $currentMonth = date('m');
5537 $currentDay = date('d');
5539 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5541 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5542 (int) $config->fiscalYearStart
['d'] > $currentDay
5545 $year = date('Y') - 1;
5550 $nextYear = $year +
1;
5552 if ($config->fiscalYearStart
) {
5553 $newFiscalYearStart = $config->fiscalYearStart
;
5554 if ($newFiscalYearStart['M'] < 10) {
5555 // This is just a clumsy way of adding padding.
5556 // @todo next round look for a nicer way.
5557 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5559 if ($newFiscalYearStart['d'] < 10) {
5560 // This is just a clumsy way of adding padding.
5561 // @todo next round look for a nicer way.
5562 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5564 $config->fiscalYearStart
= $newFiscalYearStart;
5565 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5568 // First of January.
5571 $startDate = "$year$monthDay";
5572 $endDate = "$nextYear$monthDay";
5575 'contact_id' => 'IN (' . $contactIDs . ')',
5576 'is_test' => ' = 0',
5577 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5579 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5580 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5583 foreach ($whereClauses as $key => $clause) {
5584 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5586 $whereClauseString = implode(' AND ', $clauses);
5588 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5589 // this group by + having on contribution_status_id improves performance
5591 SELECT COUNT(*) as count,
5592 SUM(total_amount) as amount,
5593 AVG(total_amount) as average,
5595 FROM civicrm_contribution b
5596 WHERE " . $whereClauseString . "
5597 GROUP BY currency, contribution_status_id
5598 HAVING $havingClause
5604 * Assign Test Value.
5606 * @param string $fieldName
5607 * @param array $fieldDef
5608 * @param int $counter
5610 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5611 if ($fieldName == 'tax_amount') {
5612 $this->{$fieldName} = "0.00";
5614 elseif ($fieldName == 'net_amount') {
5615 $this->{$fieldName} = "2.00";
5617 elseif ($fieldName == 'total_amount') {
5618 $this->{$fieldName} = "3.00";
5620 elseif ($fieldName == 'fee_amount') {
5621 $this->{$fieldName} = "1.00";
5624 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5629 * Check if contribution has participant/membership payment.
5631 * @param int $contributionId
5636 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5637 // get line item for contribution
5638 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5639 // check if line item is for membership or participant
5640 foreach ($lineItems as $items) {
5641 if ($items['entity_table'] == 'civicrm_participant') {
5645 elseif ($items['entity_table'] == 'civicrm_membership') {
5657 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5659 * @param array $trxnParams
5660 * Financial trxn params
5661 * @param array $contributionParams
5662 * Contribution Params
5666 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5667 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5670 $statusId = $contributionParams['contribution']->contribution_status_id
;
5671 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5672 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5673 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5674 // Return if contribution status is not completed.
5675 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5676 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5677 && $contributionParams['prevContribution']->is_pay_later
== 0
5683 $params = $trxnParams;
5684 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5685 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5686 $params['to_financial_account_id'] = $arAccountId;
5687 $params['status_id'] = array_search('Pending', $contributionStatuses);
5688 $params['is_payment'] = FALSE;
5689 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5690 self
::$_trxnIDs[] = $trxn->id
;
5691 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5695 * Calculate financial item amount when contribution is updated.
5697 * @param array $params
5698 * contribution params
5699 * @param array $amountParams
5701 * @param string $context
5705 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5706 if (!empty($params['is_quick_config'])) {
5707 $amount = $amountParams['item_amount'];
5709 $amount = $params['total_amount'];
5710 if ($context === NULL) {
5711 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5716 $amount = $amountParams['line_total'];
5717 if ($context == 'changedAmount') {
5718 $amount -= $amountParams['previous_line_total'];
5720 $amount *= $amountParams['diff'];
5726 * Retrieve Sales Tax Financial Accounts.
5732 public static function getSalesTaxFinancialAccounts() {
5733 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5734 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5735 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5736 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5737 $queryParams = [1 => [$accountRel, 'Integer']];
5738 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5739 $financialAccount = [];
5740 while ($dao->fetch()) {
5741 $financialAccount[$dao->id
] = $dao->id
;
5743 return $financialAccount;
5747 * Create tax entry in civicrm_entity_financial_trxn table.
5749 * @param array $entityParams
5751 * @param array $eftParams
5753 * @throws \CiviCRM_API3_Exception
5755 public static function createProportionalEntry($entityParams, $eftParams) {
5757 if ($entityParams['contribution_total_amount'] != 0) {
5758 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5760 // Record Entity Financial Trxn; CRM-20145
5761 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5762 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5766 * Create array of last financial item id's.
5768 * @param int $contributionId
5772 public static function getLastFinancialItemIds($contributionId) {
5773 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5774 FROM civicrm_financial_item fi
5775 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5776 WHERE li.contribution_id = %1";
5777 $dao = CRM_Core_DAO
::executeQuery($sql, [
5783 $ftIds = $taxItems = [];
5784 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5785 while ($dao->fetch()) {
5786 /* if sales tax item*/
5787 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5788 $taxItems[$dao->price_field_value_id
] = [
5789 'financial_item_id' => $dao->id
,
5790 'amount' => $dao->tax_amount
,
5794 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5797 return [$ftIds, $taxItems];
5801 * Create proportional entries in civicrm_entity_financial_trxn.
5803 * @param array $entityParams
5805 * @param array $lineItems
5807 * @param array $ftIds
5809 * @param array $taxItems
5811 * @throws \CiviCRM_API3_Exception
5813 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5815 'entity_table' => 'civicrm_financial_item',
5816 'financial_trxn_id' => $entityParams['trxn_id'],
5818 foreach ($lineItems as $key => $value) {
5819 if ($value['qty'] == 0) {
5822 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5823 $entityParams['line_item_amount'] = $value['line_total'];
5824 self
::createProportionalEntry($entityParams, $eftParams);
5825 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5826 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5827 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5828 self
::createProportionalEntry($entityParams, $eftParams);
5834 * Load entities related to the contribution into $this->_relatedObjects.
5838 * @throws \CRM_Core_Exception
5840 protected function loadRelatedEntitiesByID($ids) {
5842 'contact' => 'CRM_Contact_BAO_Contact',
5843 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5844 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5845 'financialType' => 'CRM_Financial_BAO_FinancialType',
5846 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5848 foreach ($entities as $entity => $bao) {
5849 if (!empty($ids[$entity])) {
5850 $this->_relatedObjects
[$entity] = new $bao();
5851 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5852 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5853 throw new CRM_Core_Exception($entity . ' could not be loaded');
5860 * Should an email receipt be sent for this contribution when complete.
5862 * @param array $input
5866 protected function isEmailReceipt($input) {
5867 if (isset($input['is_email_receipt'])) {
5868 return $input['is_email_receipt'];
5870 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5871 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5877 * Function to replace contribution tokens.
5879 * @param array $contributionIds
5881 * @param string $subject
5883 * @param array $subjectToken
5885 * @param string $text
5887 * @param string $html
5889 * @param array $messageToken
5891 * @param bool $escapeSmarty
5894 * @throws \CiviCRM_API3_Exception
5896 public static function replaceContributionTokens(
5905 if (empty($contributionIds)) {
5908 $contributionDetails = [];
5909 foreach ($contributionIds as $id) {
5910 $result = self
::getContributionTokenValues($id, $messageToken);
5911 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5912 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5913 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5915 return $contributionDetails;
5919 * Get the contribution fields for $id and display labels where
5920 * appropriate (if the token is present).
5923 * @param array $messageToken
5926 public static function getContributionTokenValues($id, $messageToken) {
5930 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5931 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5932 if (!empty($messageToken)) {
5933 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5934 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5935 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5943 * Get invoice_number for contribution.
5945 * @param int $contributionID
5949 public static function getInvoiceNumber($contributionID) {
5950 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5951 return $invoicePrefix . $contributionID;