3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
20 * Static field for all the contribution information that we can potentially import
24 public static $_importableFields = NULL;
27 * Static field for all the contribution information that we can potentially export
31 public static $_exportableFields = NULL;
34 * Static field to hold financial trxn id's.
38 public static $_trxnIDs = NULL;
41 * Field for all the objects related to this contribution
43 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
45 public $_relatedObjects = [];
48 * Field for the component - either 'event' (participant) or 'contribute'
49 * (any item related to a contribution page e.g. membership, pledge, contribution)
50 * This is used for composing messages because they have dependency on the
51 * contribution_page or event page - although over time we may eliminate that
54 * "contribution"\"event"
56 public $_component = NULL;
59 * Possibly obsolete variable.
61 * If you use it please explain why it is set in the create function here.
65 public $trxn_result_code;
70 public function __construct() {
71 parent
::__construct();
75 * Takes an associative array and creates a contribution object.
77 * the function extract all the params it needs to initialize the create a
78 * contribution object. the params array could contain additional unused name/value
81 * @param array $params
82 * (reference ) an assoc array of name/value pairs.
84 * The array that holds all the db ids.
86 * @return \CRM_Contribute_BAO_Contribution
87 * @throws \CRM_Core_Exception
88 * @throws \CiviCRM_API3_Exception
90 public static function add(&$params, $ids = []) {
95 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be passed into Contribution.add');
97 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
98 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
99 $action = $contributionID ?
'edit' : 'create';
101 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
102 $message = ts("Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: %1", [1 => implode(', ', $duplicates)]);
103 throw new CRM_Core_Exception($message);
106 // first clean up all the money fields
111 'non_deductible_amount',
114 //if priceset is used, no need to cleanup money
115 if (!empty($params['skipCleanMoney'])) {
119 // @todo put a deprecated here - this should be done in the form layer.
120 $params['skipCleanMoney'] = FALSE;
121 Civi
::log()->warning('Deprecated code path. Money should always be clean before it hits the BAO.', array('civi.tag' => 'deprecated'));
124 foreach ($moneyFields as $field) {
125 if (isset($params[$field])) {
126 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
130 //set defaults in create mode
131 if (!$contributionID) {
132 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
134 if (empty($params['invoice_number'])) {
135 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
136 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
140 //if contribution is created with cancelled or refunded status, add credit note id
141 // do the same for chargeback - this entered the code 'accidentally' but moving it to here
142 // as part of cleanup maintains consistency.
143 if (self
::isContributionStatusNegative(CRM_Utils_Array
::value('contribution_status_id', $params))) {
144 if (empty($params['creditnote_id'])) {
145 $params['creditnote_id'] = self
::createCreditNoteId();
148 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
149 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
150 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
152 if (!$contributionStatusID) {
153 // Since the fee amount is expecting this (later on) ensure it is always set.
154 // It would only not be set for an update where it is unchanged.
155 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
156 'id' => $contributionID,
157 'return' => 'contribution_status_id',
160 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
163 && CRM_Utils_Array
::value('membership_id', $params)
164 && Civi
::settings()->get('deferred_revenue_enabled')
166 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
167 if ($memberStartDate) {
168 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
171 self
::calculateMissingAmountParams($params, $contributionID);
173 if (!empty($params['payment_instrument_id'])) {
174 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
175 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
176 $params['check_number'] = 'null';
180 $setPrevContribution = TRUE;
181 // CRM-13964 partial payment
182 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])) {
183 $partialAmtTotal = $params['partial_payment_total'];
184 $partialAmtPay = $params['partial_amount_to_pay'];
185 $params['total_amount'] = $partialAmtTotal;
186 if ($partialAmtPay < $partialAmtTotal) {
187 $params['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Partially paid');
188 $params['is_pay_later'] = 0;
189 $setPrevContribution = FALSE;
192 if ($contributionID && $setPrevContribution) {
193 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
195 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
197 if ($contributionID && !empty($params['revenue_recognition_date'])
198 && !($previousContributionStatus === 'Pending')
199 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
201 unset($params['revenue_recognition_date']);
204 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
205 isset($params['financial_type_id']))) {
206 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
209 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
211 $contribution = new CRM_Contribute_BAO_Contribution();
212 $contribution->copyValues($params);
214 $contribution->id
= $contributionID;
216 if (empty($contribution->id
)) {
217 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
218 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
219 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
223 $result = $contribution->save();
225 // Add financial_trxn details as part of fix for CRM-4724
226 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
227 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
229 //add Account details
230 $params['contribution'] = $contribution;
231 if (empty($params['is_post_payment_create'])) {
232 // If this is being called from the Payment.create api/ BAO then that Entity
233 // takes responsibility for the financial transactions. In fact calling Payment.create
234 // to add payments & having it call completetransaction and / or contribution.create
235 // to update related entities is the preferred flow.
236 // Note that leveraging this parameter for any other code flow is not supported and
237 // is likely to break in future and / or cause serious problems in your data.
238 // https://github.com/civicrm/civicrm-core/pull/14673
239 self
::recordFinancialAccounts($params);
242 if (self
::isUpdateToRecurringContribution($params)) {
243 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
244 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
246 CRM_Utils_Array
::value('receive_date', $params)
250 $params['contribution_id'] = $contribution->id
;
252 if (!empty($params['custom']) &&
253 is_array($params['custom'])
255 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
258 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
260 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
265 * Is this contribution updating an existing recurring contribution.
267 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
268 * pending payment is being confirmed (or failing).
270 * @param array $params
274 public static function isUpdateToRecurringContribution($params) {
275 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
278 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
281 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
284 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
285 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
292 * Get defaults for new entity.
296 public static function getDefaults() {
298 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
299 FALSE, FALSE, FALSE, 'AND is_default = 1')
301 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
302 'receive_date' => date('Y-m-d H:i:s'),
307 * Fetch the object and store the values in the values array.
309 * @param array $params
310 * Input parameters to find object.
311 * @param array $values
312 * Output values of the object.
314 * The array that holds all the db ids.
316 * @return CRM_Contribute_BAO_Contribution|null
317 * The found object or null
319 public static function getValues($params, &$values = [], &$ids = []) {
320 if (empty($params)) {
323 $contribution = new CRM_Contribute_BAO_Contribution();
325 $contribution->copyValues($params);
327 if ($contribution->find(TRUE)) {
328 $ids['contribution'] = $contribution->id
;
330 CRM_Core_DAO
::storeValues($contribution, $values);
332 return $contribution;
334 // return by reference
340 * Get the values and resolve the most common mappings.
342 * Since contribution status is resolved in almost every function that calls getValues it makes
343 * sense to have an extra function to resolve it rather than repeat the code.
345 * Think carefully before adding more mappings to be resolved as there could be performance implications
346 * if this function starts to be called from more iterative functions.
348 * @param array $params
349 * Input parameters to find object.
352 * Array of the found contribution.
353 * @throws CRM_Core_Exception
355 public static function getValuesWithMappings($params) {
357 $contribution = self
::getValues($params, $values, $ids);
358 if (is_null($contribution)) {
359 throw new CRM_Core_Exception('No contribution found');
361 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
366 * Calculate net_amount & fee_amount if they are not set.
368 * Net amount should be total - fee.
369 * This should only be called for new contributions.
371 * @param array $params
372 * Params for a new contribution before they are saved.
373 * @param int|null $contributionID
374 * Contribution ID if we are dealing with an update.
376 * @throws \CiviCRM_API3_Exception
378 public static function calculateMissingAmountParams(&$params, $contributionID) {
379 if (!$contributionID && !isset($params['fee_amount'])) {
380 if (isset($params['total_amount']) && isset($params['net_amount'])) {
381 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
384 $params['fee_amount'] = 0;
387 if (!isset($params['net_amount'])) {
388 if (!$contributionID) {
389 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
392 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
393 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
394 // net_amount may need adjusting.
395 $contribution = civicrm_api3('Contribution', 'getsingle', [
396 'id' => $contributionID,
397 'return' => ['total_amount', 'net_amount', 'fee_amount'],
399 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
400 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
401 $params['net_amount'] = $totalAmount - $feeAmount;
409 * @param $billingLocationTypeID
413 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
414 $hasBillingField = FALSE;
423 //build address array
425 $addressParams['location_type_id'] = $billingLocationTypeID;
426 $addressParams['is_billing'] = 1;
428 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
429 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
430 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
431 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
433 foreach ($billingFields as $value) {
434 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
435 if (!empty($addressParams[$value])) {
436 $hasBillingField = TRUE;
439 return [$hasBillingField, $addressParams];
443 * Get address params ready to be passed to the payment processor.
445 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
446 * To create an address we need state_province_id.
448 * @param array $params
449 * @param int $billingLocationTypeID
453 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
454 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
455 foreach ($addressParams as $name => $field) {
456 if (substr($name, 0, 8) == 'billing_') {
457 $addressParams[substr($name, 9)] = $addressParams[$field];
460 return [$hasBillingField, $addressParams];
464 * Get the number of terms for this contribution for a given membership type
465 * based on querying the line item table and relevant price field values
466 * Note that any one contribution should only be able to have one line item relating to a particular membership
469 * @param int $membershipTypeID
471 * @param int $contributionID
475 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
476 $numTerms = CRM_Core_DAO
::singleValueQuery("
477 SELECT membership_num_terms FROM civicrm_line_item li
478 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
479 WHERE contribution_id = %1 AND membership_type_id = %2",
480 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
482 // default of 1 is precautionary
483 return empty($numTerms) ?
1 : $numTerms;
487 * Takes an associative array and creates a contribution object.
489 * @param array $params
490 * (reference ) an assoc array of name/value pairs.
492 * The array that holds all the db ids.
494 * @return CRM_Contribute_BAO_Contribution
496 * @throws \CRM_Core_Exception
497 * @throws \CiviCRM_API3_Exception
499 public static function create(&$params, $ids = []) {
505 'revenue_recognition_date',
507 foreach ($dateFields as $df) {
508 if (isset($params[$df])) {
509 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
513 $transaction = new CRM_Core_Transaction();
516 if (!isset($params['id']) && isset($ids['contribution'])) {
517 CRM_Core_Error
::deprecatedFunctionWarning('ids should not be used for contribution create');
518 $params['id'] = $ids['contribution'];
520 $contribution = self
::add($params);
522 catch (CRM_Core_Exception
$e) {
523 $transaction->rollback();
527 $params['contribution_id'] = $contribution->id
;
528 $session = CRM_Core_Session
::singleton();
530 if (!empty($params['note'])) {
532 'entity_table' => 'civicrm_contribution',
533 'note' => $params['note'],
534 'entity_id' => $contribution->id
,
535 'contact_id' => $session->get('userID'),
536 'modified_date' => date('Ymd'),
538 if (!$noteParams['contact_id']) {
539 $noteParams['contact_id'] = $params['contact_id'];
541 CRM_Core_BAO_Note
::add($noteParams);
544 // make entry in batch entity batch table
545 if (!empty($params['batch_id'])) {
546 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
553 $retrieveRequired = 0;
554 foreach ($titleFields as $titleField) {
555 if (!isset($contribution->$titleField)) {
556 $retrieveRequired = 1;
560 if ($retrieveRequired == 1) {
561 $contribution->find(TRUE);
565 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
567 $transaction->commit();
569 $activity = civicrm_api3('Activity', 'get', [
570 'source_record_id' => $contribution->id
,
571 'options' => ['limit' => 1],
573 'activity_type_id' => 'Contribution',
574 'return' => ['id', 'campaign'],
577 //CRM-18406: Update activity when edit contribution.
578 if ($activity['count']) {
579 // CRM-13237 : if activity record found, update it with campaign id of contribution
580 // @todo compare campaign ids first.
581 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity['id'], 'campaign_id', $contribution->campaign_id
);
582 $contribution->activity_id
= $activity['id'];
585 if (empty($contribution->contact_id
)) {
586 $contribution->find(TRUE);
588 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution');
590 // do not add to recent items for import, CRM-4399
591 if (empty($params['skipRecentView'])) {
592 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
593 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
595 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
602 $retrieveRequired = 0;
603 foreach ($titleFields as $titleField) {
604 if (!isset($contribution->$titleField)) {
605 $retrieveRequired = 1;
609 if ($retrieveRequired == 1) {
610 $contribution->find(TRUE);
612 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
613 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
616 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
617 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
618 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
622 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
623 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
624 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
628 // add the recently created Contribution
629 CRM_Utils_Recent
::add($title,
633 $contribution->contact_id
,
639 return $contribution;
643 * Get the values for pseudoconstants for name->value and reverse.
645 * @param array $defaults
646 * (reference) the default values, some of which need to be resolved.
647 * @param bool $reverse
648 * True if we want to resolve the values in the reverse direction (value -> name).
650 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
651 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
652 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
653 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
654 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
658 * Convert associative array names to values and vice-versa.
660 * This function is used by both the web form layer and the api. Note that
661 * the api needs the name => value conversion, also the view layer typically
662 * requires value => name conversion
664 * @param array $defaults
665 * @param string $property
666 * @param array $lookup
667 * @param bool $reverse
671 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
672 $id = $property . '_id';
674 $src = $reverse ?
$property : $id;
675 $dst = $reverse ?
$id : $property;
677 if (!array_key_exists($src, $defaults)) {
681 $look = $reverse ?
array_flip($lookup) : $lookup;
683 if (is_array($look)) {
684 if (!array_key_exists($defaults[$src], $look)) {
688 $defaults[$dst] = $look[$defaults[$src]];
693 * Retrieve DB object based on input parameters.
695 * It also stores all the retrieved values in the default array.
697 * @param array $params
698 * (reference ) an assoc array of name/value pairs.
699 * @param array $defaults
700 * (reference ) an assoc array to hold the name / value pairs.
701 * in a hierarchical manner
703 * (reference) the array that holds all the db ids.
705 * @return CRM_Contribute_BAO_Contribution
707 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
708 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
709 return $contribution;
713 * Combine all the importable fields from the lower levels object.
715 * The ordering is important, since currently we do not have a weight
716 * scheme. Adding weight is super important and should be done in the
717 * next week or so, before this can be called complete.
719 * @param string $contactType
720 * @param bool $status
723 * array of importable Fields
725 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
726 if (!self
::$_importableFields) {
727 if (!self
::$_importableFields) {
728 self
::$_importableFields = [];
732 $fields = ['' => ['title' => ts('- do not import -')]];
735 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
738 $note = CRM_Core_DAO_Note
::import();
739 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
740 unset($tmpFields['option_value']);
741 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
742 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
744 // Using new Dedupe rule.
746 'contact_type' => $contactType,
747 'used' => 'Unsupervised',
749 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
750 $tmpContactField = [];
751 if (is_array($fieldsArray)) {
752 foreach ($fieldsArray as $value) {
753 //skip if there is no dupe rule
754 if ($value == 'none') {
757 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
762 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
763 $tmpContactField[trim($value)] = $contactFields[trim($value)];
765 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
768 $title = $tmpContactField[trim($value)]['title'];
770 $tmpContactField[trim($value)]['title'] = $title;
774 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
775 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
776 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
777 $fields = array_merge($fields, $tmpContactField);
778 $fields = array_merge($fields, $tmpFields);
779 $fields = array_merge($fields, $note);
780 $fields = array_merge($fields, $optionFields);
781 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
782 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
783 self
::$_importableFields = $fields;
785 return self
::$_importableFields;
789 * Combine all the exportable fields from the lower level objects.
791 * @param bool $checkPermission
794 * array of exportable Fields
796 public static function &exportableFields($checkPermission = TRUE) {
797 if (!self
::$_exportableFields) {
798 if (!self
::$_exportableFields) {
799 self
::$_exportableFields = [];
802 $fields = CRM_Contribute_DAO_Contribution
::export();
803 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
804 $fields = array_merge(
806 CRM_Contribute_DAO_Product
::export(),
807 CRM_Contribute_DAO_ContributionProduct
::export(),
808 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
810 'contribution_product_id' => [
811 'title' => ts('Premium'),
812 'name' => 'contribution_product_id',
813 'where' => 'civicrm_product.id',
814 'data_type' => CRM_Utils_Type
::T_INT
,
820 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
822 $contributionPage = [
823 'contribution_page' => [
824 'title' => ts('Contribution Page'),
825 'name' => 'contribution_page',
826 'where' => 'civicrm_contribution_page.title',
827 'data_type' => CRM_Utils_Type
::T_STRING
,
831 $contributionNote = [
832 'contribution_note' => [
833 'title' => ts('Contribution Note'),
834 'name' => 'contribution_note',
835 'data_type' => CRM_Utils_Type
::T_TEXT
,
840 'contribution_batch' => [
841 'title' => ts('Batch Name'),
847 'contribution_campaign_title' => [
848 'title' => ts('Campaign Title'),
849 'name' => 'campaign_title',
850 'where' => 'civicrm_campaign.title',
851 'data_type' => CRM_Utils_Type
::T_STRING
,
854 $softCreditFields = [
855 'contribution_soft_credit_name' => [
856 'name' => 'contribution_soft_credit_name',
857 'title' => ts('Soft Credit For'),
858 'where' => 'civicrm_contact_d.display_name',
859 'data_type' => CRM_Utils_Type
::T_STRING
,
861 'contribution_soft_credit_amount' => [
862 'name' => 'contribution_soft_credit_amount',
863 'title' => ts('Soft Credit Amount'),
864 'where' => 'civicrm_contribution_soft.amount',
865 'data_type' => CRM_Utils_Type
::T_MONEY
,
867 'contribution_soft_credit_type' => [
868 'name' => 'contribution_soft_credit_type',
869 'title' => ts('Soft Credit Type'),
870 'where' => 'contribution_softcredit_type.label',
871 'data_type' => CRM_Utils_Type
::T_STRING
,
873 'contribution_soft_credit_contribution_id' => [
874 'name' => 'contribution_soft_credit_contribution_id',
875 'title' => ts('Soft Credit For Contribution ID'),
876 'where' => 'civicrm_contribution_soft.contribution_id',
877 'data_type' => CRM_Utils_Type
::T_INT
,
879 'contribution_soft_credit_contact_id' => [
880 'name' => 'contribution_soft_credit_contact_id',
881 'title' => ts('Soft Credit For Contact ID'),
882 'where' => 'civicrm_contact_d.id',
883 'data_type' => CRM_Utils_Type
::T_INT
,
887 $fields = array_merge($fields, $contributionPage,
888 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
889 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
892 self
::$_exportableFields = $fields;
895 return self
::$_exportableFields;
899 * Record an activity when a payment is received.
901 * @todo this is intended to be moved to payment BAO class as a protected function
902 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
903 * merit it's own function as it makes the code less rather than more readable.
905 * @param int $contributionId
906 * @param int $participantId
907 * @param string $totalAmount
908 * @param string $currency
909 * @param string $trxnDate
911 * @throws \CRM_Core_Exception
912 * @throws \CiviCRM_API3_Exception
914 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
915 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
917 if ($participantId) {
918 $inputParams['id'] = $participantId;
921 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
922 $entityObj = $entityObj[$participantId];
923 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
926 $entityObj = new CRM_Contribute_BAO_Contribution();
927 $entityObj->id
= $contributionId;
928 $entityObj->find(TRUE);
929 $title = ts('Contribution');
931 // @todo per block above this is not a logical splitting off of functionality.
932 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
936 * Get the value for the To Financial Account.
938 * @param $contribution
943 public static function getToFinancialAccount($contribution, $params) {
944 if (!empty($params['payment_processor_id'])) {
945 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
947 if (!empty($params['payment_instrument_id'])) {
948 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
951 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
952 $queryParams = [1 => [$relationTypeId, 'Integer']];
953 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
958 * Get memberships related to the contribution.
960 * @param int $contributionID
964 protected static function getRelatedMemberships($contributionID) {
965 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
966 'return' => 'membership_id',
967 'contribution_id' => (int) $contributionID,
970 foreach ($membershipPayments as $membershipPayment) {
971 $membershipIDs[] = $membershipPayment['membership_id'];
973 if (empty($membershipIDs)) {
976 // We could combine this with the MembershipPayment.get - we'd
977 // need to re-wrangle the params (here or in the calling function)
978 // as they would then me membership.contact_id, membership.is_test etc
979 return civicrm_api3('Membership', 'get', [
980 'id' => ['IN' => $membershipIDs],
981 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
986 * Cancel contribution.
988 * This function should only be called from transitioncomponents - it is an interim step in refactoring.
990 * @param $processContributionObject
991 * @param $memberships
992 * @param $contributionId
993 * @param $membershipStatuses
994 * @param $updateResult
995 * @param $participant
997 * @param $pledgePayment
999 * @param $pledgePaymentIDs
1000 * @param $contributionStatusId
1004 protected static function cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId) {
1005 // @fixme https://lab.civicrm.org/dev/core/issues/927 Cancelling membership etc is not desirable for all use-cases and we should be able to disable it
1006 $processContribution = FALSE;
1007 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1008 if (is_array($memberships)) {
1009 foreach ($memberships as $membership) {
1011 //Update Membership status if there is no other completed contribution associated with the membership.
1012 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
1013 foreach ($relatedContributions as $contriId) {
1014 if ($contriId == $contributionId) {
1017 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
1018 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
1022 if ($membership && $update) {
1023 $newStatus = array_search('Cancelled', $membershipStatuses);
1026 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1028 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1029 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1030 'target_contact_id' => $membership->contact_id
,
1031 'source_record_id' => $membership->id
,
1032 'activity_type_id' => 'Change Membership Status',
1033 'status_id' => 'Completed',
1034 'priority_id' => 'Normal',
1035 'activity_date_time' => 'now',
1038 $membership->status_id
= $newStatus;
1039 $membership->is_override
= TRUE;
1040 $membership->status_override_end_date
= 'null';
1041 $membership->save();
1042 civicrm_api3('activity', 'create', $activityParam);
1044 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1045 if ($processContributionObject) {
1046 $processContribution = TRUE;
1053 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1054 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1056 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1057 if ($processContributionObject) {
1058 $processContribution = TRUE;
1062 if ($pledgePayment) {
1063 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1065 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1066 if ($processContributionObject) {
1067 $processContribution = TRUE;
1070 return [$updateResult, $processContribution];
1074 * Do any accounting updates required as a result of a contribution status change.
1076 * Currently we have a bit of a roundabout where adding a payment results in this being called &
1077 * this may attempt to add a payment. We need to resolve that....
1079 * The 'right' way to add payments or refunds is through the Payment.create api. That api
1080 * then updates the contribution but this process should not also record another financial trxn.
1081 * Currently we have weak detection fot that scenario & where it is detected the first returned
1082 * value is FALSE - meaning 'do not continue'.
1084 * We should also look at the fact that the calling function - updateFinancialAccounts
1085 * bunches together some disparate processes rather than having separate appropriate
1088 * @param array $params
1091 * Return indicates whether the updateFinancialAccounts function should continue.
1093 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1094 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1095 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1097 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
1098 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
1099 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1100 // why it is here or where it is handled instead.
1101 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1102 && $currentContributionStatus == 'Partially paid'))
1107 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1108 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1109 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1111 elseif (($previousContributionStatus == 'Pending'
1112 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
1114 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1115 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1117 if ($currentContributionStatus == 'Cancelled') {
1118 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1119 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1120 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1123 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1124 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1128 if (($previousContributionStatus == 'Pending'
1129 ||
$previousContributionStatus == 'In Progress')
1130 && ($currentContributionStatus == 'Completed')
1132 if (empty($params['line_item'])) {
1134 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1135 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
1136 // & this can be removed
1139 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1140 // This is an update so original currency if none passed in.
1141 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1143 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1144 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1145 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1146 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1148 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1151 'entity_table' => 'civicrm_financial_item',
1153 foreach ($params['line_item'] as $fieldId => $fields) {
1154 foreach ($fields as $fieldValueId => $lineItemDetails) {
1155 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1157 1 => [$lineItemDetails['id'], 'Integer'],
1159 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1160 while ($financialItem->fetch()) {
1161 $entityParams['entity_id'] = $financialItem->id
;
1162 $entityParams['amount'] = $financialItem->amount
;
1163 foreach (self
::$_trxnIDs as $tID) {
1164 $entityParams['financial_trxn_id'] = $tID;
1165 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1176 * It is possible to override the membership id that is updated from the payment processor.
1178 * Historically Paypal does this & it still does if it determines data is messed up - see
1179 * https://lab.civicrm.org/dev/membership/issues/13
1181 * Read the comment block on repeattransaction for more information
1182 * about how things should work.
1184 * @param int $contributionID
1185 * @param array $input
1187 * @throws \CiviCRM_API3_Exception
1189 protected static function handleMembershipIDOverride($contributionID, $input) {
1190 if (!empty($input['membership_id'])) {
1191 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1192 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1197 * Update all financial items related to the line item tto have a status of paid.
1199 * @param int $lineItemID
1201 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1204 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1207 2 => [$lineItemID, 'Integer'],
1209 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1210 CRM_Core_DAO
::executeQuery($query, $fparams);
1214 * Create the financial items for the line.
1216 * @param array $params
1217 * @param string $context
1218 * @param array $fields
1219 * @param array $previousLineItems
1220 * @param array $inputParams
1221 * @param bool $isARefund
1222 * @param array $trxnIds
1223 * @param int $fieldId
1227 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1228 foreach ($fields as $fieldValueId => $lineItemDetails) {
1229 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1230 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1231 if ($params['contribution']->receive_date
) {
1232 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1235 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1237 $currency = $params['prevContribution']->currency
;
1238 if ($params['contribution']->currency
) {
1239 $currency = $params['contribution']->currency
;
1241 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1243 'transaction_date' => $receiveDate,
1244 'contact_id' => $params['prevContribution']->contact_id
,
1245 'currency' => $currency,
1246 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1247 'description' => CRM_Utils_Array
::value('description', $prevFinancialItem),
1248 'status_id' => $prevFinancialItem['status_id'],
1249 'financial_account_id' => $financialAccount,
1250 'entity_table' => 'civicrm_line_item',
1251 'entity_id' => $lineItemDetails['id'],
1253 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1254 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1255 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1257 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1258 $taxAmount = (float) $lineItemDetails['tax_amount'];
1259 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1260 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1261 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1263 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1264 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1266 if ($taxAmount != 0) {
1267 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1268 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1269 if ($lineItemDetails['financial_type_id']) {
1270 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1272 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1280 * Does this contributtion status update represent a refund.
1282 * @param int $previousContributionStatusID
1283 * @param int $currentContributionStatusID
1287 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1288 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1291 return self
::isContributionStatusNegative($currentContributionStatusID);
1297 public function addSelectWhereClause() {
1298 $whereClauses = parent
::addSelectWhereClause();
1299 if ($whereClauses !== []) {
1300 // In this case permisssions have been applied & we assume the
1301 // financialaclreport is applying these
1302 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1303 return $whereClauses;
1306 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1307 return $whereClauses;
1309 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1310 if (empty($types)) {
1311 $whereClauses['financial_type_id'] = 'IN (0)';
1314 $whereClauses['financial_type_id'] = [
1315 'IN (' . implode(',', array_keys($types)) . ')',
1318 return $whereClauses;
1322 * @param null $status
1323 * @param null $startDate
1324 * @param null $endDate
1326 * @return array|null
1328 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1332 $where[] = 'contribution_status_id = 1';
1336 $where[] = 'contribution_status_id = 3';
1341 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1344 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1346 $financialTypeACLJoin = '';
1347 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1348 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1349 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1350 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1351 if ($financialTypes) {
1352 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1353 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1356 $where[] = "c.financial_type_id IN (0)";
1360 $whereCond = implode(' AND ', $where);
1363 SELECT sum( total_amount ) as total_amount,
1364 count( c.id ) as total_count,
1366 FROM civicrm_contribution c
1367 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1368 $financialTypeACLJoin
1370 AND ( is_test = 0 OR is_test IS NULL )
1371 AND contact.is_deleted = 0
1375 $dao = CRM_Core_DAO
::executeQuery($query);
1378 while ($dao->fetch()) {
1379 $count +
= $dao->total_count
;
1380 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1384 'amount' => implode(', ', $amount),
1392 * Delete the indirect records associated with this contribution first.
1396 * @return mixed|null
1397 * $results no of deleted Contribution on success, false otherwise
1399 public static function deleteContribution($id) {
1400 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
1402 $transaction = new CRM_Core_Transaction();
1405 //delete activity record
1407 'source_record_id' => $id,
1408 // activity type id for contribution
1409 'activity_type_id' => 6,
1412 CRM_Activity_BAO_Activity
::deleteActivity($params);
1414 //delete billing address if exists for this contribution.
1415 self
::deleteAddress($id);
1417 //update pledge and pledge payment, CRM-3961
1418 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1420 // remove entry from civicrm_price_set_entity, CRM-5095
1421 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1422 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1424 // cleanup line items.
1425 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1427 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1428 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1430 if ($participantId) {
1431 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1434 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1438 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1439 $noteId = key($note);
1441 CRM_Core_BAO_Note
::del($noteId, FALSE);
1444 $dao = new CRM_Contribute_DAO_Contribution();
1447 $results = $dao->delete();
1449 $transaction->commit();
1451 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1453 // delete the recently created Contribution
1454 $contributionRecent = [
1456 'type' => 'Contribution',
1458 CRM_Utils_Recent
::del($contributionRecent);
1464 * React to a financial transaction (payment) failure.
1466 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1467 * payments is important for forensic and outreach reasons.
1469 * @param int $contributionID
1470 * @param int $contactID
1471 * @param string $message
1473 * @throws \CiviCRM_API3_Exception
1475 public static function failPayment($contributionID, $contactID, $message) {
1476 civicrm_api3('activity', 'create', [
1477 'activity_type_id' => 'Failed Payment',
1478 'details' => $message,
1479 'subject' => ts('Payment failed at payment processor'),
1480 'source_record_id' => $contributionID,
1481 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1484 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1485 civicrm_api3('contribution', 'create', [
1486 'id' => $contributionID,
1487 'contribution_status_id' => 'Failed',
1492 * Check if there is a contribution with the same trxn_id or invoice_id.
1494 * @param array $input
1495 * An assoc array of name/value pairs.
1496 * @param array $duplicates
1497 * (reference) store ids of duplicate contribs.
1501 * true if duplicate, false otherwise
1503 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1505 $id = CRM_Utils_Array
::value('id', $input);
1507 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1508 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1514 $clause[] = "trxn_id = %1";
1515 $input[1] = [$trxn_id, 'String'];
1519 $clause[] = "invoice_id = %2";
1520 $input[2] = [$invoice_id, 'String'];
1523 if (empty($clause)) {
1527 $clause = implode(' OR ', $clause);
1529 $clause = "( $clause ) AND id != %3";
1530 $input[3] = [$id, 'Integer'];
1533 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1534 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1536 while ($dao->fetch()) {
1537 $duplicates[] = $dao->id
;
1544 * Takes an associative array and creates a contribution_product object.
1546 * the function extract all the params it needs to initialize the create a
1547 * contribution_product object. the params array could contain additional unused name/value
1550 * @param array $params
1551 * (reference) an assoc array of name/value pairs.
1553 * @return CRM_Contribute_DAO_ContributionProduct
1555 public static function addPremium(&$params) {
1556 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1557 $contributionProduct->copyValues($params);
1558 return $contributionProduct->save();
1562 * Get list of contribution fields for profile.
1563 * For now we only allow custom contribution fields to be in
1566 * @param bool $addExtraFields
1567 * True if special fields needs to be added.
1570 * the list of contribution fields
1572 public static function getContributionFields($addExtraFields = TRUE) {
1573 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1574 // @todo remove this - this line was added because payment_instrument_id was not
1575 // set to exportable - but now it is.
1576 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1578 if ($addExtraFields) {
1579 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1582 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1584 foreach ($contributionFields as $key => $var) {
1585 if ($key == 'contribution_contact_id') {
1588 elseif ($key == 'contribution_campaign_id') {
1589 $var['title'] = ts('Campaign');
1591 $fields[$key] = $var;
1594 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1599 * Add extra fields specific to contribution.
1601 public static function getSpecialContributionFields() {
1603 'contribution_soft_credit_name' => [
1604 'name' => 'contribution_soft_credit_name',
1605 'title' => ts('Soft Credit Name'),
1606 'headerPattern' => '/^soft_credit_name$/i',
1607 'where' => 'civicrm_contact_d.display_name',
1609 'contribution_soft_credit_email' => [
1610 'name' => 'contribution_soft_credit_email',
1611 'title' => ts('Soft Credit Email'),
1612 'headerPattern' => '/^soft_credit_email$/i',
1613 'where' => 'soft_email.email',
1615 'contribution_soft_credit_phone' => [
1616 'name' => 'contribution_soft_credit_phone',
1617 'title' => ts('Soft Credit Phone'),
1618 'headerPattern' => '/^soft_credit_phone$/i',
1619 'where' => 'soft_phone.phone',
1621 'contribution_soft_credit_contact_id' => [
1622 'name' => 'contribution_soft_credit_contact_id',
1623 'title' => ts('Soft Credit Contact ID'),
1624 'headerPattern' => '/^soft_credit_contact_id$/i',
1625 'where' => 'civicrm_contribution_soft.contact_id',
1627 'contribution_pcp_title' => [
1628 'name' => 'contribution_pcp_title',
1629 'title' => ts('Personal Campaign Page Title'),
1630 'headerPattern' => '/^contribution_pcp_title$/i',
1631 'where' => 'contribution_pcp.title',
1635 return $extraFields;
1639 * @param int $pageID
1643 public static function getCurrentandGoalAmount($pageID) {
1645 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1646 FROM civicrm_contribution_page p,
1647 civicrm_contribution c
1648 WHERE p.id = c.contribution_page_id
1650 AND c.cancel_date is null
1654 $config = CRM_Core_Config
::singleton();
1655 $params = [1 => [$pageID, 'Integer']];
1656 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1658 if ($dao->fetch()) {
1659 return [$dao->goal
, $dao->total
];
1662 return [NULL, NULL];
1667 * Get list of contributions which credit the passed in contact ID.
1669 * The returned array provides details about the original contribution & donor.
1671 * @param int $honorId
1672 * In Honor of Contact ID.
1675 * list of contribution fields
1676 * @todo - this is a confusing function called from one place. It has a test. It would be
1677 * nice to deprecate it.
1680 public static function getHonorContacts($honorId) {
1682 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1683 $honorDAO->contact_id
= $honorId;
1686 $type = CRM_Contribute_PseudoConstant
::financialType();
1688 while ($honorDAO->fetch()) {
1689 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1690 $contributionDAO->id
= $honorDAO->contribution_id
;
1692 if ($contributionDAO->find(TRUE)) {
1693 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1694 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1695 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1696 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1697 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1698 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1699 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1700 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1701 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1709 * Get the sort name of a contact for a particular contribution.
1712 * Id of the contribution.
1714 * @return null|string
1715 * sort name of the contact if found
1717 public static function sortName($id) {
1718 $id = CRM_Utils_Type
::escape($id, 'Integer');
1721 SELECT civicrm_contact.sort_name
1722 FROM civicrm_contribution, civicrm_contact
1723 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1724 AND civicrm_contribution.id = {$id}
1726 return CRM_Core_DAO
::singleValueQuery($query);
1730 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1732 * @param int|array $contactIDs
1736 public static function annual($contactIDs) {
1737 if (!is_array($contactIDs)) {
1738 // In practice I can't fine any evidence that this function is ever called with
1739 // anything other than a single contact id, but left like this due to .... fear.
1740 $contactIDs = explode(',', $contactIDs);
1743 $query = self
::getAnnualQuery($contactIDs);
1744 $dao = CRM_Core_DAO
::executeQuery($query);
1746 $amount = $average = [];
1747 while ($dao->fetch()) {
1748 if ($dao->count
> 0 && $dao->amount
> 0) {
1749 $count +
= $dao->count
;
1750 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1751 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1757 implode(', ', $amount),
1758 implode(', ', $average),
1765 * Check if there is a contribution with the params passed in.
1767 * Used for trxn_id,invoice_id and contribution_id
1769 * @param array $params
1770 * An assoc array of name/value pairs.
1773 * contribution id if success else NULL
1775 public static function checkDuplicateIds($params) {
1776 $dao = new CRM_Contribute_DAO_Contribution();
1780 foreach ($params as $k => $v) {
1782 $clause[] = "$k = '$v'";
1785 $clause = implode(' AND ', $clause);
1786 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1787 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1789 while ($dao->fetch()) {
1797 * Get the contribution details for component export.
1799 * @param int $exportMode
1801 * @param array $componentIds
1807 public static function getContributionDetails($exportMode, $componentIds) {
1808 $paymentDetails = [];
1809 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1811 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1812 $componentSelect = " civicrm_participant_payment.participant_id id";
1813 $additionalClause = "
1814 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1815 AND civicrm_participant_payment.participant_id {$componentClause} )
1818 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1819 $componentSelect = " civicrm_membership_payment.membership_id id";
1820 $additionalClause = "
1821 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1822 AND civicrm_membership_payment.membership_id {$componentClause} )
1825 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1826 $componentSelect = " civicrm_pledge_payment.id id";
1827 $additionalClause = "
1828 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1829 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1833 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1834 trxn_id, {$componentSelect}
1835 FROM civicrm_contribution
1836 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1837 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1838 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1839 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1840 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1841 AND option_group_contribution_status.id = contribution_status.option_group_id )
1845 $dao = CRM_Core_DAO
::executeQuery($query);
1847 while ($dao->fetch()) {
1848 $paymentDetails[$dao->id
] = [
1849 'total_amount' => $dao->total_amount
,
1850 'contribution_status' => $dao->status
,
1851 'receive_date' => $dao->receive_date
,
1852 'pay_instru' => $dao->payment_instrument
,
1853 'trxn_id' => $dao->trxn_id
,
1857 return $paymentDetails;
1861 * Create address associated with contribution record.
1863 * As long as there is one or more billing field in the parameters we will create the address.
1865 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1868 * @param array $params
1869 * @param int $billingLocationTypeID
1874 public static function createAddress($params, $billingLocationTypeID) {
1875 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1876 if ($hasBillingField) {
1877 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1878 return $address->id
;
1885 * Delete billing address record related contribution.
1887 * @param int $contributionId
1888 * @param int $contactId
1890 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1892 $contactJoin = NULL;
1894 if ($contributionId) {
1895 $clauses[] = "cc.id = {$contributionId}";
1899 $clauses[] = "cco.id = {$contactId}";
1900 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1903 if (empty($clauses)) {
1904 CRM_Core_Error
::fatal();
1907 $condition = implode(' OR ', $clauses);
1911 FROM civicrm_address ca
1912 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1916 $dao = CRM_Core_DAO
::executeQuery($query);
1918 while ($dao->fetch()) {
1919 $params = ['id' => $dao->id
];
1920 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1925 * This function check online pending contribution associated w/
1926 * Online Event Registration or Online Membership signup.
1928 * @param int $componentId
1929 * Participant/membership id.
1930 * @param string $componentName
1934 * pending contribution id.
1936 public static function checkOnlinePendingContribution($componentId, $componentName) {
1937 $contributionId = NULL;
1938 if (!$componentId ||
1939 !in_array($componentName, ['Event', 'Membership'])
1941 return $contributionId;
1944 if ($componentName == 'Event') {
1945 $idName = 'participant_id';
1946 $componentTable = 'civicrm_participant';
1947 $paymentTable = 'civicrm_participant_payment';
1948 $source = ts('Online Event Registration');
1951 if ($componentName == 'Membership') {
1952 $idName = 'membership_id';
1953 $componentTable = 'civicrm_membership';
1954 $paymentTable = 'civicrm_membership_payment';
1955 $source = ts('Online Contribution');
1958 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1961 SELECT component.id as {$idName},
1962 componentPayment.contribution_id as contribution_id,
1963 contribution.source source,
1964 contribution.contribution_status_id as contribution_status_id,
1965 contribution.is_pay_later as is_pay_later
1966 FROM $componentTable component
1967 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1968 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1969 WHERE component.id = {$componentId}";
1971 $dao = CRM_Core_DAO
::executeQuery($query);
1973 while ($dao->fetch()) {
1974 if ($dao->contribution_id
&&
1975 $dao->is_pay_later
&&
1976 $dao->contribution_status_id
== $pendingStatusId &&
1977 strpos($dao->source
, $source) !== FALSE
1979 $contributionId = $dao->contribution_id
;
1983 return $contributionId;
1987 * Update contribution as well as related objects.
1989 * This function by-passes hooks - to address this - don't use this function.
1991 * @param array $params
1992 * @param bool $processContributionObject
1996 * @throws CRM_Core_Exception
1997 * @throws \CiviCRM_API3_Exception
2000 * Use api contribute.completetransaction
2001 * For failures use failPayment (preferably exposing by api in the process).
2004 public static function transitionComponents($params, $processContributionObject = FALSE) {
2005 // get minimum required values.
2006 $contactId = CRM_Utils_Array
::value('contact_id', $params);
2007 $componentId = CRM_Utils_Array
::value('component_id', $params);
2008 $componentName = CRM_Utils_Array
::value('componentName', $params);
2009 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
2010 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
2012 // if we already processed contribution object pass previous status id.
2013 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
2017 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2019 // we process only ( Completed, Cancelled, or Failed ) contributions.
2020 if (!$contributionId ||
2021 !in_array($contributionStatusId, [
2022 array_search('Completed', $contributionStatuses),
2023 array_search('Cancelled', $contributionStatuses),
2024 array_search('Failed', $contributionStatuses),
2027 return $updateResult;
2030 if (!$componentName ||
!$componentId) {
2031 // get the related component details.
2032 $componentDetails = self
::getComponentDetails($contributionId);
2035 $componentDetails['contact_id'] = $contactId;
2036 $componentDetails['component'] = $componentName;
2038 if ($componentName == 'event') {
2039 $componentDetails['participant'] = $componentId;
2042 $componentDetails['membership'] = $componentId;
2046 if (!empty($componentDetails['contact_id'])) {
2047 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2053 // do check for required ids.
2054 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2055 return $updateResult;
2058 //now we are ready w/ required ids, start processing.
2060 $baseIPN = new CRM_Core_Payment_BaseIPN();
2062 $input = $ids = $objects = [];
2064 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
2065 $ids['contribution'] = $contributionId;
2066 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
2067 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
2068 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
2069 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
2070 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
2071 $ids['contributionRecur'] = NULL;
2072 $ids['contributionPage'] = NULL;
2074 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
2075 CRM_Core_Error
::fatal();
2078 $memberships = &$objects['membership'];
2079 $participant = &$objects['participant'];
2080 $pledgePayment = &$objects['pledge_payment'];
2081 $contribution = &$objects['contribution'];
2082 $pledgeID = $oldStatus = NULL;
2083 $pledgePaymentIDs = [];
2084 if ($pledgePayment) {
2085 foreach ($pledgePayment as $key => $object) {
2086 $pledgePaymentIDs[] = $object->id
;
2088 $pledgeID = $pledgePayment[0]->pledge_id
;
2091 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2094 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2095 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2100 // we might want to process contribution object.
2101 $processContribution = FALSE;
2102 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
2103 // Call interim cancel function - with a goal to cleaning up the signature on it and switching to a tested api Contribution.cancel function.
2104 list($updateResult, $processContribution) = self
::cancel($processContributionObject, $memberships, $contributionId, $membershipStatuses, $updateResult, $participant, $oldStatus, $pledgePayment, $pledgeID, $pledgePaymentIDs, $contributionStatusId);
2106 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
2107 if (is_array($memberships)) {
2108 foreach ($memberships as $membership) {
2110 //Update Membership status if there is no other completed contribution associated with the membership.
2111 $relatedContributions = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
, TRUE);
2112 foreach ($relatedContributions as $contriId) {
2113 if ($contriId == $contributionId) {
2116 $statusId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_BAO_Contribution', $contriId, 'contribution_status_id');
2117 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $statusId) === 'Completed') {
2121 if ($membership && $update) {
2122 $membership->status_id
= array_search('Expired', $membershipStatuses);
2123 $membership->is_override
= TRUE;
2124 $membership->status_override_end_date
= 'null';
2125 $membership->save();
2127 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2128 if ($processContributionObject) {
2129 $processContribution = TRUE;
2135 $updatedStatusId = array_search('Cancelled', $participantStatuses);
2136 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2138 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2139 if ($processContributionObject) {
2140 $processContribution = TRUE;
2144 if ($pledgePayment) {
2145 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2147 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2148 if ($processContributionObject) {
2149 $processContribution = TRUE;
2153 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2155 // only pending contribution related object processed.
2156 if ($previousContriStatusId &&
2157 !in_array($contributionStatuses[$previousContriStatusId], [
2162 // this is case when we already processed contribution object.
2163 return $updateResult;
2165 elseif (!$previousContriStatusId &&
2166 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2171 // this is case when we are going to process contribution object later.
2172 return $updateResult;
2175 if (is_array($memberships)) {
2176 foreach ($memberships as $membership) {
2181 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2182 $membership->membership_type_id
,
2183 $membership->is_test
, $membership->id
2186 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2187 // this picks up membership type changes during renewals
2189 SELECT membership_type_id
2190 FROM civicrm_membership_log
2191 WHERE membership_id=$membership->id
2194 $dao = new CRM_Core_DAO();
2196 if ($dao->fetch()) {
2197 if (!empty($dao->membership_type_id
)) {
2198 $membership->membership_type_id
= $dao->membership_type_id
;
2199 $membership->save();
2202 // else fall back to using current membership type
2203 // Figure out number of terms
2205 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2206 foreach ($lineitems as $lineitem) {
2207 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
2208 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
2210 // in case membership_num_terms comes through as null or zero
2211 $numterms = $numterms >= 1 ?
$numterms : 1;
2216 // CRM-15735-to update the membership status as per the contribution receive date
2218 $oldStatus = $membership->status_id
;
2219 if (!empty($params['receive_date'])) {
2220 $joinDate = $params['receive_date'];
2221 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2222 $membership->end_date
,
2223 $membership->join_date
,
2224 $params['receive_date'],
2226 $membership->membership_type_id
,
2229 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2230 $membership->save();
2233 if ($currentMembership) {
2234 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2235 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2236 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2239 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2242 //get the status for membership.
2243 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2245 $dates['join_date'],
2248 $membership->membership_type_id
,
2252 $formattedParams = [
2253 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2254 array_search('Current', $membershipStatuses)
2256 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2257 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2258 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2261 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2263 $membership->copyValues($formattedParams);
2264 $membership->save();
2266 //updating the membership log
2267 $membershipLog = [];
2268 $membershipLog = $formattedParams;
2269 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
2270 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2272 $membershipLog['start_date'] = $logStartDate;
2273 $membershipLog['membership_id'] = $membership->id
;
2274 $membershipLog['modified_id'] = $membership->contact_id
;
2275 $membershipLog['modified_date'] = date('Ymd');
2276 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2278 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2280 //update related Memberships.
2281 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2283 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2284 $scheduledActivityID = CRM_Utils_Array
::value('id',
2285 civicrm_api3('Activity', 'Get',
2287 'source_record_id' => $membership->id
,
2288 'activity_type_id' => $activityType,
2289 'status_id' => 'Scheduled',
2292 'sort' => 'id DESC',
2297 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2298 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2299 if ($scheduledActivityID) {
2300 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2305 // track membership status change if any
2306 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2307 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2308 CRM_Activity_BAO_Activity
::addActivity($membership,
2309 'Change Membership Status',
2312 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2313 'source_contact_id' => $membershipLog['modified_id'],
2314 'priority_id' => 'Normal',
2319 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
2320 if ($processContributionObject) {
2321 $processContribution = TRUE;
2324 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2330 $updatedStatusId = array_search('Registered', $participantStatuses);
2331 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2333 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2334 if ($processContributionObject) {
2335 $processContribution = TRUE;
2339 if ($pledgePayment) {
2340 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2342 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2343 if ($processContributionObject) {
2344 $processContribution = TRUE;
2349 // process contribution object.
2350 if ($processContribution) {
2351 $contributionParams = [];
2358 'payment_instrument_id',
2361 'financial_type_id',
2362 'contribution_status_id',
2363 'non_deductible_amount',
2367 foreach ($fields as $field) {
2368 if (empty($params[$field])) {
2371 $contributionParams[$field] = $params[$field];
2374 $contributionParams['id'] = $contributionId;
2375 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2378 return $updateResult;
2382 * Returns all contribution related object ids.
2384 * @param $contributionId
2388 public static function getComponentDetails($contributionId) {
2389 $componentDetails = $pledgePayment = [];
2390 if (!$contributionId) {
2391 return $componentDetails;
2395 SELECT c.id as contribution_id,
2396 c.contact_id as contact_id,
2397 c.contribution_recur_id,
2398 mp.membership_id as membership_id,
2399 m.membership_type_id as membership_type_id,
2400 pp.participant_id as participant_id,
2401 p.event_id as event_id,
2402 pgp.id as pledge_payment_id
2403 FROM civicrm_contribution c
2404 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2405 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2406 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2407 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2408 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2409 WHERE c.id = $contributionId";
2411 $dao = CRM_Core_DAO
::executeQuery($query);
2412 $componentDetails = [];
2414 while ($dao->fetch()) {
2415 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2416 $componentDetails['contact_id'] = $dao->contact_id
;
2417 if ($dao->event_id
) {
2418 $componentDetails['event'] = $dao->event_id
;
2420 if ($dao->participant_id
) {
2421 $componentDetails['participant'] = $dao->participant_id
;
2423 if ($dao->membership_id
) {
2424 if (!isset($componentDetails['membership'])) {
2425 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2427 $componentDetails['membership'][] = $dao->membership_id
;
2428 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2430 if ($dao->pledge_payment_id
) {
2431 $pledgePayment[] = $dao->pledge_payment_id
;
2433 if ($dao->contribution_recur_id
) {
2434 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2438 if ($pledgePayment) {
2439 $componentDetails['pledge_payment'] = $pledgePayment;
2442 return $componentDetails;
2446 * @param int $contactId
2447 * @param bool $includeSoftCredit
2449 * @return null|string
2451 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2455 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2456 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2457 $liWhere = " AND i.financial_type_id IN (0)";
2458 if (!empty($financialTypes)) {
2459 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2460 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2462 $contactContributionsSQL = "
2463 SELECT contribution.id AS id
2464 FROM civicrm_contribution contribution
2465 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2466 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2470 $contactSoftCreditContributionsSQL = "
2471 SELECT contribution.id
2472 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2473 ON ( contribution.id = softContribution.contribution_id )
2474 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2475 $query = "SELECT count( x.id ) count FROM ( ";
2476 $query .= $contactContributionsSQL;
2478 if ($includeSoftCredit) {
2479 $query .= " UNION ";
2480 $query .= $contactSoftCreditContributionsSQL;
2485 return CRM_Core_DAO
::singleValueQuery($query);
2489 * Repeat a transaction as part of a recurring series.
2492 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2493 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2494 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2495 * and associated entities.
2496 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2497 * which updates the various entities and sends appropriate emails.
2499 * Gaps in the above (@todo)
2500 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2501 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2502 * 3) Repeat transaction duplicates rather than calls Order.create
2503 * 4) Use of payment.create still limited - completetransaction is more common.
2504 * 5) the template transaction is tricky - historically we used the first contribution
2505 * linked to a recurring contribution. More recently that was changed to be the most recent.
2506 * Ideally it would be an actual template - not a contribution used as a template which
2507 * would give more appropriate flexibility. Note line_items have an entity so that table
2508 * could be used for the line item template - the difficulty is the custom fields...
2509 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2510 * to load the membership(s) referred to via line items in the template transactions. Any other
2511 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2512 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2513 * - membership_payment record
2514 * - civicrm_membership.contribution_recur_id
2516 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2517 * of historical processors since this has been handled 'forever' - specifically for paypal.
2518 * albeit by an even nastier mechanism than the current input override.
2519 * The count is out on how correct related entities wind up in this case.
2521 * @param CRM_Contribute_BAO_Contribution $contribution
2522 * @param array $input
2523 * @param array $contributionParams
2524 * @param int $paymentProcessorID
2527 * @throws CiviCRM_API3_Exception
2529 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2530 if (!empty($contribution->id
)) {
2533 if (empty($contribution->id
)) {
2534 // Unclear why this would only be set for repeats.
2535 if (!empty($input['amount'])) {
2536 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2539 if (!empty($contributionParams['contribution_recur_id'])) {
2540 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2541 'id' => $contributionParams['contribution_recur_id'],
2543 if (!empty($recurringContribution['campaign_id'])) {
2544 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2545 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2547 if (!empty($recurringContribution['financial_type_id'])) {
2548 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2549 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2552 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2553 $contributionParams['contribution_recur_id'],
2554 array_intersect_key($contributionParams, [
2555 'total_amount' => TRUE,
2556 'financial_type_id' => TRUE,
2559 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2561 $contributionParams['status_id'] = 'Pending';
2562 if (isset($contributionParams['financial_type_id'])) {
2563 // Give precedence to passed in type.
2564 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2567 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2569 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2570 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2572 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2573 //do not create CC or BCC emails or profile notifications.
2574 //The if is just to be safe. Not sure if we can ever arrive with this unset
2575 // but per CRM-19478 it seems it can be 'null'
2576 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2577 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2579 if (!empty($contribution->tax_amount
)) {
2580 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2583 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2584 $contribution->id
= $createContribution['id'];
2585 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2586 self
::handleMembershipIDOverride($contribution->id
, $input);
2592 * Get individual id for onbehalf contribution.
2594 * @param int $contributionId
2596 * @param int $contributorId
2600 * containing organization id and individual id
2602 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2606 if (!$contributionId) {
2610 // fetch contributor id if null
2611 if (!$contributorId) {
2612 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2613 $contributionId, 'contact_id'
2617 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2618 $activityTypeId = array_search('Contribution', $activityTypeIds);
2620 if ($activityTypeId && $contributorId) {
2622 SELECT civicrm_activity_contact.contact_id
2623 FROM civicrm_activity_contact
2624 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2625 WHERE civicrm_activity.activity_type_id = %1
2626 AND civicrm_activity.source_record_id = %2
2627 AND civicrm_activity_contact.record_type_id = %3
2630 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2631 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2634 1 => [$activityTypeId, 'Integer'],
2635 2 => [$contributionId, 'Integer'],
2636 3 => [$sourceID, 'Integer'],
2639 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2641 // for on behalf contribution source is individual and contributor is organization
2642 if ($sourceContactId && $sourceContactId != $contributorId) {
2643 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2644 // get rel type id for employee of relation
2645 foreach ($relationshipTypeIds as $id => $typeVals) {
2646 if ($typeVals['name_a_b'] == 'Employee of') {
2647 $relationshipTypeId = $id;
2652 $rel = new CRM_Contact_DAO_Relationship();
2653 $rel->relationship_type_id
= $relationshipTypeId;
2654 $rel->contact_id_a
= $sourceContactId;
2655 $rel->contact_id_b
= $contributorId;
2656 if ($rel->find(TRUE)) {
2657 $ids['individual_id'] = $rel->contact_id_a
;
2658 $ids['organization_id'] = $rel->contact_id_b
;
2669 public static function getContributionDates() {
2670 $config = CRM_Core_Config
::singleton();
2671 $currentMonth = date('m');
2672 $currentDay = date('d');
2673 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2674 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2675 (int ) $config->fiscalYearStart
['d'] > $currentDay
2678 $year = date('Y') - 1;
2683 $year = ['Y' => $year];
2684 $yearDate = $config->fiscalYearStart
;
2685 $yearDate = array_merge($year, $yearDate);
2686 $yearDate = CRM_Utils_Date
::format($yearDate);
2688 $monthDate = date('Ym') . '01';
2694 'yearDate' => $yearDate,
2695 'monthDate' => $monthDate,
2700 * Load objects relations to contribution object.
2701 * Objects are stored in the $_relatedObjects property
2702 * In the first instance we are just moving functionality from BASEIpn -
2704 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2706 * Note that the unit test for the BaseIPN class tests this function
2708 * @param array $input
2709 * Input as delivered from Payment Processor.
2711 * Ids as Loaded by Payment Processor.
2712 * @param bool $loadAll
2713 * Load all related objects - even where id not passed in? (allows API to call this).
2718 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2719 // @todo deprecate this function - the steps should be
2720 // 1) add additional functions like 'getRelatedMemberships'
2721 // 2) switch all calls that refer to ->_relatedObjects to
2722 // using the helper functions
2723 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2724 // 4) make ->_relatedObjects protected
2725 // 5) hone up the individual functions to not use rely on this having been called
2726 // 6) deprecate like mad
2728 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2729 if (empty($ids['contact']) && isset($this->contact_id
)) {
2730 $ids['contact'] = $this->contact_id
;
2733 if (empty($this->_component
)) {
2734 if (!empty($ids['event'])) {
2735 $this->_component
= 'event';
2738 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2742 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2743 // refactoring than anything else, and has unit test coverage.
2744 if (empty($this->financial_type_id
)) {
2748 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2753 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2754 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2755 $this->contribution_page_id
,
2758 if ($paymentProcessorID) {
2759 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2763 $ids['contributionType'] = $this->financial_type_id
;
2764 $ids['financialType'] = $this->financial_type_id
;
2765 if ($this->contribution_page_id
) {
2766 $ids['contributionPage'] = $this->contribution_page_id
;
2769 $this->loadRelatedEntitiesByID($ids);
2771 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2772 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2775 if (!empty($ids['pledge_payment'])) {
2776 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2777 if (empty($paymentID)) {
2780 $payment = new CRM_Pledge_BAO_PledgePayment();
2781 $payment->id
= $paymentID;
2782 if (!$payment->find(TRUE)) {
2783 throw new Exception("Could not find pledge payment record: " . $paymentID);
2785 $this->_relatedObjects
['pledge_payment'][] = $payment;
2789 // These are probably no longer accessed from anywhere
2790 // @todo remove this line, after ensuring not used.
2791 $ids = $this->loadRelatedMembershipObjects($ids);
2793 if ($this->_component
!= 'contribute') {
2794 // we are in event mode
2795 // make sure event exists and is valid
2796 $event = new CRM_Event_BAO_Event();
2797 $event->id
= $ids['event'];
2798 if ($ids['event'] &&
2801 throw new Exception("Could not find event: " . $ids['event']);
2804 $this->_relatedObjects
['event'] = &$event;
2806 $participant = new CRM_Event_BAO_Participant();
2807 $participant->id
= $ids['participant'];
2808 if ($ids['participant'] &&
2809 !$participant->find(TRUE)
2811 throw new Exception("Could not find participant: " . $ids['participant']);
2813 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2815 $this->_relatedObjects
['participant'] = &$participant;
2817 // get the payment processor id from event - this is inaccurate see CRM-16923
2818 // in future we should look at throwing an exception here rather than an dubious guess.
2819 if (!$paymentProcessorID) {
2820 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2821 if ($paymentProcessorID) {
2822 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2827 if ($paymentProcessorID) {
2828 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2829 $this->is_test ?
'test' : 'live'
2831 $ids['paymentProcessor'] = $paymentProcessorID;
2832 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2835 // Add contribution id to $ids. CRM-20401
2836 $ids['contribution'] = $this->id
;
2841 * Create array of message information - ie. return html version, txt version, to field
2843 * @param array $input
2844 * Incoming information.
2845 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2846 * just check presence of recur object but maintaining legacy approach
2849 * IDs of related objects.
2850 * @param array $values
2851 * Any values that may have already been compiled by calling process.
2852 * This is augmented by values 'gathered' by gatherMessageValues
2853 * @param bool $returnMessageText
2854 * Distinguishes between whether to send message or return.
2855 * message text. We are working towards this function ALWAYS returning message text & calling
2856 * function doing emails / pdfs with it
2862 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2863 $this->loadRelatedObjects($input, $ids);
2865 if (empty($this->_component
)) {
2866 $this->_component
= CRM_Utils_Array
::value('component', $input);
2869 //not really sure what params might be passed in but lets merge em into values
2870 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2871 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2872 if (!empty($input['receipt_date'])) {
2873 $values['receipt_date'] = $input['receipt_date'];
2876 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2877 //what does recur 'mean here - to do with payment processor return functionality but
2878 // what is the importance
2879 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2880 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2882 $entityID = $entity = NULL;
2883 if (isset($ids['contribution'])) {
2884 $entity = 'contribution';
2885 $entityID = $ids['contribution'];
2887 if (!empty($ids['membership'])) {
2888 //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
2889 // 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
2890 // line having loaded an array
2891 $ids['membership'] = (array) $ids['membership'];
2892 $entity = 'membership';
2893 $entityID = $ids['membership'][0];
2896 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2897 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2898 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2900 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2901 //direct mode showing billing block, so use directIPN for temporary
2902 $template->assign('contributeMode', 'directIPN');
2905 // todo remove strtolower - check consistency
2906 if (strtolower($this->_component
) == 'event') {
2907 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2908 $values['event'] = [];
2910 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2912 //get location details
2914 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2915 'entity_table' => 'civicrm_event',
2917 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2920 'entity_table' => 'civicrm_event',
2921 'entity_id' => $ids['event'],
2922 'module' => 'CiviEvent',
2925 list($custom_pre_id,
2927 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2929 $values['custom_pre_id'] = $custom_pre_id;
2930 $values['custom_post_id'] = $custom_post_ids;
2931 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2932 //and cases involving status updation through ipn
2933 // whatever that means!
2934 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2935 // perhaps we should throw an e-notice if amount is set & force total_amount?
2936 if (!empty($input['amount'])) {
2937 $values['totalAmount'] = $input['amount'];
2939 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2940 if ($values['event']['is_email_confirm']) {
2941 $values['is_email_receipt'] = 1;
2944 if (!empty($ids['contribution'])) {
2945 $values['contributionId'] = $ids['contribution'];
2948 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2949 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2953 $values['contribution_id'] = $this->id
;
2954 if (!empty($ids['related_contact'])) {
2955 $values['related_contact'] = $ids['related_contact'];
2956 if (isset($ids['onbehalf_dupe_alert'])) {
2957 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2960 'contact_id' => $ids['contact'],
2961 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2962 'Home', 'id', 'name'
2965 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2966 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2969 if ($this->is_test
) {
2972 if (!empty($this->_relatedObjects
['membership'])) {
2973 foreach ($this->_relatedObjects
['membership'] as $membership) {
2974 if ($membership->id
) {
2975 $values['membership_id'] = $membership->id
;
2976 $values['isMembership'] = TRUE;
2977 $values['membership_assign'] = TRUE;
2979 // need to set the membership values here
2980 $template->assign('membership_name',
2981 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2983 $template->assign('mem_start_date', $membership->start_date
);
2984 $template->assign('mem_join_date', $membership->join_date
);
2985 $template->assign('mem_end_date', $membership->end_date
);
2986 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2987 $template->assign('mem_status', $membership_status);
2988 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2989 $values['is_pay_later'] = 1;
2991 // Pass amount to floatval as string '0.00' is considered a
2992 // valid amount and includes Fee section in the mail.
2993 if (isset($values['amount'])) {
2994 $values['amount'] = floatval($values['amount']);
2997 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2998 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2999 $template->assign('cancelSubscriptionUrl', $url);
3000 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
3001 $template->assign('updateSubscriptionBillingUrl', $url);
3002 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3003 $template->assign('updateSubscriptionUrl', $url);
3006 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3009 // otherwise if its about sending emails, continue sending without return, as we
3010 // don't want to exit the loop.
3015 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3021 * Gather values for contribution mail - this function has been created
3022 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3023 * Values related to the contribution in question are gathered
3025 * @param array $input
3026 * Input into function (probably from payment processor).
3027 * @param array $values
3029 * The set of ids related to the input.
3032 * @throws \CRM_Core_Exception
3034 public function _gatherMessageValues($input, &$values, $ids = []) {
3035 // set display address of contributor
3036 $values['billingName'] = '';
3037 if ($this->address_id
) {
3038 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
3039 $addressDetails = reset($addressDetails);
3040 $values['billingName'] = $addressDetails['name'] ??
'';
3042 // Else we assign the billing address of the contribution contact.
3044 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
3045 $addressDetails = reset($addressDetails);
3047 $values['address'] = $addressDetails['display'] ??
'';
3049 if ($this->_component
=== 'contribute') {
3050 //get soft contributions
3051 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
3052 if (!empty($softContributions)) {
3053 $values['softContributions'] = $softContributions['soft_credit'];
3055 if (isset($this->contribution_page_id
)) {
3056 // This is a call we want to use less, in favour of loading related objects.
3057 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3058 if ($this->contribution_page_id
) {
3059 // This is precautionary as there are some legacy flows, but it should really be
3061 if (!isset($this->_relatedObjects
['contributionPage'])) {
3062 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
3064 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
3067 // no contribution page -probably back office
3069 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3070 $values['title'] = 'Contribution';
3072 // set lineItem for contribution
3074 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
3075 if (!empty($lineItems)) {
3076 $firstLineItem = reset($lineItems);
3078 if (!empty($firstLineItem['price_set_id'])) {
3079 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3080 'id' => $firstLineItem['price_set_id'],
3081 'return' => 'is_quick_config, id',
3083 $values['priceSetID'] = $priceSet['id'];
3085 foreach ($lineItems as &$eachItem) {
3086 if (isset($this->_relatedObjects
['membership'])
3087 && is_array($this->_relatedObjects
['membership'])
3088 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
3089 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
3090 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
3091 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
3093 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3094 // However, that does create upgrade pain so would be better to be phased in.
3095 $values['useForMember'] = empty($priceSet['is_quick_config']);
3097 $values['lineItem'][0] = $lineItems;
3101 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3105 // if this is onbehalf of contribution then set related contact
3106 if (!empty($relatedContact['individual_id'])) {
3107 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3111 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3114 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3117 foreach ($groupTree as $key => $group) {
3118 if ($key === 'info') {
3122 foreach ($group['fields'] as $k => $customField) {
3123 $groupLabel = $group['title'];
3124 if (!empty($customField['customValue'])) {
3125 foreach ($customField['customValue'] as $customFieldValues) {
3126 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
3131 $values['customGroup'] = $customGroup;
3133 $values['is_pay_later'] = $this->is_pay_later
;
3139 * Assign message variables to template but try to break the habit.
3141 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3142 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3143 * multiple recurring payments for processors like IATS that use tokens.
3145 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3146 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3147 * Note we send directly from this function in some cases because it is only partly refactored.
3149 * Don't call this function directly as the signature will change.
3153 * @param bool $returnMessageText
3157 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3158 // @todo - this should have a better separation of concerns - ie.
3159 // gatherMessageValues should build an array of values to be assigned to the template
3160 // and this function should assign them (assigning null if not set).
3161 // the way the pcpParams & honor Params section works is a baby-step towards this.
3162 $template = CRM_Core_Smarty
::singleton();
3163 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3164 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3165 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3166 $template->assign('billingName', $values['billingName']);
3168 // For some unit tests contribution cannot contain paymentProcessor information
3169 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3170 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
3172 //assign honor information to receipt message
3173 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3176 'soft_credit_type' => NULL,
3177 'honor_block_is_active' => NULL,
3179 if (isset($softRecord['soft_credit'])) {
3180 //if id of contribution page is present
3181 if (!empty($values['id'])) {
3182 $values['honor'] = [
3183 'honor_profile_values' => [],
3184 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3185 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3188 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3189 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3192 //offline contribution
3193 $softCreditTypes = $softCredits = [];
3194 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3195 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3196 $softCredits[$key] = [
3197 'Name' => $softCredit['contact_name'],
3198 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3201 $template->assign('softCreditTypes', $softCreditTypes);
3202 $template->assign('softCredits', $softCredits);
3206 $dao = new CRM_Contribute_DAO_ContributionProduct();
3207 $dao->contribution_id
= $this->id
;
3208 if ($dao->find(TRUE)) {
3209 $premiumId = $dao->product_id
;
3210 $template->assign('option', $dao->product_option
);
3212 $productDAO = new CRM_Contribute_DAO_Product();
3213 $productDAO->id
= $premiumId;
3214 $productDAO->find(TRUE);
3215 $template->assign('selectPremium', TRUE);
3216 $template->assign('product_name', $productDAO->name
);
3217 $template->assign('price', $productDAO->price
);
3218 $template->assign('sku', $productDAO->sku
);
3220 $template->assign('title', CRM_Utils_Array
::value('title', $values));
3221 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3222 if (!$values['amount'] && isset($this->total_amount
)) {
3223 $values['amount'] = $this->total_amount
;
3228 'pcp_display_in_roll' => NULL,
3229 'pcp_roll_nickname' => NULL,
3230 'pcp_personal_note' => NULL,
3234 if (strtolower($this->_component
) == 'contribute') {
3236 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3237 $softDAO->contribution_id
= $this->id
;
3238 if ($softDAO->find(TRUE)) {
3239 $pcpParams['pcpBlock'] = TRUE;
3240 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3241 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3242 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3244 //assign the pcp page title for email subject
3245 $pcpDAO = new CRM_PCP_DAO_PCP();
3246 $pcpDAO->id
= $softDAO->pcp_id
;
3247 if ($pcpDAO->find(TRUE)) {
3248 $pcpParams['title'] = $pcpDAO->title
;
3252 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3253 $template->assign($templateKey, $templateValue);
3256 if ($this->financial_type_id
) {
3257 $values['financial_type_id'] = $this->financial_type_id
;
3260 $template->assign('trxn_id', $this->trxn_id
);
3261 $template->assign('receive_date',
3262 CRM_Utils_Date
::processDate($this->receive_date
)
3264 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3265 $template->assign('action', $this->is_test ?
1024 : 1);
3266 $template->assign('receipt_text',
3267 CRM_Utils_Array
::value('receipt_text',
3271 $template->assign('is_monetary', 1);
3272 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3273 $template->assign('currency', $this->currency
);
3274 $template->assign('address', CRM_Utils_Address
::format($input));
3275 if (!empty($values['customGroup'])) {
3276 $template->assign('customGroup', $values['customGroup']);
3278 if (!empty($values['softContributions'])) {
3279 $template->assign('softContributions', $values['softContributions']);
3281 if ($this->_component
== 'event') {
3282 $template->assign('title', $values['event']['title']);
3283 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3285 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3286 $viewRoles[] = $participantRoles[$v];
3288 $values['event']['participant_role'] = implode(', ', $viewRoles);
3289 $template->assign('event', $values['event']);
3290 $template->assign('participant', $values['participant']);
3291 $template->assign('location', $values['location']);
3292 $template->assign('customPre', $values['custom_pre_id']);
3293 $template->assign('customPost', $values['custom_post_id']);
3296 if ($this->_relatedObjects
['participant']->is_test
) {
3300 $values['params'] = [];
3301 //to get email of primary participant.
3302 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3303 $primaryAmount[] = [
3304 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3305 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3307 //build an array of cId/pId of participants
3308 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3309 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3310 //send receipt to additional participant if exists
3311 if (count($additionalIDs)) {
3312 $template->assign('isPrimary', 0);
3313 $template->assign('customProfile', NULL);
3314 //set additionalParticipant true
3315 $values['params']['additionalParticipant'] = TRUE;
3316 foreach ($additionalIDs as $pId => $cId) {
3318 //to change the status pending to completed
3319 $additional = new CRM_Event_DAO_Participant();
3320 $additional->id
= $pId;
3321 $additional->contact_id
= $cId;
3322 $additional->find(TRUE);
3323 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3324 $additional->status_id
= 1;
3325 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3326 //if additional participant dont have email
3328 if (!$additionalParticipantInfo) {
3329 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3332 'label' => $additional->fee_level
,
3333 'amount' => $additional->fee_amount
,
3335 $primaryAmount[] = [
3336 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3337 'amount' => $additional->fee_amount
,
3339 $additional->save();
3340 $template->assign('amount', $amount);
3341 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3345 //build an array of custom profile and assigning it to template
3346 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3348 if (count($customProfile)) {
3349 $template->assign('customProfile', $customProfile);
3352 // for primary contact
3353 $values['params']['additionalParticipant'] = FALSE;
3354 $template->assign('isPrimary', 1);
3355 $template->assign('amount', $primaryAmount);
3356 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3357 if ($this->payment_instrument_id
) {
3358 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3359 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3361 // carry paylater, since we did not created billing,
3362 // so need to pull email from primary location, CRM-4395
3363 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3369 * Check whether payment processor supports
3370 * cancellation of contribution subscription
3372 * @param int $contributionId
3375 * @param bool $isNotCancelled
3379 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3380 $cacheKeyString = "$contributionId";
3381 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3383 static $supportsCancel = [];
3385 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3386 $supportsCancel[$cacheKeyString] = FALSE;
3387 $isCancelled = FALSE;
3389 if ($isNotCancelled) {
3390 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3393 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3394 if (!empty($paymentObject)) {
3395 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3398 return $supportsCancel[$cacheKeyString];
3402 * Check whether subscription is already cancelled.
3404 * @param int $contributionId
3408 * contribution status
3410 public static function isSubscriptionCancelled($contributionId) {
3412 SELECT cr.contribution_status_id
3413 FROM civicrm_contribution_recur cr
3414 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3415 WHERE con.id = %1 LIMIT 1";
3416 $params = [1 => [$contributionId, 'Integer']];
3417 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3418 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3419 if ($status == 'Cancelled') {
3426 * Create all financial accounts entry.
3428 * @param array $params
3429 * Contribution object, line item array and params for trxn.
3432 * @param array $financialTrxnValues
3434 * @return null|\CRM_Core_BAO_FinancialTrxn
3436 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3437 $skipRecords = $update = $return = $isRelatedId = FALSE;
3439 $additionalParticipantId = [];
3440 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3441 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3443 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3444 $entityId = $params['participant_id'];
3445 $entityTable = 'civicrm_participant';
3446 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3448 elseif (!empty($params['membership_id'])) {
3449 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3450 // are created off one contribution should be handled elsewhere
3451 $entityId = $params['membership_id'];
3452 $entityTable = 'civicrm_membership';
3455 $entityId = $params['contribution']->id
;
3456 $entityTable = 'civicrm_contribution';
3459 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3460 $isRelatedId = TRUE;
3463 $entityID[] = $entityId;
3464 if (!empty($additionalParticipantId)) {
3465 $entityID +
= $additionalParticipantId;
3467 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3468 if (empty($params['prevContribution'])) {
3475 $statusId = $params['contribution']->contribution_status_id
;
3476 // CRM-13964 partial payment
3477 if ($contributionStatus == 'Partially paid'
3478 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_to_pay'])
3480 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_to_pay']);
3481 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3483 $fromFinancialAccountId = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3484 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3485 $params['total_amount'] = $partialAmtPay;
3487 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3488 if (empty($balanceTrxnInfo['trxn_id'])) {
3489 // create new balance transaction record
3490 $toFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], 'Accounts Receivable Account is');
3492 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3493 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3494 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3495 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3496 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3497 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3498 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3499 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3500 $balanceTrxnParams['status_id'] = $statusId;
3501 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3502 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3503 $balanceTrxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3504 $balanceTrxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3505 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3506 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3508 $balanceTrxnParams['is_payment'] = 1;
3510 if (!empty($params['payment_processor'])) {
3511 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3513 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3517 // build line item array if its not set in $params
3518 if (empty($params['line_item']) ||
$additionalParticipantId) {
3519 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3522 if ($contributionStatus != 'Failed' &&
3523 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3525 $skipRecords = TRUE;
3530 if (in_array($contributionStatus, $pendingStatus)) {
3531 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3532 $params['financial_type_id'],
3533 'Accounts Receivable Account is'
3536 elseif (!empty($params['payment_processor'])) {
3537 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3538 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3539 'id' => $params['payment_processor'],
3540 'return' => 'payment_instrument_id',
3543 elseif (!empty($params['payment_instrument_id'])) {
3544 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3547 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3548 $queryParams = [1 => [$relationTypeId, 'Integer']];
3549 $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);
3552 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3553 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3554 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3556 //build financial transaction params
3558 'contribution_id' => $params['contribution']->id
,
3559 'to_financial_account_id' => $params['to_financial_account_id'],
3560 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3561 'total_amount' => $totalAmount,
3562 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3563 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3564 'currency' => $params['contribution']->currency
,
3565 'trxn_id' => $params['contribution']->trxn_id
,
3566 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3567 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3568 // this should really default to completed (after discussion).
3569 'status_id' => $statusId,
3570 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3571 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3572 'pan_truncation' => CRM_Utils_Array
::value('pan_truncation', $params),
3573 'card_type_id' => CRM_Utils_Array
::value('card_type_id', $params),
3575 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3576 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3577 if (isset($params['refund_trxn_id'])) {
3578 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3579 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3582 //CRM-16259, set is_payment flag for non pending status
3583 if (!in_array($contributionStatus, $pendingStatus)) {
3584 $trxnParams['is_payment'] = 1;
3586 if (!empty($params['payment_processor'])) {
3587 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3590 if (isset($fromFinancialAccountId)) {
3591 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3594 // consider external values passed for recording transaction entry
3595 if (!empty($financialTrxnValues)) {
3596 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3598 if (empty($trxnParams['payment_processor_id'])) {
3599 unset($trxnParams['payment_processor_id']);
3602 $params['trxnParams'] = $trxnParams;
3604 if (!empty($params['prevContribution'])) {
3606 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3607 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3608 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3609 if (!isset($params['trxnParams']['trxn_id'])) {
3610 // Actually I have no idea why we are overwriting any values from the previous contribution.
3611 // (filling makes sense to me). However, only protecting this value as I really really know we
3612 // don't want this one overwritten.
3614 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3616 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3618 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3619 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3620 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3622 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3623 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3626 //if financial type is changed
3627 if (!empty($params['financial_type_id']) &&
3628 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3630 $accountRelationship = 'Income Account is';
3631 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3632 $accountRelationship = 'Deferred Revenue Account is';
3634 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3635 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3636 if ($oldFinancialAccount != $newFinancialAccount) {
3637 $params['total_amount'] = 0;
3638 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3639 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3640 $params['prevContribution']->financial_type_id
, $accountRelationship);
3643 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3644 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3645 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3648 self
::updateFinancialAccounts($params, 'changeFinancialType');
3649 $params['skipLineItem'] = FALSE;
3650 foreach ($params['line_item'] as &$lineItems) {
3651 foreach ($lineItems as &$line) {
3652 $line['financial_type_id'] = $params['financial_type_id'];
3655 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3656 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3657 $params['financial_account_id'] = $newFinancialAccount;
3658 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3659 self
::updateFinancialAccounts($params);
3660 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3661 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3663 $params['deferred_financial_account_id'] = $newFinancialAccount;
3667 //Update contribution status
3668 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3669 if (!isset($params['refund_trxn_id'])) {
3670 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3671 // gets preference over another so I am only 'protecting' a very specific tested flow
3672 // and letting natural justice take care of the rest.
3673 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3675 if (!empty($params['contribution_status_id']) &&
3676 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3678 //Update Financial Records
3679 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3680 if ($callUpdateFinancialAccounts) {
3681 self
::updateFinancialAccounts($params, 'changedStatus');
3682 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3687 // change Payment Instrument for a Completed contribution
3688 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3689 // instrument is null and now new payment instrument is added along with the payment
3690 if (!$params['contribution']->payment_instrument_id
) {
3691 $params['contribution']->find(TRUE);
3693 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3694 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3696 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3697 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3700 //if Change contribution amount
3701 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3702 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3703 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3704 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3705 if (isset($totalAmount) &&
3706 $totalAmount != $params['prevContribution']->total_amount
3708 //Update Financial Records
3709 $params['trxnParams']['from_financial_account_id'] = NULL;
3710 self
::updateFinancialAccounts($params, 'changedAmount');
3711 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3716 // Looks like we might have a data correction update.
3717 // This would be a case where a transaction id has been entered but it is incorrect &
3718 // the person goes back in & fixes it, as opposed to a new transaction.
3719 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3720 // the data fix scenario.
3722 if (isset($params['refund_trxn_id'])) {
3723 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3724 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3725 civicrm_api3('FinancialTrxn', 'create', [
3726 'id' => $refundIDs['financialTrxnId'],
3727 'trxn_id' => $params['refund_trxn_id'],
3731 $cardType = CRM_Utils_Array
::value('card_type_id', $params);
3732 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3733 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3738 // records finanical trxn and entity financial trxn
3739 // also make it available as return value
3740 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3741 $trxnParams['pan_truncation'] = CRM_Utils_Array
::value('pan_truncation', $params);
3742 $trxnParams['card_type_id'] = CRM_Utils_Array
::value('card_type_id', $params);
3743 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3744 $params['entity_id'] = $financialTxn->id
;
3745 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3746 self
::$_trxnIDs[] = $financialTxn->id
;
3750 // record line items and financial items
3751 if (empty($params['skipLineItem'])) {
3752 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3755 // create batch entry if batch_id is passed and
3756 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3757 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3759 'batch_id' => $params['batch_id'],
3760 'entity_table' => 'civicrm_financial_trxn',
3761 'entity_id' => $financialTxn->id
,
3763 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3766 // when a fee is charged
3767 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3768 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3771 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3772 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3774 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3775 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3776 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3778 unset($params['line_item']);
3779 self
::$_trxnIDs = NULL;
3784 * Update all financial accounts entry.
3786 * @param array $params
3787 * Contribution object, line item array and params for trxn.
3789 * @param string $context
3792 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3793 * adds unpredictability.
3796 public static function updateFinancialAccounts(&$params, $context = NULL) {
3798 $inputParams = $params;
3799 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3801 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3802 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3803 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3806 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3807 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3808 $params['entity_id'] = $trxn->id
;
3810 $itemParams['entity_table'] = 'civicrm_line_item';
3811 $trxnIds['id'] = $params['entity_id'];
3812 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3813 foreach ($params['line_item'] as $fieldId => $fields) {
3814 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3819 * Is this contribution status a reversal.
3821 * If so we would expect to record a negative value in the financial_trxn table.
3823 * @param int $status_id
3827 public static function isContributionStatusNegative($status_id) {
3828 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3829 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3833 * Check status validation on update of a contribution.
3835 * @param array $values
3836 * Previous form values before submit.
3838 * @param array $fields
3839 * The input form values.
3841 * @param array $errors
3846 public static function checkStatusValidation($values, &$fields, &$errors) {
3847 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3848 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3849 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3853 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3855 'Cancelled' => ['Completed', 'Refunded'],
3856 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3857 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3858 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3859 'Refunded' => ['Cancelled', 'Completed'],
3860 'Partially paid' => ['Completed'],
3861 'Pending refund' => ['Completed', 'Refunded'],
3864 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3865 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3867 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3868 1 => $contributionStatuses[$values['contribution_status_id']],
3869 2 => $contributionStatuses[$fields['contribution_status_id']],
3875 * Delete contribution of contact.
3879 * @param int $contactId
3883 public static function deleteContactContribution($contactId) {
3884 $contribution = new CRM_Contribute_DAO_Contribution();
3885 $contribution->contact_id
= $contactId;
3886 $contribution->find();
3887 while ($contribution->fetch()) {
3888 self
::deleteContribution($contribution->id
);
3893 * Get options for a given contribution field.
3895 * @param string $fieldName
3896 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3897 * @param array $props whatever is known about this dao object.
3899 * @return array|bool
3900 * @see CRM_Core_DAO::buildOptions
3903 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3904 $className = __CLASS__
;
3906 if (isset($props['orderColumn'])) {
3907 $params['orderColumn'] = $props['orderColumn'];
3909 switch ($fieldName) {
3910 // This field is not part of this object but the api supports it
3911 case 'payment_processor':
3912 $className = 'CRM_Contribute_BAO_ContributionPage';
3913 // Filter results by contribution page
3914 if (!empty($props['contribution_page_id'])) {
3915 $page = civicrm_api('contribution_page', 'getsingle', [
3917 'id' => ($props['contribution_page_id']),
3919 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3920 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3924 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3925 case 'honor_type_id':
3926 $className = 'CRM_Contribute_BAO_ContributionSoft';
3927 $fieldName = 'soft_credit_type_id';
3928 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3931 case 'contribution_status_id':
3932 if ($context !== 'validate') {
3933 $params['condition'] = "v.name <> 'Template'";
3936 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3940 * Validate financial type.
3944 * @param int $financialTypeId
3945 * Financial Type id.
3947 * @param string $relationName
3949 * @return array|bool
3951 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3952 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3954 if (!$financialAccount) {
3955 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3961 * @param int $targetCid
3962 * @param $activityType
3963 * @param string $title
3964 * @param int $contributionId
3965 * @param string $totalAmount
3966 * @param string $currency
3967 * @param string $trxn_date
3969 * @throws \CRM_Core_Exception
3970 * @throws \CiviCRM_API3_Exception
3972 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3973 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3974 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3975 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3976 // source record id would be the contribution id
3977 $srcRecId = $contributionId;
3981 'source_contact_id' => $targetCid,
3982 'source_record_id' => $srcRecId,
3983 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3984 'subject' => $subject,
3985 'activity_date_time' => $date,
3986 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3987 'skipRecentView' => TRUE,
3990 // create activity with target contacts
3991 $session = CRM_Core_Session
::singleton();
3992 $id = $session->get('userID');
3994 $activityParams['source_contact_id'] = $id;
3995 $activityParams['target_contact_id'][] = $targetCid;
3997 civicrm_api3('Activity', 'create', $activityParams);
4001 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4005 * @param bool $getTrxnInfo
4006 * @param bool $usingLineTotal
4010 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4011 // @todo deprecate passing in component - always call with contribution.
4012 if ($component == 'event') {
4013 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4015 if (!$contributionId) {
4016 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4017 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4018 $id = $primaryParticipantId;
4020 if (!$contributionId) {
4025 elseif ($component == 'membership') {
4026 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4029 $contributionId = $id;
4032 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4033 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4035 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4036 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4038 if (empty($total['total_amount']) ||
$usingLineTotal) {
4039 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4042 $baseTrxnId = $total['trxn_id'];
4043 $total = $total['total_amount'];
4046 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
4048 $contribution = civicrm_api3('Contribution', 'getsingle', [
4049 'id' => $contributionId,
4053 'contribution_status_id',
4054 'financial_type_id',
4058 $info['payLater'] = $contribution['is_pay_later'];
4059 $info['contribution_status'] = $contribution['contribution_status'];
4060 $info['currency'] = $contribution['currency'];
4062 $financialTypeId = $contribution['financial_type_id'];
4063 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
4065 $info['total'] = $total;
4066 $info['paid'] = $total - $paymentBalance;
4067 $info['balance'] = $paymentBalance;
4069 $info['component'] = $component;
4071 if ($getTrxnInfo && $baseTrxnId) {
4072 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4074 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4076 ft.payment_instrument_id,
4077 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
4079 FROM civicrm_contribution con
4080 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4081 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4082 AND ft.to_financial_account_id != %2
4083 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4084 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4085 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4087 WHERE con.id = %1 AND ft.is_payment = 1
4090 1 => [$contributionId, 'Integer'],
4091 2 => [$feeFinancialAccount, 'Integer'],
4093 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4094 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
4096 while ($resultDAO->fetch()) {
4097 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4098 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4099 if ($resultDAO->card_type_id
) {
4100 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
4101 $pantruncation = '';
4102 if ($resultDAO->pan_truncation
) {
4103 $pantruncation = ": {$resultDAO->pan_truncation}";
4105 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4108 // show payment edit link only for payments done via backoffice form
4109 $paymentEditLink = '';
4110 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
4112 CRM_Core_Action
::UPDATE
=> [
4113 'name' => "<i class='crm-i fa-pencil'></i>",
4114 'url' => 'civicrm/payment/edit',
4115 'class' => 'medium-popup',
4116 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
4117 'title' => ts('Edit Payment'),
4120 $paymentEditLink = CRM_Core_Action
::formLink(
4122 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
4124 'id' => $resultDAO->id
,
4125 'contribution_id' => $contributionId,
4131 'id' => $resultDAO->id
,
4132 'total_amount' => $resultDAO->total_amount
,
4133 'financial_type' => $resultDAO->financial_account
,
4134 'payment_instrument' => $paidByLabel,
4135 'receive_date' => $resultDAO->trxn_date
,
4136 'trxn_id' => $resultDAO->trxn_id
,
4137 'status' => $statuses[$resultDAO->status_id
],
4138 'currency' => $resultDAO->currency
,
4139 'action' => $paymentEditLink,
4141 if ($paidByName == 'Check') {
4142 $val['check_number'] = $resultDAO->check_number
;
4146 $info['transaction'] = $rows;
4149 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4154 * Get the outstanding balance on a contribution.
4156 * @param int $contributionId
4157 * @param float $contributionTotal
4158 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4162 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4163 if ($contributionTotal === NULL) {
4164 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4167 return (float) CRM_Utils_Money
::subtractCurrencies(
4169 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
4170 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4175 * Get the tax amount (misnamed function).
4177 * @param array $params
4178 * @param bool $isLineItem
4182 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4183 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4185 // This function should be only called after standardisation (removal of
4186 // thousand separator & using a decimal point for cents separator.
4187 // However, we don't know if that is always true :-(
4188 // There is a deprecation notice tho :-)
4189 $unknownIfMoneyIsClean = empty($params['skipCleanMoney']) && !$isLineItem;
4190 // Update contribution.
4191 if (!empty($params['id'])) {
4192 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4193 // there are no tax implications - early return.
4194 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4197 if (empty($params['prevContribution'])) {
4198 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4201 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4202 if (!isset($params[$field])) {
4203 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4204 // Tax amount gets added back on later....
4205 $params['total_amount'] = $params['prevContribution']->total_amount
-
4206 $params['prevContribution']->tax_amount
;
4209 $params[$field] = $params['prevContribution']->$field;
4210 if ($params[$field] != $params['prevContribution']->$field) {
4216 self
::calculateMissingAmountParams($params, $params['id']);
4217 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4218 // Assign tax Amount on update of contribution
4219 if (!empty($params['prevContribution']->tax_amount
)) {
4220 $params['tax_amount'] = 'null';
4221 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4222 foreach ($params['line_item'] as $setID => $priceField) {
4223 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4224 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4231 // New Contribution and update of contribution with tax rate financial type
4232 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4233 empty($params['skipLineItem']) && !$isLineItem
4235 $taxRateParams = $taxRates[$params['financial_type_id']];
4236 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams, $unknownIfMoneyIsClean);
4237 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4239 // Get Line Item on update of contribution
4240 if (isset($params['id'])) {
4241 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
4244 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4246 foreach ($params['line_item'] as $setID => $priceField) {
4247 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4248 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4251 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4253 elseif (isset($params['api.line_item.create'])) {
4254 // Update total amount of contribution using lineItem
4255 $taxAmountArray = [];
4256 foreach ($params['api.line_item.create'] as $key => $value) {
4257 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4258 $taxRate = $taxRates[$value['financial_type_id']];
4259 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4260 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4263 $params['tax_amount'] = array_sum($taxAmountArray);
4264 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4267 // update line item of contrbution
4268 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4269 $taxRate = $taxRates[$params['financial_type_id']];
4270 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate, $unknownIfMoneyIsClean);
4271 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4278 * Check financial type validation on update of a contribution.
4280 * @param int $financialTypeId
4281 * Value of latest Financial Type.
4283 * @param int $contributionId
4286 * @param array $errors
4291 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4292 if (!empty($financialTypeId)) {
4293 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4294 if ($oldFinancialTypeId == $financialTypeId) {
4298 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4300 '1' => [$contributionId, 'Integer'],
4302 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4303 if ($result->N
> 1) {
4304 $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.');
4309 * Update related pledge payment payments.
4311 * This function has been refactored out of the back office contribution form and may
4312 * still overlap with other functions.
4314 * @param string $action
4315 * @param int $pledgePaymentID
4316 * @param int $contributionID
4317 * @param bool $adjustTotalAmount
4318 * @param float $total_amount
4319 * @param float $original_total_amount
4320 * @param int $contribution_status_id
4321 * @param int $original_contribution_status_id
4323 public static function updateRelatedPledge(
4329 $original_total_amount,
4330 $contribution_status_id,
4331 $original_contribution_status_id
4333 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4337 if ($pledgePaymentID) {
4338 //store contribution id in payment record.
4339 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4342 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4349 if (!$pledgePaymentID) {
4352 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4358 $updatePledgePaymentStatus = FALSE;
4360 // If either the status or the amount has changed we update the pledge status.
4361 if ($action & CRM_Core_Action
::ADD
) {
4362 $updatePledgePaymentStatus = TRUE;
4364 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4365 ($original_total_amount != $total_amount))
4367 $updatePledgePaymentStatus = TRUE;
4370 if ($updatePledgePaymentStatus) {
4371 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4373 $contribution_status_id,
4382 * Compute the stats values
4384 * @param string $stat either 'mode' or 'median'
4385 * @param string $sql
4386 * @param string $alias of civicrm_contribution
4388 * @return array|null
4392 public static function computeStats($stat, $sql, $alias = NULL) {
4393 CRM_Core_Error
::deprecatedFunctionWarning('computeStats is now deprecated');
4398 * Is there only one line item attached to the contribution.
4404 * @throws \CiviCRM_API3_Exception
4406 public static function isSingleLineItem($id) {
4407 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4408 return ($lineItemCount == 1);
4412 * Complete an order.
4414 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4416 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4418 * Moving it out of the BaseIPN class is just the first step.
4420 * @param array $input
4422 * @param array $objects
4423 * @param CRM_Core_Transaction $transaction
4424 * @param CRM_Contribute_BAO_Contribution $contribution
4425 * @param bool $isPostPaymentCreate
4426 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4427 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4428 * transitioning related elements).
4431 * @throws \CRM_Core_Exception
4432 * @throws \CiviCRM_API3_Exception
4434 public static function completeOrder($input, &$ids, $objects, $transaction, $contribution, $isPostPaymentCreate = FALSE) {
4435 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4436 // The previous details are used when calculating line items so keep it before any code that 'does something'
4437 if (!empty($contribution->id
)) {
4438 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4440 $inputContributionWhiteList = [
4445 'payment_instrument_id',
4450 'contribution_status_id',
4454 if (self
::isSingleLineItem($primaryContributionID)) {
4455 $inputContributionWhiteList[] = 'financial_type_id';
4458 $participant = CRM_Utils_Array
::value('participant', $objects);
4459 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4460 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4461 $event = CRM_Utils_Array
::value('event', $objects);
4463 $paymentProcessorId = '';
4464 if (isset($objects['paymentProcessor'])) {
4465 if (is_array($objects['paymentProcessor'])) {
4466 $paymentProcessorId = $objects['paymentProcessor']['id'];
4469 $paymentProcessorId = $objects['paymentProcessor']->id
;
4473 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4475 $contributionParams = array_merge([
4476 'contribution_status_id' => $completedContributionStatusID,
4477 'source' => self
::getRecurringContributionDescription($contribution, $event),
4478 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4481 // CRM-20678 Ensure that the currency is correct in subseqent transcations.
4482 if (empty($contributionParams['currency']) && isset($objects['first_contribution']->currency
)) {
4483 $contributionParams['currency'] = $objects['first_contribution']->currency
;
4486 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4488 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4489 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4490 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4491 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4494 if ($recurringContributionID) {
4495 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4497 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4499 if (empty($contributionParams['receive_date']) && $changeDate) {
4500 $contributionParams['receive_date'] = $changeDate;
4503 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4504 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4507 if (isset($input['is_email_receipt'])) {
4508 $values['is_email_receipt'] = $input['is_email_receipt'];
4511 if ($input['component'] == 'contribute') {
4512 if ($contribution->contribution_page_id
) {
4513 // Figure out what we gain from this.
4514 // Note that we may have overwritten the is_email_receipt input, fix that below.
4515 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4517 elseif ($recurContrib && $recurringContributionID) {
4518 $values['amount'] = $recurContrib->amount
;
4519 $values['financial_type_id'] = $objects['contributionType']->id
;
4520 $values['title'] = $source = ts('Offline Recurring Contribution');
4523 if (isset($input['is_email_receipt'])) {
4524 // CRM-19601 - we may have overwritten this above.
4525 $values['is_email_receipt'] = $input['is_email_receipt'];
4527 elseif ($recurContrib && $recurringContributionID) {
4528 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4529 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4530 // dev/core#1245 this maybe not the desired effect because the default value for is_email_receipt is set to 0 rather than 1 in
4531 // Instance that had the table added via an upgrade in 4.1
4532 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
4533 // https://lab.civicrm.org/dev/core/issues/1245
4534 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4537 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4538 self
::updateMembershipBasedOnCompletionOfContribution(
4540 $primaryContributionID,
4546 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4547 if ($event->is_email_confirm
) {
4548 // @todo this should be set by the function that sends the mail after sending.
4549 $contributionParams['receipt_date'] = $changeDate;
4551 $participantParams['id'] = $participant->id
;
4552 $participantParams['status_id'] = 'Registered';
4553 civicrm_api3('Participant', 'create', $participantParams);
4557 $contributionParams['id'] = $contribution->id
;
4558 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4560 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4561 // unsetting it here does NOT cause any other contribution test to fail!
4562 unset($contributionParams['financial_type_id']);
4563 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4565 // Add new soft credit against current $contribution.
4566 if (!empty($objects['contributionRecur']) && $objects['contributionRecur']->id
) {
4567 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4570 if (empty($contribution->_relatedObjects
['participant']) && !empty($contribution->_relatedObjects
['membership'])) {
4571 // @fixme Can we remove this if altogether? - we removed the participant if / else and left relatedObjects['participant'] to ensure behaviour didn't change but it is probably not required.
4572 // @todo - use getRelatedMemberships instead
4573 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4574 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4575 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4578 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4579 $transaction->commit();
4581 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4582 $contributionParams['contribution_status_id'], $input['amount']);
4584 // create an activity record
4585 if ($input['component'] == 'contribute') {
4587 $targetContactID = NULL;
4588 if (!empty($ids['related_contact'])) {
4589 $targetContactID = $contribution->contact_id
;
4590 $contribution->contact_id
= $ids['related_contact'];
4592 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4595 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4596 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4597 if (!array_key_exists('is_email_receipt', $values) ||
4598 $values['is_email_receipt'] == 1
4600 civicrm_api3('Contribution', 'sendconfirmation', [
4601 'id' => $contribution->id
,
4602 'payment_processor_id' => $paymentProcessorId,
4604 CRM_Core_Error
::debug_log_message("Receipt sent");
4607 CRM_Core_Error
::debug_log_message("Success: Database updated");
4608 return $contributionResult;
4612 * Send receipt from contribution.
4614 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4616 * Note that the compose message part has been moved to contribution
4617 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4619 * @param array $input
4620 * Incoming data from Payment processor.
4622 * Related object IDs.
4623 * @param int $contributionID
4624 * @param array $values
4625 * Values related to objects that have already been loaded.
4626 * @param bool $returnMessageText
4627 * Should text be returned instead of sent. This.
4628 * is because the function is also used to generate pdfs
4631 * @throws \CRM_Core_Exception
4632 * @throws \CiviCRM_API3_Exception
4633 * @throws \Exception
4635 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4636 $returnMessageText = FALSE) {
4638 $contribution = new CRM_Contribute_BAO_Contribution();
4639 $contribution->id
= $contributionID;
4640 if (!$contribution->find(TRUE)) {
4641 throw new CRM_Core_Exception('Contribution does not exist');
4643 $contribution->loadRelatedObjects($input, $ids, TRUE);
4644 // set receipt from e-mail and name in value
4645 if (!$returnMessageText) {
4646 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4648 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4649 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4650 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4651 civicrm_api3('Contribution', 'create', [
4652 'receipt_date' => 'now',
4653 'id' => $contribution->id
,
4660 * Generate From email and from name in an array values
4662 * @param array $input
4663 * @param \CRM_Contribute_BAO_Contribution $contribution
4667 public static function generateFromEmailAndName($input, $contribution) {
4668 // Use input value if supplied.
4669 if (!empty($input['receipt_from_email'])) {
4671 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4672 $input['receipt_from_email'],
4675 // if we are still empty see if we can use anything from a contribution page.
4677 if (!empty($contribution->contribution_page_id
)) {
4678 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4680 // if we are still empty see if we can use anything from a contribution page.
4681 if (!empty($pageValues['receipt_from_email'])) {
4683 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4684 $pageValues['receipt_from_email'],
4687 // If we are still empty fall back to the domain or logged in user information.
4688 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4692 * Generate credit note id with next avaible number
4697 public static function createCreditNoteId() {
4698 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4700 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution WHERE creditnote_id IS NOT NULL");
4701 $creditNoteId = NULL;
4705 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4706 $result = civicrm_api3('Contribution', 'getcount', [
4708 'creditnote_id' => $creditNoteId,
4710 } while ($result > 0);
4712 return $creditNoteId;
4716 * Load related memberships.
4720 * @return array $ids
4725 * Note that in theory it should be possible to retrieve these from the line_item table
4726 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4727 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4728 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4729 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4731 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4734 public function loadRelatedMembershipObjects($ids = []) {
4736 SELECT membership_id
4737 FROM civicrm_membership_payment
4738 WHERE contribution_id = %1 ";
4739 $params = [1 => [$this->id
, 'Integer']];
4740 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4742 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4743 while ($dao->fetch()) {
4744 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4745 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4749 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4750 foreach ($ids['membership'] as $id) {
4752 $membership = new CRM_Member_BAO_Membership();
4753 $membership->id
= $id;
4754 if (!$membership->find(TRUE)) {
4755 throw new Exception("Could not find membership record: $id");
4757 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4758 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4759 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4760 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4768 * This function is used to record partial payments for contribution
4770 * @param array $contribution
4772 * @param array $params
4774 * @return CRM_Financial_DAO_FinancialTrxn
4776 public static function recordPartialPayment($contribution, $params) {
4777 CRM_Core_Error
::deprecatedFunctionWarning('use payment create api');
4778 $balanceTrxnParams['to_financial_account_id'] = self
::getToFinancialAccount($contribution, $params);
4779 $balanceTrxnParams['from_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($contribution['financial_type_id'], 'Accounts Receivable Account is');
4780 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4781 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4782 $balanceTrxnParams['trxn_date'] = CRM_Utils_Array
::value('trxn_date', $params, CRM_Utils_Array
::value('contribution_receive_date', $params, date('YmdHis')));
4783 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4784 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4785 $balanceTrxnParams['currency'] = $contribution['currency'];
4786 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4787 $balanceTrxnParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Completed');
4788 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4789 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4790 $balanceTrxnParams['is_payment'] = 1;
4792 if (!empty($params['payment_processor'])) {
4793 // I can't find evidence this is passed in - I was gonna just remove it but decided to deprecate as I see self::getToFinancialAccount
4794 // also anticipates it.
4795 CRM_Core_Error
::deprecatedFunctionWarning('passing payment_processor is deprecated - use payment_processor_id');
4796 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4798 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4802 * Get the description (source field) for the recurring contribution.
4804 * @param CRM_Contribute_BAO_Contribution $contribution
4805 * @param CRM_Event_DAO_Event|null $event
4808 * @throws \CiviCRM_API3_Exception
4810 protected static function getRecurringContributionDescription($contribution, $event) {
4811 if (!empty($contribution->source
)) {
4812 return $contribution->source
;
4814 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4815 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4816 'id' => $contribution->contribution_page_id
,
4817 'return' => 'title',
4819 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4822 return ts('Online Event Registration') . ': ' . $event->title
;
4824 elseif (!empty($contribution->contribution_recur_id
)) {
4825 return 'recurring contribution';
4831 * Function to add payments for contribution for Partially Paid status
4833 * @deprecated this is known to be flawed and possibly buggy.
4835 * Replace with Order.create->Payment.create flow.
4837 * @param array $contributions
4839 * @throws \CiviCRM_API3_Exception
4841 public static function addPayments($contributions) {
4842 // get financial trxn which is a payment
4843 $ftSql = "SELECT ft.id, ft.total_amount
4844 FROM civicrm_financial_trxn ft
4845 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4846 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4847 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
4848 'labelColumn' => 'name',
4850 foreach ($contributions as $contribution) {
4851 if ($contributionStatus[$contribution->contribution_status_id
] !== 'Partially paid') {
4854 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, [
4862 // store financial item Proportionaly.
4864 'total_amount' => $ftDao->total_amount
,
4865 'contribution_id' => $contribution->id
,
4867 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4872 * Function use to store line item proportionally in in entity financial trxn table
4874 * @param array $trxnParams
4876 * @param int $trxnId
4878 * @param float $contributionTotalAmount
4880 * @throws \CiviCRM_API3_Exception
4882 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4883 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4884 if (!empty($lineItems)) {
4885 // get financial item
4886 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4888 'contribution_total_amount' => $contributionTotalAmount,
4889 'trxn_total_amount' => $trxnParams['total_amount'],
4890 'trxn_id' => $trxnId,
4892 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4897 * Checks if line items total amounts
4898 * match the contribution total amount.
4900 * @param array $params
4901 * array of order params.
4903 * @throws \API_Exception
4905 public static function checkLineItems(&$params) {
4906 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4907 $lineItemAmount = 0;
4909 foreach ($params['line_items'] as &$lineItems) {
4910 foreach ($lineItems['line_item'] as &$item) {
4911 if (empty($item['financial_type_id'])) {
4912 $item['financial_type_id'] = $params['financial_type_id'];
4914 $lineItemAmount +
= $item['line_total'] + CRM_Utils_Array
::value('tax_amount', $item, 0.00);
4918 if (!isset($totalAmount)) {
4919 $params['total_amount'] = $lineItemAmount;
4922 $currency = CRM_Utils_Array
::value('currency', $params, '');
4924 if (empty($currency)) {
4925 $currency = CRM_Core_Config
::singleton()->defaultCurrency
;
4928 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4929 throw new CRM_Contribute_Exception_CheckLineItemsException();
4935 * Get the financial account for the item associated with the new transaction.
4937 * @param array $params
4938 * @param int $default
4942 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4944 if (!empty($params['financial_account_id'])) {
4945 return $params['financial_account_id'];
4948 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4949 $preferredAccountsRelationships = [
4950 'Refunded' => 'Credit/Contra Revenue Account is',
4951 'Chargeback' => 'Chargeback Account is',
4954 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4955 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4956 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4958 $preferredAccountsRelationships[$contributionStatus]
4966 * ContributionPage values were being imposed onto values.
4968 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4969 * REALLY didn't want superimposed. The rest are left there in their overkill out
4972 * The rationale for making this explicit is that it was a case of carefully set values being
4973 * seemingly randonly overwritten without much care. In general I think array randomly setting
4974 * variables en mass is risky.
4976 * @param array $values
4980 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4981 $contributionPageValues = [];
4982 CRM_Contribute_BAO_ContributionPage
::setValues(
4983 $this->contribution_page_id
,
4984 $contributionPageValues
4987 // These are the values that I believe to be useful.
4990 'pay_later_receipt',
4992 'receipt_from_email',
4993 'receipt_from_name',
4997 'honoree_profile_id',
4998 'onbehalf_profile_id',
4999 'honor_block_is_active',
5000 // Kinda might be - but would be on the contribution...
5003 // Included for 'fear of regression' but can't justify any use for these....
5005 'payment_processor',
5006 'financial_type_id',
5007 'amount_block_is_active',
5012 'default_amount_id',
5016 'initial_amount_help_text',
5017 'initial_amount_label',
5019 'is_allow_other_amount',
5020 'is_billing_required',
5021 'is_confirm_enabled',
5022 'is_credit_card_only',
5024 'is_partial_payment',
5025 'is_recur_installments',
5026 'is_recur_interval',
5030 'min_initial_amount',
5031 'recur_frequency_unit',
5038 foreach ($valuesToCopy as $valueToCopy) {
5039 if (isset($contributionPageValues[$valueToCopy])) {
5040 if ($valueToCopy === 'title') {
5041 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
5044 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5052 * Get values of CiviContribute Settings
5053 * and check if its enabled or not.
5054 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5055 * in serialized form. Usually this should be stored as flat settings for each form fields
5056 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5057 * settings we will live with an inconsistency because it's too hard to change for now.
5058 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5061 * @param string $name
5062 * @param bool $checkInvoicing
5066 public static function checkContributeSettings($name = NULL, $checkInvoicing = FALSE) {
5067 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5069 if ($checkInvoicing && empty($contributeSettings['invoicing'])) {
5074 return CRM_Utils_Array
::value($name, $contributeSettings);
5076 return $contributeSettings;
5080 * This function process contribution related objects.
5082 * @param int $contributionId
5083 * @param int $statusId
5084 * @param int|null $previousStatusId
5086 * @param string $receiveDate
5088 * @return null|string
5090 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5092 if (!$contributionId ||
!$statusId) {
5097 'contribution_id' => $contributionId,
5098 'contribution_status_id' => $statusId,
5099 'previous_contribution_status_id' => $previousStatusId,
5100 'receive_date' => $receiveDate,
5103 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5105 if (!is_array($updateResult) ||
5106 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5107 !is_array($updatedComponents) ||
5108 empty($updatedComponents)
5113 // get the user display name.
5115 SELECT display_name as displayName
5116 FROM civicrm_contact
5117 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5118 WHERE civicrm_contribution.id = {$contributionId}";
5119 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5121 // get the status message for user.
5122 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5124 if ($componentName == 'CiviMember') {
5125 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5126 CRM_Member_PseudoConstant
::membershipStatus()
5129 $statusNameMsgPart = 'updated';
5130 switch ($updatedStatusName) {
5133 $statusNameMsgPart = $updatedStatusName;
5137 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
5138 1 => $userDisplayName,
5139 2 => $statusNameMsgPart,
5143 if ($componentName == 'CiviEvent') {
5144 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5145 CRM_Event_PseudoConstant
::participantStatus()
5147 if ($updatedStatusName == 'Cancelled') {
5148 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
5150 elseif ($updatedStatusName == 'Registered') {
5151 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
5155 if ($componentName == 'CiviPledge') {
5156 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5157 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5159 if ($updatedStatusName == 'Cancelled') {
5160 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
5162 elseif ($updatedStatusName == 'Failed') {
5163 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
5165 elseif ($updatedStatusName == 'Completed') {
5166 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
5175 * Get the contribution as it is in the database before being updated.
5177 * @param int $contributionID
5179 * @return \CRM_Contribute_BAO_Contribution|null
5181 private static function getOriginalContribution($contributionID) {
5182 return self
::getValues(['id' => $contributionID]);
5186 * Get the amount for the financial item row.
5188 * Helper function to start to break down recordFinancialTransactions for readability.
5190 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
5192 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
5193 * for historical reasons. Going forwards we can hope to add tests & improve readibility
5196 * @param array $params
5197 * Params as passed to contribution.create
5199 * @param string $context
5200 * changeFinancialType| changedAmount
5201 * @param array $lineItemDetails
5203 * @param bool $isARefund
5204 * Is this a refund / negative transaction.
5205 * @param int $previousLineItemTotal
5208 * @todo move recordFinancialAccounts & helper functions to their own class?
5211 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
5212 if ($context == 'changedAmount') {
5213 $lineTotal = $lineItemDetails['line_total'];
5214 if ($lineTotal != $previousLineItemTotal) {
5215 $lineTotal -= $previousLineItemTotal;
5219 elseif ($context == 'changeFinancialType') {
5220 return -$lineItemDetails['line_total'];
5222 elseif ($context == 'changedStatus') {
5223 $cancelledTaxAmount = 0;
5225 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
5227 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
5229 elseif ($context === NULL) {
5230 // erm, yes because? but, hey, it's tested.
5231 return $lineItemDetails['line_total'];
5233 elseif (empty($lineItemDetails['line_total'])) {
5234 // follow legacy code path
5236 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5237 return $params['total_amount'];
5240 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
5245 * Get the multiplier for adjusting rows.
5247 * If we are dealing with a refund or cancellation then it will be a negative
5248 * amount to reflect the negative transaction.
5250 * If we are changing Financial Type it will be a negative amount to
5251 * adjust down the old type.
5253 * @param int $contribution_status_id
5254 * @param string $context
5258 protected static function getMultiplier($contribution_status_id, $context) {
5259 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
5266 * Does this transaction reflect a payment instrument change.
5268 * @param array $params
5269 * @param array $pendingStatuses
5273 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5274 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
5276 if (array_key_exists('payment_instrument_id', $params)) {
5277 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
5278 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
5280 //check if status is changed from Pending to Completed
5281 // do not update payment instrument changes for Pending to Completed
5282 if (!($contributionStatus == 'Completed' &&
5283 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
5288 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
5289 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
5290 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5294 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
5295 $params['contribution']->check_number
!= $params['prevContribution']->check_number
5297 // another special case when check number is changed, create new financial records
5298 // create financial trxn with negative amount
5306 * Update the memberships associated with a contribution if it has been completed.
5308 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5309 * load them in this function. Code clean up would compensate for any minor performance implication.
5311 * @param \CRM_Contribute_BAO_Contribution $contribution
5312 * @param int $primaryContributionID
5313 * @param string $changeDate
5315 * @throws \CRM_Core_Exception
5316 * @throws \CiviCRM_API3_Exception
5318 public static function updateMembershipBasedOnCompletionOfContribution($contribution, $primaryContributionID, $changeDate) {
5319 $memberships = self
::getRelatedMemberships($contribution->id
);
5320 foreach ($memberships as $membership) {
5321 $membershipParams = [
5322 'id' => $membership['id'],
5323 'contact_id' => $membership['contact_id'],
5324 'is_test' => $membership['is_test'],
5325 'membership_type_id' => $membership['membership_type_id'],
5326 'membership_activity_status' => 'Completed',
5329 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
5330 $membershipParams['membership_type_id'],
5331 $membershipParams['is_test'],
5332 $membershipParams['id']
5335 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5336 // this picks up membership type changes during renewals
5337 // @todo this is almost certainly an obsolete sql call, the pre-change
5338 // membership is accessible via $this->_relatedObjects
5340 SELECT membership_type_id
5341 FROM civicrm_membership_log
5342 WHERE membership_id={$membershipParams['id']}
5345 $dao = CRM_Core_DAO
::executeQuery($sql);
5346 if ($dao->fetch()) {
5347 if (!empty($dao->membership_type_id
)) {
5348 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
5351 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5352 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5353 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5354 // The api assumes num_terms is a special sauce for 'is_renewal' so we need to not pass it when updating a pending to completed.
5355 // @todo once apiv4 ships with core switch to that & find sanity.
5356 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
5357 $membershipParams['membership_type_id'],
5358 $primaryContributionID
5361 // @todo remove all this stuff in favour of letting the api call further down handle in
5362 // (it is a duplication of what the api does).
5363 $dates = array_fill_keys([
5368 if ($currentMembership) {
5370 * Fixed FOR CRM-4433
5371 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5372 * when Contribution mode is notify and membership is for renewal )
5374 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5376 // @todo - we should pass membership_type_id instead of null here but not
5377 // adding as not sure of testing
5378 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
5379 $changeDate, NULL, $membershipParams['num_terms']
5381 $dates['join_date'] = $currentMembership['join_date'];
5384 //get the status for membership.
5385 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
5387 $dates['join_date'],
5390 $membershipParams['membership_type_id'],
5394 unset($dates['end_date']);
5395 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
5396 //we might be renewing membership,
5397 //so make status override false.
5398 $membershipParams['is_override'] = FALSE;
5399 $membershipParams['status_override_end_date'] = 'null';
5401 //CRM-17723 - reset static $relatedContactIds array()
5402 // @todo move it to Civi Statics.
5404 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
5405 civicrm_api3('Membership', 'create', $membershipParams);
5410 * Get payment links as they relate to a contribution.
5412 * If a payment can be made then include a payment link & if a refund is appropriate
5413 * then a refund link.
5416 * @param float $balance
5417 * @param string $contributionStatus
5420 * $actionLinks Links array containing:
5424 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5425 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
5426 // In general the balance is the best way to determine if a payment can be added or not,
5427 // but not for Failed contributions, where we don't accept additional payments at the moment.
5428 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5429 // do accept more payments agains them.
5433 if ((int) $balance > 0) {
5434 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
5436 'url' => CRM_Utils_System
::url('civicrm/payment', [
5442 'title' => ts('Submit Credit Card payment'),
5446 'url' => CRM_Utils_System
::url('civicrm/payment', [
5451 'title' => ts('Record Payment'),
5454 elseif ((int) $balance < 0) {
5456 'url' => CRM_Utils_System
::url('civicrm/payment', [
5461 'title' => ts('Record Refund'),
5464 return $actionLinks;
5468 * Get a query to determine the amount donated by the contact/s in the current financial year.
5470 * @param array $contactIDs
5474 public static function getAnnualQuery($contactIDs) {
5475 $contactIDs = implode(',', $contactIDs);
5476 $config = CRM_Core_Config
::singleton();
5477 $currentMonth = date('m');
5478 $currentDay = date('d');
5480 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
5482 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
5483 (int) $config->fiscalYearStart
['d'] > $currentDay
5486 $year = date('Y') - 1;
5491 $nextYear = $year +
1;
5493 if ($config->fiscalYearStart
) {
5494 $newFiscalYearStart = $config->fiscalYearStart
;
5495 if ($newFiscalYearStart['M'] < 10) {
5496 // This is just a clumsy way of adding padding.
5497 // @todo next round look for a nicer way.
5498 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5500 if ($newFiscalYearStart['d'] < 10) {
5501 // This is just a clumsy way of adding padding.
5502 // @todo next round look for a nicer way.
5503 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5505 $config->fiscalYearStart
= $newFiscalYearStart;
5506 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
5509 // First of January.
5512 $startDate = "$year$monthDay";
5513 $endDate = "$nextYear$monthDay";
5516 'contact_id' => 'IN (' . $contactIDs . ')',
5517 'is_test' => ' = 0',
5518 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5520 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5521 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
5524 foreach ($whereClauses as $key => $clause) {
5525 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5527 $whereClauseString = implode(' AND ', $clauses);
5529 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5530 // this group by + having on contribution_status_id improves performance
5532 SELECT COUNT(*) as count,
5533 SUM(total_amount) as amount,
5534 AVG(total_amount) as average,
5536 FROM civicrm_contribution b
5537 WHERE " . $whereClauseString . "
5538 GROUP BY currency, contribution_status_id
5539 HAVING $havingClause
5545 * Assign Test Value.
5547 * @param string $fieldName
5548 * @param array $fieldDef
5549 * @param int $counter
5551 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5552 if ($fieldName == 'tax_amount') {
5553 $this->{$fieldName} = "0.00";
5555 elseif ($fieldName == 'net_amount') {
5556 $this->{$fieldName} = "2.00";
5558 elseif ($fieldName == 'total_amount') {
5559 $this->{$fieldName} = "3.00";
5561 elseif ($fieldName == 'fee_amount') {
5562 $this->{$fieldName} = "1.00";
5565 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5570 * Check if contribution has participant/membership payment.
5572 * @param int $contributionId
5577 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5578 // get line item for contribution
5579 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5580 // check if line item is for membership or participant
5581 foreach ($lineItems as $items) {
5582 if ($items['entity_table'] == 'civicrm_participant') {
5586 elseif ($items['entity_table'] == 'civicrm_membership') {
5598 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5600 * @param array $trxnParams
5601 * Financial trxn params
5602 * @param array $contributionParams
5603 * Contribution Params
5607 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5608 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5611 $statusId = $contributionParams['contribution']->contribution_status_id
;
5612 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5613 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5614 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5615 // Return if contribution status is not completed.
5616 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5617 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5618 && $contributionParams['prevContribution']->is_pay_later
== 0
5624 $params = $trxnParams;
5625 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5626 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5627 $params['to_financial_account_id'] = $arAccountId;
5628 $params['status_id'] = array_search('Pending', $contributionStatuses);
5629 $params['is_payment'] = FALSE;
5630 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5631 self
::$_trxnIDs[] = $trxn->id
;
5632 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5636 * Calculate financial item amount when contribution is updated.
5638 * @param array $params
5639 * contribution params
5640 * @param array $amountParams
5642 * @param string $context
5646 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5647 if (!empty($params['is_quick_config'])) {
5648 $amount = $amountParams['item_amount'];
5650 $amount = $params['total_amount'];
5651 if ($context === NULL) {
5652 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5657 $amount = $amountParams['line_total'];
5658 if ($context == 'changedAmount') {
5659 $amount -= $amountParams['previous_line_total'];
5661 $amount *= $amountParams['diff'];
5667 * Retrieve Sales Tax Financial Accounts.
5673 public static function getSalesTaxFinancialAccounts() {
5674 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5675 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5676 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5677 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5678 $queryParams = [1 => [$accountRel, 'Integer']];
5679 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5680 $financialAccount = [];
5681 while ($dao->fetch()) {
5682 $financialAccount[$dao->id
] = $dao->id
;
5684 return $financialAccount;
5688 * Create tax entry in civicrm_entity_financial_trxn table.
5690 * @param array $entityParams
5692 * @param array $eftParams
5694 * @throws \CiviCRM_API3_Exception
5696 public static function createProportionalEntry($entityParams, $eftParams) {
5698 if ($entityParams['contribution_total_amount'] != 0) {
5699 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5701 // Record Entity Financial Trxn; CRM-20145
5702 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5703 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5707 * Create array of last financial item id's.
5709 * @param int $contributionId
5713 public static function getLastFinancialItemIds($contributionId) {
5714 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5715 FROM civicrm_financial_item fi
5716 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5717 WHERE li.contribution_id = %1";
5718 $dao = CRM_Core_DAO
::executeQuery($sql, [
5724 $ftIds = $taxItems = [];
5725 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5726 while ($dao->fetch()) {
5727 /* if sales tax item*/
5728 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5729 $taxItems[$dao->price_field_value_id
] = [
5730 'financial_item_id' => $dao->id
,
5731 'amount' => $dao->tax_amount
,
5735 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5738 return [$ftIds, $taxItems];
5742 * Create proportional entries in civicrm_entity_financial_trxn.
5744 * @param array $entityParams
5746 * @param array $lineItems
5748 * @param array $ftIds
5750 * @param array $taxItems
5752 * @throws \CiviCRM_API3_Exception
5754 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5756 'entity_table' => 'civicrm_financial_item',
5757 'financial_trxn_id' => $entityParams['trxn_id'],
5759 foreach ($lineItems as $key => $value) {
5760 if ($value['qty'] == 0) {
5763 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5764 $entityParams['line_item_amount'] = $value['line_total'];
5765 self
::createProportionalEntry($entityParams, $eftParams);
5766 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5767 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5768 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5769 self
::createProportionalEntry($entityParams, $eftParams);
5775 * Load entities related to the contribution into $this->_relatedObjects.
5779 * @throws \CRM_Core_Exception
5781 protected function loadRelatedEntitiesByID($ids) {
5783 'contact' => 'CRM_Contact_BAO_Contact',
5784 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5785 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5786 'financialType' => 'CRM_Financial_BAO_FinancialType',
5787 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5789 foreach ($entities as $entity => $bao) {
5790 if (!empty($ids[$entity])) {
5791 $this->_relatedObjects
[$entity] = new $bao();
5792 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5793 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5794 throw new CRM_Core_Exception($entity . ' could not be loaded');
5801 * Should an email receipt be sent for this contribution when complete.
5803 * @param array $input
5807 protected function isEmailReceipt($input) {
5808 if (isset($input['is_email_receipt'])) {
5809 return $input['is_email_receipt'];
5811 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5812 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;
5818 * Function to replace contribution tokens.
5820 * @param array $contributionIds
5822 * @param string $subject
5824 * @param array $subjectToken
5826 * @param string $text
5828 * @param string $html
5830 * @param array $messageToken
5832 * @param bool $escapeSmarty
5835 * @throws \CiviCRM_API3_Exception
5837 public static function replaceContributionTokens(
5846 if (empty($contributionIds)) {
5849 $contributionDetails = [];
5850 foreach ($contributionIds as $id) {
5851 $result = self
::getContributionTokenValues($id, $messageToken);
5852 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5853 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5854 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5856 return $contributionDetails;
5860 * Get the contribution fields for $id and display labels where
5861 * appropriate (if the token is present).
5864 * @param array $messageToken
5867 public static function getContributionTokenValues($id, $messageToken) {
5871 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5872 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5873 if (!empty($messageToken)) {
5874 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5875 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5876 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5884 * Get invoice_number for contribution.
5886 * @param int $contributionID
5890 public static function getInvoiceNumber($contributionID) {
5891 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix', TRUE)) {
5892 return $invoicePrefix . $contributionID;
5899 * Load the values needed for the event message.
5901 * @param int $eventID
5902 * @param int $participantID
5903 * @param int|null $contributionID
5906 * @throws \CRM_Core_Exception
5908 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5913 $values = ['event' => []];
5915 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5916 // add custom fields for event
5917 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5919 $eventCustomGroup = [];
5920 foreach ($eventGroupTree as $key => $group) {
5921 if ($key === 'info') {
5925 foreach ($group['fields'] as $k => $customField) {
5926 $groupLabel = $group['title'];
5927 if (!empty($customField['customValue'])) {
5928 foreach ($customField['customValue'] as $customFieldValues) {
5929 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5934 $values['event']['customGroup'] = $eventCustomGroup;
5936 //get participant details
5937 $participantParams = [
5938 'id' => $participantID,
5941 $values['participant'] = [];
5943 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5944 // add custom fields for event
5945 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5946 $participantCustomGroup = [];
5947 foreach ($participantGroupTree as $key => $group) {
5948 if ($key === 'info') {
5952 foreach ($group['fields'] as $k => $customField) {
5953 $groupLabel = $group['title'];
5954 if (!empty($customField['customValue'])) {
5955 foreach ($customField['customValue'] as $customFieldValues) {
5956 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
5961 $values['participant']['customGroup'] = $participantCustomGroup;
5963 //get location details
5965 'entity_id' => $eventID,
5966 'entity_table' => 'civicrm_event',
5968 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5971 'entity_table' => 'civicrm_event',
5972 'entity_id' => $eventID,
5973 'module' => 'CiviEvent',
5976 list($custom_pre_id,
5978 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5980 $values['custom_pre_id'] = $custom_pre_id;
5981 $values['custom_post_id'] = $custom_post_ids;
5983 // set lineItem for event contribution
5984 if ($contributionID) {
5985 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5986 if (!empty($participantIds)) {
5987 foreach ($participantIds as $pIDs) {
5988 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5989 if (!CRM_Utils_System
::isNull($lineItem)) {
5990 $values['lineItem'][] = $lineItem;