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 +--------------------------------------------------------------------+
12 use Civi\Api4\Activity
;
13 use Civi\Api4\ContributionPage
;
14 use Civi\Api4\ContributionRecur
;
15 use Civi\Api4\PaymentProcessor
;
20 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
25 * Static field for all the contribution information that we can potentially import
29 public static $_importableFields = NULL;
32 * Static field for all the contribution information that we can potentially export
36 public static $_exportableFields = NULL;
39 * Static field to hold financial trxn id's.
43 public static $_trxnIDs = NULL;
46 * Field for all the objects related to this contribution.
49 * 1) deprecated function transitionComponents
50 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
51 * 3) some invoice code that is copied from 2
52 * 4) odds & sods that need to be investigated and fixed.
54 * However, it is no longer used by completeOrder.
56 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
60 public $_relatedObjects = [];
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
69 * "contribution"\"event"
71 public $_component = NULL;
74 * Possibly obsolete variable.
76 * If you use it please explain why it is set in the create function here.
80 public $trxn_result_code;
85 public function __construct() {
86 parent
::__construct();
90 * Takes an associative array and creates a contribution object.
92 * the function extract all the params it needs to initialize the create a
93 * contribution object. the params array could contain additional unused name/value
96 * @param array $params
97 * (reference ) an assoc array of name/value pairs.
99 * @return \CRM_Contribute_BAO_Contribution
100 * @throws \CRM_Core_Exception
101 * @throws \CiviCRM_API3_Exception
103 public static function add(&$params) {
104 if (empty($params)) {
108 $contributionID = $params['id'] ??
NULL;
109 $action = $contributionID ?
'edit' : 'create';
111 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
112 $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)]);
113 throw new CRM_Core_Exception($message);
116 //set defaults in create mode
117 if (!$contributionID) {
118 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
119 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
120 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
121 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
125 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
126 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
127 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
129 if (!$contributionStatusID) {
130 // Since the fee amount is expecting this (later on) ensure it is always set.
131 // It would only not be set for an update where it is unchanged.
132 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
133 'id' => $contributionID,
134 'return' => 'contribution_status_id',
137 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
140 && !empty($params['membership_id'])
141 && Civi
::settings()->get('deferred_revenue_enabled')
143 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
144 if ($memberStartDate) {
145 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
148 self
::calculateMissingAmountParams($params, $contributionID);
150 if (!empty($params['payment_instrument_id'])) {
151 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
152 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
153 $params['check_number'] = 'null';
157 $setPrevContribution = TRUE;
158 if ($contributionID && $setPrevContribution) {
159 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
161 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
163 if ($contributionID && !empty($params['revenue_recognition_date'])
164 && !($previousContributionStatus === 'Pending')
165 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
167 unset($params['revenue_recognition_date']);
170 // Get Line Items if we don't have them already.
171 if (empty($params['line_item'])) {
172 if (isset($params['id'])) {
173 CRM_Price_BAO_LineItem
::getLineItemArray($params, [$params['id']]);
176 CRM_Price_BAO_LineItem
::getLineItemArray($params);
180 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
181 isset($params['financial_type_id']))) {
182 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
185 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
187 $contribution = new CRM_Contribute_BAO_Contribution();
188 $contribution->copyValues($params);
190 $contribution->id
= $contributionID;
192 if (empty($contribution->id
)) {
193 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
194 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
195 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
199 $result = $contribution->save();
201 // Add financial_trxn details as part of fix for CRM-4724
202 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
203 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
205 //add Account details
206 $params['contribution'] = $contribution;
207 if (empty($params['is_post_payment_create'])) {
208 // If this is being called from the Payment.create api/ BAO then that Entity
209 // takes responsibility for the financial transactions. In fact calling Payment.create
210 // to add payments & having it call completetransaction and / or contribution.create
211 // to update related entities is the preferred flow.
212 // Note that leveraging this parameter for any other code flow is not supported and
213 // is likely to break in future and / or cause serious problems in your data.
214 // https://github.com/civicrm/civicrm-core/pull/14673
215 self
::recordFinancialAccounts($params);
218 if (self
::isUpdateToRecurringContribution($params)) {
219 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
220 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
222 $params['receive_date'] ??
'now'
226 $params['contribution_id'] = $contribution->id
;
228 if (!empty($params['custom']) &&
229 is_array($params['custom'])
231 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
234 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
236 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
241 * Is this contribution updating an existing recurring contribution.
243 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
244 * pending payment is being confirmed (or failing).
246 * @param array $params
250 public static function isUpdateToRecurringContribution($params) {
251 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
254 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
257 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
260 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
261 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
268 * Get defaults for new entity.
272 public static function getDefaults() {
274 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
275 FALSE, FALSE, FALSE, 'AND is_default = 1')
277 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
278 'receive_date' => date('Y-m-d H:i:s'),
283 * Fetch the object and store the values in the values array.
285 * @param array $params
286 * Input parameters to find object.
287 * @param array $values
288 * Output values of the object.
290 * The array that holds all the db ids.
292 * @return CRM_Contribute_BAO_Contribution|null
293 * The found object or null
295 public static function getValues($params, &$values = [], &$ids = []) {
296 if (empty($params)) {
299 $contribution = new CRM_Contribute_BAO_Contribution();
301 $contribution->copyValues($params);
303 if ($contribution->find(TRUE)) {
304 $ids['contribution'] = $contribution->id
;
306 CRM_Core_DAO
::storeValues($contribution, $values);
308 return $contribution;
310 // return by reference
316 * Get the values and resolve the most common mappings.
318 * Since contribution status is resolved in almost every function that calls getValues it makes
319 * sense to have an extra function to resolve it rather than repeat the code.
321 * Think carefully before adding more mappings to be resolved as there could be performance implications
322 * if this function starts to be called from more iterative functions.
324 * @param array $params
325 * Input parameters to find object.
328 * Array of the found contribution.
329 * @throws CRM_Core_Exception
331 public static function getValuesWithMappings($params) {
333 $contribution = self
::getValues($params, $values, $ids);
334 if (is_null($contribution)) {
335 throw new CRM_Core_Exception('No contribution found');
337 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
342 * Calculate net_amount & fee_amount if they are not set.
344 * Net amount should be total - fee.
345 * This should only be called for new contributions.
347 * @param array $params
348 * Params for a new contribution before they are saved.
349 * @param int|null $contributionID
350 * Contribution ID if we are dealing with an update.
352 * @throws \CiviCRM_API3_Exception
354 public static function calculateMissingAmountParams(&$params, $contributionID) {
355 if (!$contributionID && (!isset($params['fee_amount']) ||
$params['fee_amount'] === '')) {
356 if (isset($params['total_amount']) && isset($params['net_amount'])) {
357 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
360 $params['fee_amount'] = 0;
363 if (!isset($params['net_amount'])) {
364 if (!$contributionID) {
365 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
368 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
369 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
370 // net_amount may need adjusting.
371 $contribution = civicrm_api3('Contribution', 'getsingle', [
372 'id' => $contributionID,
373 'return' => ['total_amount', 'net_amount', 'fee_amount'],
375 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
376 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
377 $params['net_amount'] = $totalAmount - $feeAmount;
385 * @param $billingLocationTypeID
389 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
390 $hasBillingField = FALSE;
399 //build address array
401 $addressParams['location_type_id'] = $billingLocationTypeID;
402 $addressParams['is_billing'] = 1;
404 $billingFirstName = $params['billing_first_name'] ??
NULL;
405 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
406 $billingLastName = $params['billing_last_name'] ??
NULL;
407 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
409 foreach ($billingFields as $value) {
410 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
411 if (!empty($addressParams[$value])) {
412 $hasBillingField = TRUE;
415 return [$hasBillingField, $addressParams];
419 * Get address params ready to be passed to the payment processor.
421 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
422 * To create an address we need state_province_id.
424 * @param array $params
425 * @param int $billingLocationTypeID
429 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
430 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
431 foreach ($addressParams as $name => $field) {
432 if (substr($name, 0, 8) == 'billing_') {
433 $addressParams[substr($name, 9)] = $addressParams[$field];
436 return [$hasBillingField, $addressParams];
440 * Get the number of terms for this contribution for a given membership type
441 * based on querying the line item table and relevant price field values
442 * Note that any one contribution should only be able to have one line item relating to a particular membership
445 * @param int $membershipTypeID
447 * @param int $contributionID
451 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
452 $numTerms = CRM_Core_DAO
::singleValueQuery("
453 SELECT membership_num_terms FROM civicrm_line_item li
454 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
455 WHERE contribution_id = %1 AND membership_type_id = %2",
456 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
458 // default of 1 is precautionary
459 return empty($numTerms) ?
1 : $numTerms;
463 * Takes an associative array and creates a contribution object.
465 * @param array $params
466 * (reference ) an assoc array of name/value pairs.
468 * @return CRM_Contribute_BAO_Contribution
470 * @throws \API_Exception
471 * @throws \CRM_Core_Exception
472 * @throws \CiviCRM_API3_Exception
474 public static function create(&$params) {
476 $transaction = new CRM_Core_Transaction();
479 $contribution = self
::add($params);
481 catch (CRM_Core_Exception
$e) {
482 $transaction->rollback();
486 $params['contribution_id'] = $contribution->id
;
487 $session = CRM_Core_Session
::singleton();
489 if (!empty($params['note'])) {
491 'entity_table' => 'civicrm_contribution',
492 'note' => $params['note'],
493 'entity_id' => $contribution->id
,
494 'contact_id' => $session->get('userID'),
496 if (!$noteParams['contact_id']) {
497 $noteParams['contact_id'] = $params['contact_id'];
499 CRM_Core_BAO_Note
::add($noteParams);
502 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
504 $transaction->commit();
506 if (empty($contribution->contact_id
)) {
507 $contribution->find(TRUE);
510 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
511 if (!empty($params['on_behalf'])
514 $existingActivity = Activity
::get(FALSE)->setWhere([
515 ['source_record_id', '=', $contribution->id
],
516 ['activity_type_id:name', '=', 'Contribution'],
517 ])->execute()->first();
519 $campaignParams = isset($params['campaign_id']) ?
['campaign_id' => ($params['campaign_id'] ??
NULL)] : [];
520 Activity
::save(FALSE)->addRecord(array_merge([
521 'activity_type_id:name' => 'Contribution',
522 'source_record_id' => $contribution->id
,
523 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
,
524 'target_contact_id' => CRM_Core_Session
::getLoggedInContactID() ?
[$contribution->contact_id
] : [],
525 'activity_date_time' => $contribution->receive_date
,
526 'is_test' => (bool) $contribution->is_test
,
527 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
528 'skipRecentView' => TRUE,
529 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
530 'id' => $existingActivity['id'] ??
NULL,
531 ], $campaignParams))->execute();
534 // do not add to recent items for import, CRM-4399
535 if (empty($params['skipRecentView'])) {
536 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
537 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
539 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
546 $retrieveRequired = 0;
547 foreach ($titleFields as $titleField) {
548 if (!isset($contribution->$titleField)) {
549 $retrieveRequired = 1;
553 if ($retrieveRequired == 1) {
554 $contribution->find(TRUE);
556 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
557 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
560 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
561 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
562 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
566 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
567 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
568 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
572 // add the recently created Contribution
573 CRM_Utils_Recent
::add($title,
577 $contribution->contact_id
,
583 return $contribution;
587 * Get the values for pseudoconstants for name->value and reverse.
589 * @param array $defaults
590 * (reference) the default values, some of which need to be resolved.
591 * @param bool $reverse
592 * True if we want to resolve the values in the reverse direction (value -> name).
594 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
595 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
596 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
597 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
598 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
602 * Convert associative array names to values and vice-versa.
604 * This function is used by both the web form layer and the api. Note that
605 * the api needs the name => value conversion, also the view layer typically
606 * requires value => name conversion
608 * @param array $defaults
609 * @param string $property
610 * @param array $lookup
611 * @param bool $reverse
615 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
616 $id = $property . '_id';
618 $src = $reverse ?
$property : $id;
619 $dst = $reverse ?
$id : $property;
621 if (!array_key_exists($src, $defaults)) {
625 $look = $reverse ?
array_flip($lookup) : $lookup;
627 if (is_array($look)) {
628 if (!array_key_exists($defaults[$src], $look)) {
632 $defaults[$dst] = $look[$defaults[$src]];
637 * Retrieve DB object based on input parameters.
639 * It also stores all the retrieved values in the default array.
641 * @param array $params
642 * (reference ) an assoc array of name/value pairs.
643 * @param array $defaults
644 * (reference ) an assoc array to hold the name / value pairs.
645 * in a hierarchical manner
647 * (reference) the array that holds all the db ids.
649 * @return CRM_Contribute_BAO_Contribution
651 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
652 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
653 return $contribution;
657 * Combine all the importable fields from the lower levels object.
659 * The ordering is important, since currently we do not have a weight
660 * scheme. Adding weight is super important and should be done in the
661 * next week or so, before this can be called complete.
663 * @param string $contactType
664 * @param bool $status
667 * array of importable Fields
669 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
670 if (!self
::$_importableFields) {
671 if (!self
::$_importableFields) {
672 self
::$_importableFields = [];
676 $fields = ['' => ['title' => ts('- do not import -')]];
679 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
682 $note = CRM_Core_DAO_Note
::import();
683 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
684 unset($tmpFields['option_value']);
685 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
686 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
688 // Using new Dedupe rule.
690 'contact_type' => $contactType,
691 'used' => 'Unsupervised',
693 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
694 $tmpContactField = [];
695 if (is_array($fieldsArray)) {
696 foreach ($fieldsArray as $value) {
697 //skip if there is no dupe rule
698 if ($value == 'none') {
701 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
706 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
707 $tmpContactField[trim($value)] = $contactFields[trim($value)];
709 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
712 $title = $tmpContactField[trim($value)]['title'];
714 $tmpContactField[trim($value)]['title'] = $title;
718 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
719 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
720 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
721 $fields = array_merge($fields, $tmpContactField);
722 $fields = array_merge($fields, $tmpFields);
723 $fields = array_merge($fields, $note);
724 $fields = array_merge($fields, $optionFields);
725 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
726 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
727 self
::$_importableFields = $fields;
729 return self
::$_importableFields;
733 * Combine all the exportable fields from the lower level objects.
735 * @param bool $checkPermission
738 * array of exportable Fields
740 public static function &exportableFields($checkPermission = TRUE) {
741 if (!self
::$_exportableFields) {
742 if (!self
::$_exportableFields) {
743 self
::$_exportableFields = [];
746 $fields = CRM_Contribute_DAO_Contribution
::export();
747 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
748 $fields = array_merge(
750 CRM_Contribute_DAO_Product
::export(),
751 CRM_Contribute_DAO_ContributionProduct
::export(),
752 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
754 'contribution_product_id' => [
755 'title' => ts('Premium'),
756 'name' => 'contribution_product_id',
757 'where' => 'civicrm_product.id',
758 'data_type' => CRM_Utils_Type
::T_INT
,
764 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
766 $contributionPage = [
767 'contribution_page' => [
768 'title' => ts('Contribution Page'),
769 'name' => 'contribution_page',
770 'where' => 'civicrm_contribution_page.title',
771 'data_type' => CRM_Utils_Type
::T_STRING
,
775 $contributionNote = [
776 'contribution_note' => [
777 'title' => ts('Contribution Note'),
778 'name' => 'contribution_note',
779 'data_type' => CRM_Utils_Type
::T_TEXT
,
784 'contribution_batch' => [
785 'title' => ts('Batch Name'),
791 'contribution_campaign_title' => [
792 'title' => ts('Campaign Title'),
793 'name' => 'campaign_title',
794 'where' => 'civicrm_campaign.title',
795 'data_type' => CRM_Utils_Type
::T_STRING
,
798 $softCreditFields = [
799 'contribution_soft_credit_name' => [
800 'name' => 'contribution_soft_credit_name',
801 'title' => ts('Soft Credit For'),
802 'where' => 'civicrm_contact_d.display_name',
803 'data_type' => CRM_Utils_Type
::T_STRING
,
805 'contribution_soft_credit_amount' => [
806 'name' => 'contribution_soft_credit_amount',
807 'title' => ts('Soft Credit Amount'),
808 'where' => 'civicrm_contribution_soft.amount',
809 'data_type' => CRM_Utils_Type
::T_MONEY
,
811 'contribution_soft_credit_type' => [
812 'name' => 'contribution_soft_credit_type',
813 'title' => ts('Soft Credit Type'),
814 'where' => 'contribution_softcredit_type.label',
815 'data_type' => CRM_Utils_Type
::T_STRING
,
817 'contribution_soft_credit_contribution_id' => [
818 'name' => 'contribution_soft_credit_contribution_id',
819 'title' => ts('Soft Credit For Contribution ID'),
820 'where' => 'civicrm_contribution_soft.contribution_id',
821 'data_type' => CRM_Utils_Type
::T_INT
,
823 'contribution_soft_credit_contact_id' => [
824 'name' => 'contribution_soft_credit_contact_id',
825 'title' => ts('Soft Credit For Contact ID'),
826 'where' => 'civicrm_contact_d.id',
827 'data_type' => CRM_Utils_Type
::T_INT
,
831 $fields = array_merge($fields, $contributionPage,
832 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
833 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
836 self
::$_exportableFields = $fields;
839 return self
::$_exportableFields;
843 * Record an activity when a payment is received.
845 * @todo this is intended to be moved to payment BAO class as a protected function
846 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
847 * merit it's own function as it makes the code less rather than more readable.
849 * @param int $contributionId
850 * @param int $participantId
851 * @param string $totalAmount
852 * @param string $currency
853 * @param string $trxnDate
855 * @throws \CRM_Core_Exception
856 * @throws \CiviCRM_API3_Exception
858 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
859 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
861 if ($participantId) {
862 $inputParams['id'] = $participantId;
865 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
866 $entityObj = $entityObj[$participantId];
867 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
870 $entityObj = new CRM_Contribute_BAO_Contribution();
871 $entityObj->id
= $contributionId;
872 $entityObj->find(TRUE);
873 $title = ts('Contribution');
875 // @todo per block above this is not a logical splitting off of functionality.
876 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
880 * Get the value for the To Financial Account.
882 * @param $contribution
887 public static function getToFinancialAccount($contribution, $params) {
888 if (!empty($params['payment_processor_id'])) {
889 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
891 if (!empty($params['payment_instrument_id'])) {
892 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
895 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
896 $queryParams = [1 => [$relationTypeId, 'Integer']];
897 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
902 * Get memberships related to the contribution.
904 * @param int $contributionID
908 protected static function getRelatedMemberships($contributionID) {
909 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
910 'return' => 'membership_id',
911 'contribution_id' => (int) $contributionID,
914 foreach ($membershipPayments as $membershipPayment) {
915 $membershipIDs[] = $membershipPayment['membership_id'];
917 if (empty($membershipIDs)) {
920 // We could combine this with the MembershipPayment.get - we'd
921 // need to re-wrangle the params (here or in the calling function)
922 // as they would then me membership.contact_id, membership.is_test etc
923 return civicrm_api3('Membership', 'get', [
924 'id' => ['IN' => $membershipIDs],
925 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
930 * Do any accounting updates required as a result of a contribution status change.
932 * Currently we have a bit of a roundabout where adding a payment results in this being called &
933 * this may attempt to add a payment. We need to resolve that....
935 * The 'right' way to add payments or refunds is through the Payment.create api. That api
936 * then updates the contribution but this process should not also record another financial trxn.
937 * Currently we have weak detection fot that scenario & where it is detected the first returned
938 * value is FALSE - meaning 'do not continue'.
940 * We should also look at the fact that the calling function - updateFinancialAccounts
941 * bunches together some disparate processes rather than having separate appropriate
944 * @param array $params
947 * Return indicates whether the updateFinancialAccounts function should continue.
949 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
950 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
951 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
953 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
954 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
955 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
956 // why it is here or where it is handled instead.
957 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
958 && $currentContributionStatus == 'Partially paid'))
963 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
964 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
965 $params['trxnParams']['total_amount'] = -$params['total_amount'];
967 elseif (($previousContributionStatus == 'Pending'
968 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
970 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
971 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
973 if ($currentContributionStatus == 'Cancelled') {
974 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
975 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
976 $params['trxnParams']['total_amount'] = -$params['total_amount'];
979 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
980 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
984 if (($previousContributionStatus == 'Pending'
985 ||
$previousContributionStatus == 'In Progress')
986 && ($currentContributionStatus == 'Completed')
988 if (empty($params['line_item'])) {
990 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
991 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
992 // & this can be removed
995 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
996 // This is an update so original currency if none passed in.
997 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
999 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1000 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1001 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1002 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1004 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1007 'entity_table' => 'civicrm_financial_item',
1009 foreach ($params['line_item'] as $fieldId => $fields) {
1010 foreach ($fields as $fieldValueId => $lineItemDetails) {
1011 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1013 1 => [$lineItemDetails['id'], 'Integer'],
1015 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1016 while ($financialItem->fetch()) {
1017 $entityParams['entity_id'] = $financialItem->id
;
1018 $entityParams['amount'] = $financialItem->amount
;
1019 foreach (self
::$_trxnIDs as $tID) {
1020 $entityParams['financial_trxn_id'] = $tID;
1021 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1032 * It is possible to override the membership id that is updated from the payment processor.
1034 * Historically Paypal does this & it still does if it determines data is messed up - see
1035 * https://lab.civicrm.org/dev/membership/issues/13
1037 * Read the comment block on repeattransaction for more information
1038 * about how things should work.
1040 * @param int $contributionID
1041 * @param array $input
1043 * @throws \CiviCRM_API3_Exception
1045 protected static function handleMembershipIDOverride($contributionID, $input) {
1046 if (!empty($input['membership_id'])) {
1047 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1048 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1053 * Update all financial items related to the line item tto have a status of paid.
1055 * @param int $lineItemID
1057 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1060 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1063 2 => [$lineItemID, 'Integer'],
1065 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1066 CRM_Core_DAO
::executeQuery($query, $fparams);
1070 * Create the financial items for the line.
1072 * @param array $params
1073 * @param string $context
1074 * @param array $fields
1075 * @param array $previousLineItems
1076 * @param array $inputParams
1077 * @param bool $isARefund
1078 * @param array $trxnIds
1079 * @param int $fieldId
1083 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1084 foreach ($fields as $fieldValueId => $lineItemDetails) {
1085 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1086 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1087 if ($params['contribution']->receive_date
) {
1088 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1091 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1093 $currency = $params['prevContribution']->currency
;
1094 if ($params['contribution']->currency
) {
1095 $currency = $params['contribution']->currency
;
1097 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1099 'transaction_date' => $receiveDate,
1100 'contact_id' => $params['prevContribution']->contact_id
,
1101 'currency' => $currency,
1102 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1103 'description' => $prevFinancialItem['description'] ??
NULL,
1104 'status_id' => $prevFinancialItem['status_id'],
1105 'financial_account_id' => $financialAccount,
1106 'entity_table' => 'civicrm_line_item',
1107 'entity_id' => $lineItemDetails['id'],
1109 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1110 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1111 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1113 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1114 $taxAmount = (float) $lineItemDetails['tax_amount'];
1115 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1116 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1117 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1119 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1120 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1122 if ($taxAmount != 0) {
1123 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1124 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1125 if ($lineItemDetails['financial_type_id']) {
1126 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1128 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1136 * Does this contributtion status update represent a refund.
1138 * @param int $previousContributionStatusID
1139 * @param int $currentContributionStatusID
1143 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1144 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1147 return self
::isContributionStatusNegative($currentContributionStatusID);
1151 * Get transaction information about the contribution.
1153 * @param int $contributionId
1154 * @param int $financialTypeID
1158 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1160 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1162 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1164 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1166 ft.payment_instrument_id,
1167 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1169 FROM civicrm_contribution con
1170 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1171 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1172 AND ft.to_financial_account_id != %2
1173 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1174 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1175 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1177 WHERE con.id = %1 AND ft.is_payment = 1
1180 1 => [$contributionId, 'Integer'],
1181 2 => [$feeFinancialAccount, 'Integer'],
1183 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1184 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1186 while ($resultDAO->fetch()) {
1187 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1188 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1189 if ($resultDAO->card_type_id
) {
1190 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1191 $pantruncation = '';
1192 if ($resultDAO->pan_truncation
) {
1193 $pantruncation = ": {$resultDAO->pan_truncation}";
1195 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1198 // show payment edit link only for payments done via backoffice form
1199 $paymentEditLink = '';
1200 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1202 CRM_Core_Action
::UPDATE
=> [
1203 'name' => ts('Edit Payment'),
1204 'icon' => 'fa-pencil',
1205 'url' => 'civicrm/payment/edit',
1206 'class' => 'medium-popup',
1207 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1208 'title' => ts('Edit Payment'),
1211 $paymentEditLink = CRM_Core_Action
::formLink(
1213 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1215 'id' => $resultDAO->id
,
1216 'contribution_id' => $contributionId,
1220 'Payment.edit.action',
1228 'id' => $resultDAO->id
,
1229 'total_amount' => $resultDAO->total_amount
,
1230 'financial_type' => $resultDAO->financial_account
,
1231 'payment_instrument' => $paidByLabel,
1232 'receive_date' => $resultDAO->trxn_date
,
1233 'trxn_id' => $resultDAO->trxn_id
,
1234 'status' => $statuses[$resultDAO->status_id
],
1235 'currency' => $resultDAO->currency
,
1236 'action' => $paymentEditLink,
1238 if ($paidByName == 'Check') {
1239 $val['check_number'] = $resultDAO->check_number
;
1247 * Should an email receipt be sent for this contribution on completion.
1249 * @param array $input
1250 * @param int $contributionPageID
1251 * @param int $recurringContributionID
1254 * @throws \API_Exception
1255 * @throws \Civi\API\Exception\UnauthorizedException
1257 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1258 if (isset($input['is_email_receipt'])) {
1259 return (bool) $input['is_email_receipt'];
1261 if ($recurringContributionID) {
1262 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1263 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1264 // 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
1265 // Instance that had the table added via an upgrade in 4.1
1266 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1267 // https://lab.civicrm.org/dev/core/issues/1245
1268 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1270 if ($contributionPageID) {
1271 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1273 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1281 public function addSelectWhereClause() {
1282 $whereClauses = parent
::addSelectWhereClause();
1283 if ($whereClauses !== []) {
1284 // In this case permisssions have been applied & we assume the
1285 // financialaclreport is applying these
1286 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1287 return $whereClauses;
1290 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1291 return $whereClauses;
1293 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1294 if (empty($types)) {
1295 $whereClauses['financial_type_id'] = 'IN (0)';
1298 $whereClauses['financial_type_id'] = [
1299 'IN (' . implode(',', array_keys($types)) . ')',
1302 return $whereClauses;
1306 * @param null $status
1307 * @param null $startDate
1308 * @param null $endDate
1310 * @return array|null
1312 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1316 $where[] = 'contribution_status_id = 1';
1320 $where[] = 'contribution_status_id = 3';
1325 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1328 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1330 $financialTypeACLJoin = '';
1331 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1332 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1333 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1334 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1335 if ($financialTypes) {
1336 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1337 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1340 $where[] = "c.financial_type_id IN (0)";
1344 $whereCond = implode(' AND ', $where);
1347 SELECT sum( total_amount ) as total_amount,
1348 count( c.id ) as total_count,
1350 FROM civicrm_contribution c
1351 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1352 $financialTypeACLJoin
1354 AND ( is_test = 0 OR is_test IS NULL )
1355 AND contact.is_deleted = 0
1359 $dao = CRM_Core_DAO
::executeQuery($query);
1362 while ($dao->fetch()) {
1363 $count +
= $dao->total_count
;
1364 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1368 'amount' => implode(', ', $amount),
1376 * Delete the indirect records associated with this contribution first.
1380 * @return mixed|null
1381 * $results no of deleted Contribution on success, false otherwise
1383 public static function deleteContribution($id) {
1384 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1386 $transaction = new CRM_Core_Transaction();
1389 //delete activity record
1391 'source_record_id' => $id,
1392 // activity type id for contribution
1393 'activity_type_id' => 6,
1396 CRM_Activity_BAO_Activity
::deleteActivity($params);
1398 //delete billing address if exists for this contribution.
1399 self
::deleteAddress($id);
1401 //update pledge and pledge payment, CRM-3961
1402 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1404 // remove entry from civicrm_price_set_entity, CRM-5095
1405 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1406 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1408 // cleanup line items.
1409 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1411 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1412 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1414 if ($participantId) {
1415 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1418 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1422 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1423 $noteId = key($note);
1425 CRM_Core_BAO_Note
::del($noteId, FALSE);
1428 $dao = new CRM_Contribute_DAO_Contribution();
1431 $results = $dao->delete();
1433 $transaction->commit();
1435 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1437 // delete the recently created Contribution
1438 $contributionRecent = [
1440 'type' => 'Contribution',
1442 CRM_Utils_Recent
::del($contributionRecent);
1448 * React to a financial transaction (payment) failure.
1450 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1451 * payments is important for forensic and outreach reasons.
1453 * @param int $contributionID
1454 * @param int $contactID
1455 * @param string $message
1457 * @throws \CiviCRM_API3_Exception
1459 public static function failPayment($contributionID, $contactID, $message) {
1460 civicrm_api3('activity', 'create', [
1461 'activity_type_id' => 'Failed Payment',
1462 'details' => $message,
1463 'subject' => ts('Payment failed at payment processor'),
1464 'source_record_id' => $contributionID,
1465 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1468 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1469 civicrm_api3('contribution', 'create', [
1470 'id' => $contributionID,
1471 'contribution_status_id' => 'Failed',
1476 * Check if there is a contribution with the same trxn_id or invoice_id.
1478 * @param array $input
1479 * An assoc array of name/value pairs.
1480 * @param array $duplicates
1481 * (reference) store ids of duplicate contribs.
1485 * true if duplicate, false otherwise
1487 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1489 $id = $input['id'] ??
NULL;
1491 $trxn_id = $input['trxn_id'] ??
NULL;
1492 $invoice_id = $input['invoice_id'] ??
NULL;
1498 $clause[] = "trxn_id = %1";
1499 $input[1] = [$trxn_id, 'String'];
1503 $clause[] = "invoice_id = %2";
1504 $input[2] = [$invoice_id, 'String'];
1507 if (empty($clause)) {
1511 $clause = implode(' OR ', $clause);
1513 $clause = "( $clause ) AND id != %3";
1514 $input[3] = [$id, 'Integer'];
1517 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1518 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1520 while ($dao->fetch()) {
1521 $duplicates[] = $dao->id
;
1528 * Takes an associative array and creates a contribution_product object.
1530 * the function extract all the params it needs to initialize the create a
1531 * contribution_product object. the params array could contain additional unused name/value
1534 * @param array $params
1535 * (reference) an assoc array of name/value pairs.
1537 * @return CRM_Contribute_DAO_ContributionProduct
1539 public static function addPremium(&$params) {
1540 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1541 $contributionProduct->copyValues($params);
1542 return $contributionProduct->save();
1546 * Get list of contribution fields for profile.
1547 * For now we only allow custom contribution fields to be in
1550 * @param bool $addExtraFields
1551 * True if special fields needs to be added.
1554 * the list of contribution fields
1556 public static function getContributionFields($addExtraFields = TRUE) {
1557 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1558 // @todo remove this - this line was added because payment_instrument_id was not
1559 // set to exportable - but now it is.
1560 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1562 if ($addExtraFields) {
1563 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1566 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1568 foreach ($contributionFields as $key => $var) {
1569 if ($key == 'contribution_contact_id') {
1572 elseif ($key == 'contribution_campaign_id') {
1573 $var['title'] = ts('Campaign');
1575 $fields[$key] = $var;
1578 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1583 * Add extra fields specific to contribution.
1585 public static function getSpecialContributionFields() {
1587 'contribution_soft_credit_name' => [
1588 'name' => 'contribution_soft_credit_name',
1589 'title' => ts('Soft Credit Name'),
1590 'headerPattern' => '/^soft_credit_name$/i',
1591 'where' => 'civicrm_contact_d.display_name',
1593 'contribution_soft_credit_email' => [
1594 'name' => 'contribution_soft_credit_email',
1595 'title' => ts('Soft Credit Email'),
1596 'headerPattern' => '/^soft_credit_email$/i',
1597 'where' => 'soft_email.email',
1599 'contribution_soft_credit_phone' => [
1600 'name' => 'contribution_soft_credit_phone',
1601 'title' => ts('Soft Credit Phone'),
1602 'headerPattern' => '/^soft_credit_phone$/i',
1603 'where' => 'soft_phone.phone',
1605 'contribution_soft_credit_contact_id' => [
1606 'name' => 'contribution_soft_credit_contact_id',
1607 'title' => ts('Soft Credit Contact ID'),
1608 'headerPattern' => '/^soft_credit_contact_id$/i',
1609 'where' => 'civicrm_contribution_soft.contact_id',
1611 'contribution_pcp_title' => [
1612 'name' => 'contribution_pcp_title',
1613 'title' => ts('Personal Campaign Page Title'),
1614 'headerPattern' => '/^contribution_pcp_title$/i',
1615 'where' => 'contribution_pcp.title',
1619 return $extraFields;
1623 * @param int $pageID
1627 public static function getCurrentandGoalAmount($pageID) {
1629 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1630 FROM civicrm_contribution_page p,
1631 civicrm_contribution c
1632 WHERE p.id = c.contribution_page_id
1634 AND c.cancel_date is null
1638 $config = CRM_Core_Config
::singleton();
1639 $params = [1 => [$pageID, 'Integer']];
1640 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1642 if ($dao->fetch()) {
1643 return [$dao->goal
, $dao->total
];
1646 return [NULL, NULL];
1651 * Get list of contributions which credit the passed in contact ID.
1653 * The returned array provides details about the original contribution & donor.
1655 * @param int $honorId
1656 * In Honor of Contact ID.
1659 * list of contribution fields
1660 * @todo - this is a confusing function called from one place. It has a test. It would be
1661 * nice to deprecate it.
1664 public static function getHonorContacts($honorId) {
1666 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1667 $honorDAO->contact_id
= $honorId;
1670 $type = CRM_Contribute_PseudoConstant
::financialType();
1672 while ($honorDAO->fetch()) {
1673 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1674 $contributionDAO->id
= $honorDAO->contribution_id
;
1676 if ($contributionDAO->find(TRUE)) {
1677 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1678 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1679 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1680 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1681 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1682 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1683 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1684 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1685 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1693 * Get the sort name of a contact for a particular contribution.
1696 * Id of the contribution.
1698 * @return null|string
1699 * sort name of the contact if found
1701 public static function sortName($id) {
1702 $id = CRM_Utils_Type
::escape($id, 'Integer');
1705 SELECT civicrm_contact.sort_name
1706 FROM civicrm_contribution, civicrm_contact
1707 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1708 AND civicrm_contribution.id = {$id}
1710 return CRM_Core_DAO
::singleValueQuery($query);
1714 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1716 * @param int|array $contactIDs
1720 public static function annual($contactIDs) {
1721 if (!is_array($contactIDs)) {
1722 // In practice I can't fine any evidence that this function is ever called with
1723 // anything other than a single contact id, but left like this due to .... fear.
1724 $contactIDs = explode(',', $contactIDs);
1727 $query = self
::getAnnualQuery($contactIDs);
1728 $dao = CRM_Core_DAO
::executeQuery($query);
1730 $amount = $average = [];
1731 while ($dao->fetch()) {
1732 if ($dao->count
> 0 && $dao->amount
> 0) {
1733 $count +
= $dao->count
;
1734 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1735 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1741 implode(', ', $amount),
1742 implode(', ', $average),
1749 * Check if there is a contribution with the params passed in.
1751 * Used for trxn_id,invoice_id and contribution_id
1753 * @param array $params
1754 * An assoc array of name/value pairs.
1757 * contribution id if success else NULL
1759 public static function checkDuplicateIds($params) {
1760 $dao = new CRM_Contribute_DAO_Contribution();
1764 foreach ($params as $k => $v) {
1766 $clause[] = "$k = '$v'";
1769 $clause = implode(' AND ', $clause);
1770 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1771 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1773 while ($dao->fetch()) {
1781 * Get the contribution details for component export.
1783 * @param int $exportMode
1785 * @param array $componentIds
1791 public static function getContributionDetails($exportMode, $componentIds) {
1792 $paymentDetails = [];
1793 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1795 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1796 $componentSelect = " civicrm_participant_payment.participant_id id";
1797 $additionalClause = "
1798 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1799 AND civicrm_participant_payment.participant_id {$componentClause} )
1802 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1803 $componentSelect = " civicrm_membership_payment.membership_id id";
1804 $additionalClause = "
1805 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1806 AND civicrm_membership_payment.membership_id {$componentClause} )
1809 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1810 $componentSelect = " civicrm_pledge_payment.id id";
1811 $additionalClause = "
1812 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1813 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1817 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1818 trxn_id, {$componentSelect}
1819 FROM civicrm_contribution
1820 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1821 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1822 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1823 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1824 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1825 AND option_group_contribution_status.id = contribution_status.option_group_id )
1829 $dao = CRM_Core_DAO
::executeQuery($query);
1831 while ($dao->fetch()) {
1832 $paymentDetails[$dao->id
] = [
1833 'total_amount' => $dao->total_amount
,
1834 'contribution_status' => $dao->status
,
1835 'receive_date' => $dao->receive_date
,
1836 'pay_instru' => $dao->payment_instrument
,
1837 'trxn_id' => $dao->trxn_id
,
1841 return $paymentDetails;
1845 * Create address associated with contribution record.
1847 * As long as there is one or more billing field in the parameters we will create the address.
1849 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1852 * @param array $params
1853 * @param int $billingLocationTypeID
1858 public static function createAddress($params, $billingLocationTypeID) {
1859 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1860 if ($hasBillingField) {
1861 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1862 return $address->id
;
1869 * Delete billing address record related contribution.
1871 * @param int $contributionId
1872 * @param int $contactId
1874 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1876 $contactJoin = NULL;
1878 if ($contributionId) {
1879 $clauses[] = "cc.id = {$contributionId}";
1883 $clauses[] = "cco.id = {$contactId}";
1884 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1887 if (empty($clauses)) {
1888 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1891 $condition = implode(' OR ', $clauses);
1895 FROM civicrm_address ca
1896 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1900 $dao = CRM_Core_DAO
::executeQuery($query);
1902 while ($dao->fetch()) {
1903 $params = ['id' => $dao->id
];
1904 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1909 * This function check online pending contribution associated w/
1910 * Online Event Registration or Online Membership signup.
1912 * @param int $componentId
1913 * Participant/membership id.
1914 * @param string $componentName
1918 * pending contribution id.
1920 public static function checkOnlinePendingContribution($componentId, $componentName) {
1921 $contributionId = NULL;
1922 if (!$componentId ||
1923 !in_array($componentName, ['Event', 'Membership'])
1925 return $contributionId;
1928 if ($componentName == 'Event') {
1929 $idName = 'participant_id';
1930 $componentTable = 'civicrm_participant';
1931 $paymentTable = 'civicrm_participant_payment';
1932 $source = ts('Online Event Registration');
1935 if ($componentName == 'Membership') {
1936 $idName = 'membership_id';
1937 $componentTable = 'civicrm_membership';
1938 $paymentTable = 'civicrm_membership_payment';
1939 $source = ts('Online Contribution');
1942 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1945 SELECT component.id as {$idName},
1946 componentPayment.contribution_id as contribution_id,
1947 contribution.source source,
1948 contribution.contribution_status_id as contribution_status_id,
1949 contribution.is_pay_later as is_pay_later
1950 FROM $componentTable component
1951 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1952 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1953 WHERE component.id = {$componentId}";
1955 $dao = CRM_Core_DAO
::executeQuery($query);
1957 while ($dao->fetch()) {
1958 if ($dao->contribution_id
&&
1959 $dao->is_pay_later
&&
1960 $dao->contribution_status_id
== $pendingStatusId &&
1961 strpos($dao->source
, $source) !== FALSE
1963 $contributionId = $dao->contribution_id
;
1967 return $contributionId;
1971 * Update contribution as well as related objects.
1973 * This function by-passes hooks - to address this - don't use this function.
1975 * @param array $params
1977 * @throws CRM_Core_Exception
1978 * @throws \CiviCRM_API3_Exception
1981 * Use api contribute.completetransaction
1982 * For failures use failPayment (preferably exposing by api in the process).
1985 public static function transitionComponents($params) {
1986 // get minimum required values.
1987 $contactId = $params['contact_id'] ??
NULL;
1988 $componentId = $params['component_id'] ??
NULL;
1989 $componentName = $params['componentName'] ??
NULL;
1990 $contributionId = $params['contribution_id'] ??
NULL;
1991 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
1993 // if we already processed contribution object pass previous status id.
1994 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
1996 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1998 // we process only ( Completed, Cancelled, or Failed ) contributions.
1999 if (!$contributionId ||
2000 !in_array($contributionStatusId, [
2001 array_search('Completed', $contributionStatuses),
2007 if (!$componentName ||
!$componentId) {
2008 // get the related component details.
2009 $componentDetails = self
::getComponentDetails($contributionId);
2012 $componentDetails['contact_id'] = $contactId;
2013 $componentDetails['component'] = $componentName;
2015 if ($componentName == 'event') {
2016 $componentDetails['participant'] = $componentId;
2019 $componentDetails['membership'] = $componentId;
2023 if (!empty($componentDetails['contact_id'])) {
2024 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2030 // do check for required ids.
2031 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2037 $input['component'] = $componentDetails['component'] ??
NULL;
2038 $ids['contribution'] = $contributionId;
2039 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2040 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2041 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2042 $ids['event'] = $componentDetails['event'] ??
NULL;
2043 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2044 $ids['contributionRecur'] = NULL;
2045 $ids['contributionPage'] = NULL;
2047 $contribution = new CRM_Contribute_BAO_Contribution();
2048 $contribution->id
= $ids['contribution'];
2049 $contribution->find();
2051 $contribution->loadRelatedObjects($input, $ids);
2053 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2054 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2055 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2057 $pledgeID = $oldStatus = NULL;
2058 $pledgePaymentIDs = [];
2059 if ($pledgePayment) {
2060 foreach ($pledgePayment as $key => $object) {
2061 $pledgePaymentIDs[] = $object->id
;
2063 $pledgeID = $pledgePayment[0]->pledge_id
;
2066 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2069 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2070 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2075 if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2077 // only pending contribution related object processed.
2078 if ($previousContriStatusId &&
2079 !in_array($contributionStatuses[$previousContriStatusId], [
2084 // this is case when we already processed contribution object.
2087 elseif (!$previousContriStatusId &&
2088 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2093 // this is case when we are going to process contribution object later.
2097 if (is_array($memberships)) {
2098 foreach ($memberships as $membership) {
2103 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2104 $membership->membership_type_id
,
2105 $membership->is_test
, $membership->id
2108 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2109 // this picks up membership type changes during renewals
2111 SELECT membership_type_id
2112 FROM civicrm_membership_log
2113 WHERE membership_id=$membership->id
2116 $dao = CRM_Core_DAO
::executeQuery($sql);
2117 if ($dao->fetch()) {
2118 if (!empty($dao->membership_type_id
)) {
2119 $membership->membership_type_id
= $dao->membership_type_id
;
2120 $membership->save();
2123 // else fall back to using current membership type
2124 // Figure out number of terms
2126 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2127 foreach ($lineitems as $lineitem) {
2128 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2129 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2131 // in case membership_num_terms comes through as null or zero
2132 $numterms = $numterms >= 1 ?
$numterms : 1;
2137 // CRM-15735-to update the membership status as per the contribution receive date
2139 $oldStatus = $membership->status_id
;
2140 if (!empty($params['receive_date'])) {
2141 $joinDate = $params['receive_date'];
2142 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2143 $membership->end_date
,
2144 $membership->join_date
,
2145 $params['receive_date'],
2147 $membership->membership_type_id
,
2150 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2151 $membership->save();
2154 if ($currentMembership) {
2155 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2156 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2157 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2160 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2163 //get the status for membership.
2164 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2166 $dates['join_date'],
2169 $membership->membership_type_id
,
2173 $formattedParams = [
2174 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2175 array_search('Current', $membershipStatuses)
2177 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2178 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2179 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2182 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2184 $membership->copyValues($formattedParams);
2185 $membership->save();
2187 //updating the membership log
2188 $membershipLog = [];
2189 $membershipLog = $formattedParams;
2190 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2191 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2193 $membershipLog['start_date'] = $logStartDate;
2194 $membershipLog['membership_id'] = $membership->id
;
2195 $membershipLog['modified_id'] = $membership->contact_id
;
2196 $membershipLog['modified_date'] = date('Ymd');
2197 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2199 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2201 //update related Memberships.
2202 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2204 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2205 $scheduledActivityID = CRM_Utils_Array
::value('id',
2206 civicrm_api3('Activity', 'Get',
2208 'source_record_id' => $membership->id
,
2209 'activity_type_id' => $activityType,
2210 'status_id' => 'Scheduled',
2213 'sort' => 'id DESC',
2218 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2219 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2220 if ($scheduledActivityID) {
2221 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2226 // track membership status change if any
2227 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2228 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2229 CRM_Activity_BAO_Activity
::addActivity($membership,
2230 'Change Membership Status',
2233 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2234 'source_contact_id' => $membershipLog['modified_id'],
2235 'priority_id' => 'Normal',
2240 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2246 $updatedStatusId = array_search('Registered', $participantStatuses);
2247 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2250 if ($pledgePayment) {
2251 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2258 * Returns all contribution related object ids.
2260 * @param $contributionId
2264 public static function getComponentDetails($contributionId) {
2265 $componentDetails = $pledgePayment = [];
2266 if (!$contributionId) {
2267 return $componentDetails;
2271 SELECT c.id as contribution_id,
2272 c.contact_id as contact_id,
2273 c.contribution_recur_id,
2274 mp.membership_id as membership_id,
2275 m.membership_type_id as membership_type_id,
2276 pp.participant_id as participant_id,
2277 p.event_id as event_id,
2278 pgp.id as pledge_payment_id
2279 FROM civicrm_contribution c
2280 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2281 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2282 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2283 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2284 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2285 WHERE c.id = $contributionId";
2287 $dao = CRM_Core_DAO
::executeQuery($query);
2288 $componentDetails = [];
2290 while ($dao->fetch()) {
2291 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2292 $componentDetails['contact_id'] = $dao->contact_id
;
2293 if ($dao->event_id
) {
2294 $componentDetails['event'] = $dao->event_id
;
2296 if ($dao->participant_id
) {
2297 $componentDetails['participant'] = $dao->participant_id
;
2299 if ($dao->membership_id
) {
2300 if (!isset($componentDetails['membership'])) {
2301 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2303 $componentDetails['membership'][] = $dao->membership_id
;
2304 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2306 if ($dao->pledge_payment_id
) {
2307 $pledgePayment[] = $dao->pledge_payment_id
;
2309 if ($dao->contribution_recur_id
) {
2310 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2314 if ($pledgePayment) {
2315 $componentDetails['pledge_payment'] = $pledgePayment;
2318 return $componentDetails;
2322 * @param int $contactId
2323 * @param bool $includeSoftCredit
2325 * @return null|string
2327 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2331 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2332 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2333 $liWhere = " AND i.financial_type_id IN (0)";
2334 if (!empty($financialTypes)) {
2335 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2336 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2338 $contactContributionsSQL = "
2339 SELECT contribution.id AS id
2340 FROM civicrm_contribution contribution
2341 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2342 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2346 $contactSoftCreditContributionsSQL = "
2347 SELECT contribution.id
2348 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2349 ON ( contribution.id = softContribution.contribution_id )
2350 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2351 $query = "SELECT count( x.id ) count FROM ( ";
2352 $query .= $contactContributionsSQL;
2354 if ($includeSoftCredit) {
2355 $query .= " UNION ";
2356 $query .= $contactSoftCreditContributionsSQL;
2361 return CRM_Core_DAO
::singleValueQuery($query);
2365 * Repeat a transaction as part of a recurring series.
2368 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2369 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2370 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2371 * and associated entities.
2372 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2373 * which updates the various entities and sends appropriate emails.
2375 * Gaps in the above (@todo)
2376 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2377 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2378 * 3) Repeat transaction duplicates rather than calls Order.create
2379 * 4) Use of payment.create still limited - completetransaction is more common.
2380 * 5) the template transaction is tricky - historically we used the first contribution
2381 * linked to a recurring contribution. More recently that was changed to be the most recent.
2382 * Ideally it would be an actual template - not a contribution used as a template which
2383 * would give more appropriate flexibility. Note line_items have an entity so that table
2384 * could be used for the line item template - the difficulty is the custom fields...
2385 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2386 * to load the membership(s) referred to via line items in the template transactions. Any other
2387 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2388 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2389 * - membership_payment record
2390 * - civicrm_membership.contribution_recur_id
2392 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2393 * of historical processors since this has been handled 'forever' - specifically for paypal.
2394 * albeit by an even nastier mechanism than the current input override.
2395 * The count is out on how correct related entities wind up in this case.
2397 * @param CRM_Contribute_BAO_Contribution $contribution
2398 * @param array $input
2399 * @param array $contributionParams
2401 * @return bool|array
2402 * @throws CiviCRM_API3_Exception
2404 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2405 if (!empty($contribution->id
)) {
2408 if (empty($contribution->id
)) {
2409 // Unclear why this would only be set for repeats.
2410 if (!empty($input['amount'])) {
2411 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2414 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2415 'id' => $contributionParams['contribution_recur_id'],
2417 if (!empty($recurringContribution['financial_type_id'])) {
2418 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2419 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2421 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2422 $contributionParams['contribution_recur_id'],
2423 array_intersect_key($contributionParams, [
2424 'total_amount' => TRUE,
2425 'financial_type_id' => TRUE,
2428 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2429 $contributionParams['status_id'] = 'Pending';
2431 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2432 // We permit the financial type to be overridden for single line items.
2433 // More comments on this are in getTemplateTransaction.
2434 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2437 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2439 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id'] as $fieldName) {
2440 if (isset($templateContribution[$fieldName])) {
2441 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2444 if (!empty($recurringContribution['campaign_id'])) {
2445 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2446 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2448 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2449 // Fall back on value from the previous contribution if not passed in as input
2450 // or loadable from the recurring contribution.
2451 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2453 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2455 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2456 //do not create CC or BCC emails or profile notifications.
2457 //The if is just to be safe. Not sure if we can ever arrive with this unset
2458 // but per CRM-19478 it seems it can be 'null'
2459 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2460 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2462 if (!empty($contribution->tax_amount
)) {
2463 $contributionParams['tax_amount'] = $contribution->tax_amount
;
2466 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2467 $contribution->id
= $createContribution['id'];
2468 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2469 self
::handleMembershipIDOverride($contribution->id
, $input);
2470 // Add new soft credit against current $contribution.
2471 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2472 return $createContribution;
2477 * Get individual id for onbehalf contribution.
2479 * @param int $contributionId
2481 * @param int $contributorId
2485 * containing organization id and individual id
2487 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2491 if (!$contributionId) {
2495 // fetch contributor id if null
2496 if (!$contributorId) {
2497 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2498 $contributionId, 'contact_id'
2502 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2503 $activityTypeId = array_search('Contribution', $activityTypeIds);
2505 if ($activityTypeId && $contributorId) {
2507 SELECT civicrm_activity_contact.contact_id
2508 FROM civicrm_activity_contact
2509 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2510 WHERE civicrm_activity.activity_type_id = %1
2511 AND civicrm_activity.source_record_id = %2
2512 AND civicrm_activity_contact.record_type_id = %3
2515 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2516 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2519 1 => [$activityTypeId, 'Integer'],
2520 2 => [$contributionId, 'Integer'],
2521 3 => [$sourceID, 'Integer'],
2524 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2526 // for on behalf contribution source is individual and contributor is organization
2527 if ($sourceContactId && $sourceContactId != $contributorId) {
2528 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2529 // get rel type id for employee of relation
2530 foreach ($relationshipTypeIds as $id => $typeVals) {
2531 if ($typeVals['name_a_b'] == 'Employee of') {
2532 $relationshipTypeId = $id;
2537 $rel = new CRM_Contact_DAO_Relationship();
2538 $rel->relationship_type_id
= $relationshipTypeId;
2539 $rel->contact_id_a
= $sourceContactId;
2540 $rel->contact_id_b
= $contributorId;
2541 if ($rel->find(TRUE)) {
2542 $ids['individual_id'] = $rel->contact_id_a
;
2543 $ids['organization_id'] = $rel->contact_id_b
;
2554 public static function getContributionDates() {
2555 $config = CRM_Core_Config
::singleton();
2556 $currentMonth = date('m');
2557 $currentDay = date('d');
2558 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2559 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2560 (int ) $config->fiscalYearStart
['d'] > $currentDay
2563 $year = date('Y') - 1;
2568 $year = ['Y' => $year];
2569 $yearDate = $config->fiscalYearStart
;
2570 $yearDate = array_merge($year, $yearDate);
2571 $yearDate = CRM_Utils_Date
::format($yearDate);
2573 $monthDate = date('Ym') . '01';
2579 'yearDate' => $yearDate,
2580 'monthDate' => $monthDate,
2585 * Load objects relations to contribution object.
2586 * Objects are stored in the $_relatedObjects property
2587 * In the first instance we are just moving functionality from BASEIpn -
2589 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2591 * Note that the unit test for the BaseIPN class tests this function
2593 * @param array $input
2594 * Input as delivered from Payment Processor.
2596 * Ids as Loaded by Payment Processor.
2597 * @param bool $loadAll
2598 * Load all related objects - even where id not passed in? (allows API to call this).
2601 * @throws CRM_Core_Exception
2603 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2604 // @todo deprecate this function - the steps should be
2605 // 1) add additional functions like 'getRelatedMemberships'
2606 // 2) switch all calls that refer to ->_relatedObjects to
2607 // using the helper functions
2608 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2609 // 4) make ->_relatedObjects protected
2610 // 5) hone up the individual functions to not use rely on this having been called
2611 // 6) deprecate like mad
2613 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2614 if (empty($ids['contact']) && isset($this->contact_id
)) {
2615 $ids['contact'] = $this->contact_id
;
2618 if (empty($this->_component
)) {
2619 if (!empty($ids['event'])) {
2620 $this->_component
= 'event';
2623 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2627 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2628 // refactoring than anything else, and has unit test coverage.
2629 if (empty($this->financial_type_id
)) {
2633 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2638 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2639 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2640 $this->contribution_page_id
,
2643 if ($paymentProcessorID) {
2644 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2648 $ids['contributionType'] = $this->financial_type_id
;
2649 $ids['financialType'] = $this->financial_type_id
;
2650 if ($this->contribution_page_id
) {
2651 $ids['contributionPage'] = $this->contribution_page_id
;
2654 $this->loadRelatedEntitiesByID($ids);
2656 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2657 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2660 if (!empty($ids['pledge_payment'])) {
2661 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2662 if (empty($paymentID)) {
2665 $payment = new CRM_Pledge_BAO_PledgePayment();
2666 $payment->id
= $paymentID;
2667 if (!$payment->find(TRUE)) {
2668 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2670 $this->_relatedObjects
['pledge_payment'][] = $payment;
2674 // These are probably no longer accessed from anywhere
2675 // @todo remove this line, after ensuring not used.
2676 $ids = $this->loadRelatedMembershipObjects($ids);
2678 if ($this->_component
!= 'contribute') {
2679 // we are in event mode
2680 // make sure event exists and is valid
2681 $event = new CRM_Event_BAO_Event();
2682 $event->id
= $ids['event'];
2683 if ($ids['event'] &&
2686 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2689 $this->_relatedObjects
['event'] = &$event;
2691 $participant = new CRM_Event_BAO_Participant();
2692 $participant->id
= $ids['participant'];
2693 if ($ids['participant'] &&
2694 !$participant->find(TRUE)
2696 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2698 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2700 $this->_relatedObjects
['participant'] = &$participant;
2702 // get the payment processor id from event - this is inaccurate see CRM-16923
2703 // in future we should look at throwing an exception here rather than an dubious guess.
2704 if (!$paymentProcessorID) {
2705 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2706 if ($paymentProcessorID) {
2707 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2712 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2713 if (!empty($relatedContact['individual_id'])) {
2714 $ids['related_contact'] = $relatedContact['individual_id'];
2717 if ($paymentProcessorID) {
2718 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2719 $this->is_test ?
'test' : 'live'
2721 $ids['paymentProcessor'] = $paymentProcessorID;
2722 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2725 // Add contribution id to $ids. CRM-20401
2726 $ids['contribution'] = $this->id
;
2731 * Create array of message information - ie. return html version, txt version, to field
2733 * @param array $input
2734 * Incoming information.
2735 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2736 * just check presence of recur object but maintaining legacy approach
2739 * IDs of related objects.
2740 * @param array $values
2741 * Any values that may have already been compiled by calling process.
2742 * This is augmented by values 'gathered' by gatherMessageValues
2743 * @param bool $returnMessageText
2744 * Distinguishes between whether to send message or return.
2745 * message text. We are working towards this function ALWAYS returning message text & calling
2746 * function doing emails / pdfs with it
2752 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2753 $this->loadRelatedObjects($input, $ids);
2755 if (empty($this->_component
)) {
2756 $this->_component
= $input['component'] ??
NULL;
2759 //not really sure what params might be passed in but lets merge em into values
2760 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2761 $values['is_email_receipt'] = !$returnMessageText;
2762 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text', 'pay_later_receipt'] as $fld) {
2763 if (!empty($input[$fld])) {
2764 $values[$fld] = $input[$fld];
2768 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2769 //what does recur 'mean here - to do with payment processor return functionality but
2770 // what is the importance
2771 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2772 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2774 $entityID = $entity = NULL;
2775 if (isset($ids['contribution'])) {
2776 $entity = 'contribution';
2777 $entityID = $ids['contribution'];
2779 if (!empty($ids['membership'])) {
2780 //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
2781 // 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
2782 // line having loaded an array
2783 $ids['membership'] = (array) $ids['membership'];
2784 $entity = 'membership';
2785 $entityID = $ids['membership'][0];
2788 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2789 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2790 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2792 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2793 //direct mode showing billing block, so use directIPN for temporary
2794 $template->assign('contributeMode', 'directIPN');
2797 // todo remove strtolower - check consistency
2798 if (strtolower($this->_component
) == 'event') {
2799 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2800 $values['event'] = [];
2802 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2804 //get location details
2806 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2807 'entity_table' => 'civicrm_event',
2809 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2812 'entity_table' => 'civicrm_event',
2813 'entity_id' => $ids['event'],
2814 'module' => 'CiviEvent',
2817 list($custom_pre_id,
2819 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2821 $values['custom_pre_id'] = $custom_pre_id;
2822 $values['custom_post_id'] = $custom_post_ids;
2823 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2824 //and cases involving status updation through ipn
2825 // whatever that means!
2826 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2827 // perhaps we should throw an e-notice if amount is set & force total_amount?
2828 if (!empty($input['amount'])) {
2829 $values['totalAmount'] = $input['amount'];
2831 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2832 if ($values['event']['is_email_confirm']) {
2833 $values['is_email_receipt'] = 1;
2836 if (!empty($ids['contribution'])) {
2837 $values['contributionId'] = $ids['contribution'];
2840 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2841 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2845 $values['contribution_id'] = $this->id
;
2846 if (!empty($ids['related_contact'])) {
2847 $values['related_contact'] = $ids['related_contact'];
2848 if (isset($ids['onbehalf_dupe_alert'])) {
2849 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2852 'contact_id' => $ids['contact'],
2853 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2854 'Home', 'id', 'name'
2857 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2858 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display'] ??
NULL);
2861 if ($this->is_test
) {
2864 if (!empty($this->_relatedObjects
['membership'])) {
2865 foreach ($this->_relatedObjects
['membership'] as $membership) {
2866 if ($membership->id
) {
2867 $values['membership_id'] = $membership->id
;
2868 $values['isMembership'] = TRUE;
2869 $values['membership_assign'] = TRUE;
2871 // need to set the membership values here
2872 $template->assign('membership_name',
2873 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2875 $template->assign('mem_start_date', $membership->start_date
);
2876 $template->assign('mem_join_date', $membership->join_date
);
2877 $template->assign('mem_end_date', $membership->end_date
);
2878 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2879 $template->assign('mem_status', $membership_status);
2880 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2881 $values['is_pay_later'] = 1;
2883 // Pass amount to floatval as string '0.00' is considered a
2884 // valid amount and includes Fee section in the mail.
2885 if (isset($values['amount'])) {
2886 $values['amount'] = floatval($values['amount']);
2889 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2890 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2891 $template->assign('cancelSubscriptionUrl', $url);
2892 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2893 $template->assign('updateSubscriptionBillingUrl', $url);
2894 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2895 $template->assign('updateSubscriptionUrl', $url);
2898 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2901 // otherwise if its about sending emails, continue sending without return, as we
2902 // don't want to exit the loop.
2907 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2913 * Gather values for contribution mail - this function has been created
2914 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2915 * Values related to the contribution in question are gathered
2917 * @param array $input
2918 * Input into function (probably from payment processor).
2919 * @param array $values
2921 * The set of ids related to the input.
2924 * @throws \CRM_Core_Exception
2926 public function _gatherMessageValues($input, &$values, $ids = []) {
2927 // set display address of contributor
2928 $values['billingName'] = '';
2929 if ($this->address_id
) {
2930 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
2931 $addressDetails = reset($addressDetails);
2932 $values['billingName'] = $addressDetails['name'] ??
'';
2934 // Else we assign the billing address of the contribution contact.
2936 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
2937 $addressDetails = reset($addressDetails);
2939 $values['address'] = $addressDetails['display'] ??
'';
2941 if ($this->_component
=== 'contribute') {
2942 //get soft contributions
2943 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2944 if (!empty($softContributions)) {
2945 // For pcp soft credit, there is no 'soft_credit' member it comes
2946 // back in different array members, but shortly after returning from
2947 // this function it calls _assignMessageVariablesToTemplate which does
2948 // its own lookup of any pcp soft credit, so we can skip it here.
2949 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
2951 if (isset($this->contribution_page_id
)) {
2952 // This is a call we want to use less, in favour of loading related objects.
2953 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2954 if ($this->contribution_page_id
) {
2955 // This is precautionary as there are some legacy flows, but it should really be
2957 if (!isset($this->_relatedObjects
['contributionPage'])) {
2958 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2960 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
2963 // no contribution page -probably back office
2965 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2966 $values['title'] = 'Contribution';
2968 // set lineItem for contribution
2970 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2971 if (!empty($lineItems)) {
2972 $firstLineItem = reset($lineItems);
2974 if (!empty($firstLineItem['price_set_id'])) {
2975 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
2976 'id' => $firstLineItem['price_set_id'],
2977 'return' => 'is_quick_config, id',
2979 $values['priceSetID'] = $priceSet['id'];
2981 foreach ($lineItems as &$eachItem) {
2982 if (isset($this->_relatedObjects
['membership'])
2983 && is_array($this->_relatedObjects
['membership'])
2984 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2985 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
2986 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
2987 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
2989 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2990 // However, that does create upgrade pain so would be better to be phased in.
2991 $values['useForMember'] = empty($priceSet['is_quick_config']);
2993 $values['lineItem'][0] = $lineItems;
2997 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3001 // if this is onbehalf of contribution then set related contact
3002 if (!empty($relatedContact['individual_id'])) {
3003 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3007 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3010 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3013 foreach ($groupTree as $key => $group) {
3014 if ($key === 'info') {
3018 foreach ($group['fields'] as $k => $customField) {
3019 $groupLabel = $group['title'];
3020 if (!empty($customField['customValue'])) {
3021 foreach ($customField['customValue'] as $customFieldValues) {
3022 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3027 $values['customGroup'] = $customGroup;
3029 $values['is_pay_later'] = $this->is_pay_later
;
3035 * Assign message variables to template but try to break the habit.
3037 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3038 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3039 * multiple recurring payments for processors like IATS that use tokens.
3041 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3042 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3043 * Note we send directly from this function in some cases because it is only partly refactored.
3045 * Don't call this function directly as the signature will change.
3049 * @param bool $returnMessageText
3053 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3054 // @todo - this should have a better separation of concerns - ie.
3055 // gatherMessageValues should build an array of values to be assigned to the template
3056 // and this function should assign them (assigning null if not set).
3057 // the way the pcpParams & honor Params section works is a baby-step towards this.
3058 $template = CRM_Core_Smarty
::singleton();
3059 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3060 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3061 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3062 $template->assign('billingName', $values['billingName']);
3064 // For some unit tests contribution cannot contain paymentProcessor information
3065 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3066 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3068 //assign honor information to receipt message
3069 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3072 'soft_credit_type' => NULL,
3073 'honor_block_is_active' => NULL,
3075 if (isset($softRecord['soft_credit'])) {
3076 //if id of contribution page is present
3077 if (!empty($values['id'])) {
3078 $values['honor'] = [
3079 'honor_profile_values' => [],
3080 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3081 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3084 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3085 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3088 //offline contribution
3089 $softCreditTypes = $softCredits = [];
3090 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3091 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3092 $softCredits[$key] = [
3093 'Name' => $softCredit['contact_name'],
3094 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3097 $template->assign('softCreditTypes', $softCreditTypes);
3098 $template->assign('softCredits', $softCredits);
3102 $dao = new CRM_Contribute_DAO_ContributionProduct();
3103 $dao->contribution_id
= $this->id
;
3104 if ($dao->find(TRUE)) {
3105 $premiumId = $dao->product_id
;
3106 $template->assign('option', $dao->product_option
);
3108 $productDAO = new CRM_Contribute_DAO_Product();
3109 $productDAO->id
= $premiumId;
3110 $productDAO->find(TRUE);
3111 $template->assign('selectPremium', TRUE);
3112 $template->assign('product_name', $productDAO->name
);
3113 $template->assign('price', $productDAO->price
);
3114 $template->assign('sku', $productDAO->sku
);
3116 $template->assign('title', $values['title'] ??
NULL);
3117 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3118 if (!$values['amount'] && isset($this->total_amount
)) {
3119 $values['amount'] = $this->total_amount
;
3124 'pcp_display_in_roll' => NULL,
3125 'pcp_roll_nickname' => NULL,
3126 'pcp_personal_note' => NULL,
3130 if (strtolower($this->_component
) == 'contribute') {
3132 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3133 $softDAO->contribution_id
= $this->id
;
3134 if ($softDAO->find(TRUE)) {
3135 $pcpParams['pcpBlock'] = TRUE;
3136 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3137 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3138 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3140 //assign the pcp page title for email subject
3141 $pcpDAO = new CRM_PCP_DAO_PCP();
3142 $pcpDAO->id
= $softDAO->pcp_id
;
3143 if ($pcpDAO->find(TRUE)) {
3144 $pcpParams['title'] = $pcpDAO->title
;
3148 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3149 $template->assign($templateKey, $templateValue);
3152 if ($this->financial_type_id
) {
3153 $values['financial_type_id'] = $this->financial_type_id
;
3156 $template->assign('trxn_id', $this->trxn_id
);
3157 $template->assign('receive_date',
3158 CRM_Utils_Date
::processDate($this->receive_date
)
3160 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3161 $template->assign('action', $this->is_test ?
1024 : 1);
3162 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3163 $template->assign('is_monetary', 1);
3164 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3165 $template->assign('currency', $this->currency
);
3166 $template->assign('address', CRM_Utils_Address
::format($input));
3167 if (!empty($values['customGroup'])) {
3168 $template->assign('customGroup', $values['customGroup']);
3170 if (!empty($values['softContributions'])) {
3171 $template->assign('softContributions', $values['softContributions']);
3173 if ($this->_component
== 'event') {
3174 $template->assign('title', $values['event']['title']);
3175 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3177 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3178 $viewRoles[] = $participantRoles[$v];
3180 $values['event']['participant_role'] = implode(', ', $viewRoles);
3181 $template->assign('event', $values['event']);
3182 $template->assign('participant', $values['participant']);
3183 $template->assign('location', $values['location']);
3184 $template->assign('customPre', $values['custom_pre_id']);
3185 $template->assign('customPost', $values['custom_post_id']);
3188 if ($this->_relatedObjects
['participant']->is_test
) {
3192 $values['params'] = [];
3193 //to get email of primary participant.
3194 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3195 $primaryAmount[] = [
3196 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3197 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3199 //build an array of cId/pId of participants
3200 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3201 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3202 //send receipt to additional participant if exists
3203 if (count($additionalIDs)) {
3204 $template->assign('isPrimary', 0);
3205 $template->assign('customProfile', NULL);
3206 //set additionalParticipant true
3207 $values['params']['additionalParticipant'] = TRUE;
3208 foreach ($additionalIDs as $pId => $cId) {
3210 //to change the status pending to completed
3211 $additional = new CRM_Event_DAO_Participant();
3212 $additional->id
= $pId;
3213 $additional->contact_id
= $cId;
3214 $additional->find(TRUE);
3215 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3216 $additional->status_id
= 1;
3217 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3218 //if additional participant dont have email
3220 if (!$additionalParticipantInfo) {
3221 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3224 'label' => $additional->fee_level
,
3225 'amount' => $additional->fee_amount
,
3227 $primaryAmount[] = [
3228 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3229 'amount' => $additional->fee_amount
,
3231 $additional->save();
3232 $template->assign('amount', $amount);
3233 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3237 //build an array of custom profile and assigning it to template
3238 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3240 if (count($customProfile)) {
3241 $template->assign('customProfile', $customProfile);
3244 // for primary contact
3245 $values['params']['additionalParticipant'] = FALSE;
3246 $template->assign('isPrimary', 1);
3247 $template->assign('amount', $primaryAmount);
3248 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3249 if ($this->payment_instrument_id
) {
3250 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3251 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3253 // carry paylater, since we did not created billing,
3254 // so need to pull email from primary location, CRM-4395
3255 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3261 * Check whether payment processor supports
3262 * cancellation of contribution subscription
3264 * @param int $contributionId
3267 * @param bool $isNotCancelled
3271 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3272 $cacheKeyString = "$contributionId";
3273 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3275 static $supportsCancel = [];
3277 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3278 $supportsCancel[$cacheKeyString] = FALSE;
3279 $isCancelled = FALSE;
3281 if ($isNotCancelled) {
3282 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3285 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3286 if (!empty($paymentObject)) {
3287 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3290 return $supportsCancel[$cacheKeyString];
3294 * Check whether subscription is already cancelled.
3296 * @param int $contributionId
3300 * contribution status
3302 public static function isSubscriptionCancelled($contributionId) {
3304 SELECT cr.contribution_status_id
3305 FROM civicrm_contribution_recur cr
3306 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3307 WHERE con.id = %1 LIMIT 1";
3308 $params = [1 => [$contributionId, 'Integer']];
3309 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3310 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3311 if ($status == 'Cancelled') {
3318 * Create all financial accounts entry.
3320 * @param array $params
3321 * Contribution object, line item array and params for trxn.
3324 * @param array $financialTrxnValues
3326 * @return null|\CRM_Core_BAO_FinancialTrxn
3328 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3329 $skipRecords = $update = $return = $isRelatedId = FALSE;
3330 $isUpdate = !empty($params['prevContribution']);
3332 $additionalParticipantId = [];
3333 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3334 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3336 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3337 $entityId = $params['participant_id'];
3338 $entityTable = 'civicrm_participant';
3339 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3341 elseif (!empty($params['membership_id'])) {
3342 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3343 // are created off one contribution should be handled elsewhere
3344 $entityId = $params['membership_id'];
3345 $entityTable = 'civicrm_membership';
3348 $entityId = $params['contribution']->id
;
3349 $entityTable = 'civicrm_contribution';
3352 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3353 $isRelatedId = TRUE;
3356 $entityID[] = $entityId;
3357 if (!empty($additionalParticipantId)) {
3358 $entityID +
= $additionalParticipantId;
3360 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3361 if (empty($params['prevContribution'])) {
3365 $statusId = $params['contribution']->contribution_status_id
;
3367 // build line item array if its not set in $params
3368 if (empty($params['line_item']) ||
$additionalParticipantId) {
3369 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3372 if ($contributionStatus != 'Failed' &&
3373 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3375 $skipRecords = TRUE;
3380 if (in_array($contributionStatus, $pendingStatus)) {
3381 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3382 $params['financial_type_id'],
3383 'Accounts Receivable Account is'
3386 elseif (!empty($params['payment_processor'])) {
3387 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3388 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3389 'id' => $params['payment_processor'],
3390 'return' => 'payment_instrument_id',
3393 elseif (!empty($params['payment_instrument_id'])) {
3394 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3396 // dev/financial#160 - If this is a contribution update, also check for an existing payment_instrument_id.
3397 elseif ($isUpdate && $params['prevContribution']->payment_instrument_id
) {
3398 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount((int) $params['prevContribution']->payment_instrument_id
);
3401 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3402 $queryParams = [1 => [$relationTypeId, 'Integer']];
3403 $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);
3406 $totalAmount = $params['total_amount'] ??
NULL;
3407 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3408 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3410 //build financial transaction params
3412 'contribution_id' => $params['contribution']->id
,
3413 'to_financial_account_id' => $params['to_financial_account_id'],
3414 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3415 'total_amount' => $totalAmount,
3416 'fee_amount' => $params['fee_amount'] ??
NULL,
3417 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3418 'currency' => $params['contribution']->currency
,
3419 'trxn_id' => $params['contribution']->trxn_id
,
3420 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3421 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3422 // this should really default to completed (after discussion).
3423 'status_id' => $statusId,
3424 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3425 'check_number' => $params['check_number'] ??
NULL,
3426 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3427 'card_type_id' => $params['card_type_id'] ??
NULL,
3429 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3430 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3431 if (isset($params['refund_trxn_id'])) {
3432 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3433 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3436 //CRM-16259, set is_payment flag for non pending status
3437 if (!in_array($contributionStatus, $pendingStatus)) {
3438 $trxnParams['is_payment'] = 1;
3440 if (!empty($params['payment_processor'])) {
3441 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3444 if (isset($fromFinancialAccountId)) {
3445 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3448 // consider external values passed for recording transaction entry
3449 if (!empty($financialTrxnValues)) {
3450 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3452 if (empty($trxnParams['payment_processor_id'])) {
3453 unset($trxnParams['payment_processor_id']);
3456 $params['trxnParams'] = $trxnParams;
3460 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3461 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3462 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3463 if (!isset($params['trxnParams']['trxn_id'])) {
3464 // Actually I have no idea why we are overwriting any values from the previous contribution.
3465 // (filling makes sense to me). However, only protecting this value as I really really know we
3466 // don't want this one overwritten.
3468 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3470 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3472 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3473 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3474 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3476 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3477 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3480 //if financial type is changed
3481 if (!empty($params['financial_type_id']) &&
3482 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3484 $accountRelationship = 'Income Account is';
3485 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3486 $accountRelationship = 'Deferred Revenue Account is';
3488 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3489 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3490 if ($oldFinancialAccount != $newFinancialAccount) {
3491 $params['total_amount'] = 0;
3492 // If we have a fee amount set reverse this as well.
3493 if (isset($params['fee_amount'])) {
3494 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3496 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3497 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3498 $params['prevContribution']->financial_type_id
, $accountRelationship);
3501 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3502 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3503 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3506 self
::updateFinancialAccounts($params, 'changeFinancialType');
3507 $params['skipLineItem'] = FALSE;
3508 foreach ($params['line_item'] as &$lineItems) {
3509 foreach ($lineItems as &$line) {
3510 $line['financial_type_id'] = $params['financial_type_id'];
3513 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3514 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3515 $params['financial_account_id'] = $newFinancialAccount;
3516 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3517 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3518 if (isset($params['fee_amount'])) {
3519 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3521 self
::updateFinancialAccounts($params);
3522 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3523 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3525 $params['deferred_financial_account_id'] = $newFinancialAccount;
3529 //Update contribution status
3530 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3531 if (!isset($params['refund_trxn_id'])) {
3532 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3533 // gets preference over another so I am only 'protecting' a very specific tested flow
3534 // and letting natural justice take care of the rest.
3535 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3537 if (!empty($params['contribution_status_id']) &&
3538 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3540 //Update Financial Records
3541 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3542 if ($callUpdateFinancialAccounts) {
3543 self
::updateFinancialAccounts($params, 'changedStatus');
3544 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3549 // change Payment Instrument for a Completed contribution
3550 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3551 // instrument is null and now new payment instrument is added along with the payment
3552 if (!$params['contribution']->payment_instrument_id
) {
3553 $params['contribution']->find(TRUE);
3555 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3556 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3558 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3559 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3562 //if Change contribution amount
3563 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3564 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3565 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3566 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3567 if (isset($totalAmount) &&
3568 $totalAmount != $params['prevContribution']->total_amount
3570 //Update Financial Records
3571 $params['trxnParams']['from_financial_account_id'] = NULL;
3572 self
::updateFinancialAccounts($params, 'changedAmount');
3573 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3578 // Looks like we might have a data correction update.
3579 // This would be a case where a transaction id has been entered but it is incorrect &
3580 // the person goes back in & fixes it, as opposed to a new transaction.
3581 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3582 // the data fix scenario.
3584 if (isset($params['refund_trxn_id'])) {
3585 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3586 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3587 civicrm_api3('FinancialTrxn', 'create', [
3588 'id' => $refundIDs['financialTrxnId'],
3589 'trxn_id' => $params['refund_trxn_id'],
3593 $cardType = $params['card_type_id'] ??
NULL;
3594 $panTruncation = $params['pan_truncation'] ??
NULL;
3595 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3600 // records finanical trxn and entity financial trxn
3601 // also make it available as return value
3602 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3603 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3604 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3605 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3606 $params['entity_id'] = $financialTxn->id
;
3607 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3608 self
::$_trxnIDs[] = $financialTxn->id
;
3612 // record line items and financial items
3613 if (empty($params['skipLineItem'])) {
3614 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3617 // create batch entry if batch_id is passed and
3618 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3619 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3621 'batch_id' => $params['batch_id'],
3622 'entity_table' => 'civicrm_financial_trxn',
3623 'entity_id' => $financialTxn->id
,
3625 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3628 // when a fee is charged
3629 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3630 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3633 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3634 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3636 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3637 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3638 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3640 unset($params['line_item']);
3641 self
::$_trxnIDs = NULL;
3646 * Update all financial accounts entry.
3648 * @param array $params
3649 * Contribution object, line item array and params for trxn.
3651 * @param string $context
3654 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3655 * adds unpredictability.
3658 public static function updateFinancialAccounts(&$params, $context = NULL) {
3660 $inputParams = $params;
3661 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3663 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3664 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3665 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3668 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3669 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3670 $params['entity_id'] = $trxn->id
;
3672 $itemParams['entity_table'] = 'civicrm_line_item';
3673 $trxnIds['id'] = $params['entity_id'];
3674 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3675 foreach ($params['line_item'] as $fieldId => $fields) {
3676 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3681 * Is this contribution status a reversal.
3683 * If so we would expect to record a negative value in the financial_trxn table.
3685 * @param int $status_id
3689 public static function isContributionStatusNegative($status_id) {
3690 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3691 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3695 * Check status validation on update of a contribution.
3697 * @param array $values
3698 * Previous form values before submit.
3700 * @param array $fields
3701 * The input form values.
3703 * @param array $errors
3708 public static function checkStatusValidation($values, &$fields, &$errors) {
3709 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3710 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3711 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3715 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3717 'Cancelled' => ['Completed', 'Refunded'],
3718 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3719 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3720 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3721 'Refunded' => ['Cancelled', 'Completed'],
3722 'Partially paid' => ['Completed'],
3723 'Pending refund' => ['Completed', 'Refunded'],
3724 'Failed' => ['Pending'],
3727 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3728 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3730 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3731 1 => $contributionStatuses[$values['contribution_status_id']],
3732 2 => $contributionStatuses[$fields['contribution_status_id']],
3738 * Delete contribution of contact.
3740 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3742 * @param int $contactId
3746 public static function deleteContactContribution($contactId) {
3747 $contribution = new CRM_Contribute_DAO_Contribution();
3748 $contribution->contact_id
= $contactId;
3749 $contribution->find();
3750 while ($contribution->fetch()) {
3751 self
::deleteContribution($contribution->id
);
3756 * Get options for a given contribution field.
3758 * @param string $fieldName
3759 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3760 * @param array $props whatever is known about this dao object.
3762 * @return array|bool
3763 * @see CRM_Core_DAO::buildOptions
3766 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3767 $className = __CLASS__
;
3769 if (isset($props['orderColumn'])) {
3770 $params['orderColumn'] = $props['orderColumn'];
3772 switch ($fieldName) {
3773 // This field is not part of this object but the api supports it
3774 case 'payment_processor':
3775 $className = 'CRM_Contribute_BAO_ContributionPage';
3776 // Filter results by contribution page
3777 if (!empty($props['contribution_page_id'])) {
3778 $page = civicrm_api('contribution_page', 'getsingle', [
3780 'id' => ($props['contribution_page_id']),
3782 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3783 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3787 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3788 case 'honor_type_id':
3789 $className = 'CRM_Contribute_BAO_ContributionSoft';
3790 $fieldName = 'soft_credit_type_id';
3791 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3794 case 'contribution_status_id':
3795 if ($context !== 'validate') {
3796 $params['condition'] = "v.name <> 'Template'";
3799 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3803 * Validate financial type.
3805 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3807 * @param int $financialTypeId
3808 * Financial Type id.
3810 * @param string $relationName
3812 * @return array|bool
3814 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3815 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3817 if (!$financialAccount) {
3818 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3824 * @param int $targetCid
3825 * @param $activityType
3826 * @param string $title
3827 * @param int $contributionId
3828 * @param string $totalAmount
3829 * @param string $currency
3830 * @param string $trxn_date
3832 * @throws \CRM_Core_Exception
3833 * @throws \CiviCRM_API3_Exception
3835 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3836 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3837 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3838 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3839 // source record id would be the contribution id
3840 $srcRecId = $contributionId;
3844 'source_contact_id' => $targetCid,
3845 'source_record_id' => $srcRecId,
3846 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3847 'subject' => $subject,
3848 'activity_date_time' => $date,
3849 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3850 'skipRecentView' => TRUE,
3853 // create activity with target contacts
3854 $session = CRM_Core_Session
::singleton();
3855 $id = $session->get('userID');
3857 $activityParams['source_contact_id'] = $id;
3858 $activityParams['target_contact_id'][] = $targetCid;
3860 civicrm_api3('Activity', 'create', $activityParams);
3864 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3867 * @param string $component
3868 * @param bool $getTrxnInfo
3872 * @throws \CRM_Core_Exception
3873 * @throws \CiviCRM_API3_Exception
3875 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3876 // @todo deprecate passing in component - always call with contribution.
3877 if ($component == 'event') {
3878 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3880 if (!$contributionId) {
3881 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3882 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3883 $id = $primaryParticipantId;
3885 if (!$contributionId) {
3890 elseif ($component == 'membership') {
3891 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3894 $contributionId = $id;
3897 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3898 // but need to unpick the whole trxn_id it's returning first.
3899 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3900 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3902 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3903 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3905 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3907 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3909 $contribution = civicrm_api3('Contribution', 'getsingle', [
3910 'id' => $contributionId,
3914 'contribution_status_id',
3915 'financial_type_id',
3919 $info['payLater'] = $contribution['is_pay_later'];
3920 $info['contribution_status'] = $contribution['contribution_status'];
3921 $info['currency'] = $contribution['currency'];
3923 $info['total'] = $total;
3924 $info['paid'] = $total - $paymentBalance;
3925 $info['balance'] = $paymentBalance;
3927 $info['component'] = $component;
3928 if ($getTrxnInfo && $baseTrxnId) {
3929 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
3932 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
3937 * Get the outstanding balance on a contribution.
3939 * @param int $contributionId
3940 * @param float $contributionTotal
3941 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
3945 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
3946 if ($contributionTotal === NULL) {
3947 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3950 return (float) CRM_Utils_Money
::subtractCurrencies(
3952 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
3953 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
3958 * Get the tax amount (misnamed function).
3960 * @param array $params
3963 * @throws \CiviCRM_API3_Exception
3965 protected static function checkTaxAmount($params) {
3966 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3968 // Update contribution.
3969 if (!empty($params['id'])) {
3970 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
3971 // there are no tax implications - early return.
3972 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
3975 if (empty($params['prevContribution'])) {
3976 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
3979 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
3980 if (!isset($params[$field])) {
3981 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
3982 // Tax amount gets added back on later....
3983 $params['total_amount'] = $params['prevContribution']->total_amount
-
3984 $params['prevContribution']->tax_amount
;
3987 $params[$field] = $params['prevContribution']->$field;
3988 if ($params[$field] != $params['prevContribution']->$field) {
3994 self
::calculateMissingAmountParams($params, $params['id']);
3995 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
3996 // Assign tax Amount on update of contribution
3997 if (!empty($params['prevContribution']->tax_amount
)) {
3998 $params['tax_amount'] = 'null';
3999 foreach ($params['line_item'] as $setID => $priceField) {
4000 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4001 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4008 // New Contribution and update of contribution with tax rate financial type
4009 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4010 empty($params['skipLineItem'])) {
4011 $taxRateParams = $taxRates[$params['financial_type_id']];
4012 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4013 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4015 foreach ($params['line_item'] as $setID => $priceField) {
4016 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4017 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4020 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4022 elseif (isset($params['api.line_item.create'])) {
4023 // Update total amount of contribution using lineItem
4024 $taxAmountArray = [];
4025 foreach ($params['api.line_item.create'] as $key => $value) {
4026 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4027 $taxRate = $taxRates[$value['financial_type_id']];
4028 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4029 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4032 $params['tax_amount'] = array_sum($taxAmountArray);
4033 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4040 * Check financial type validation on update of a contribution.
4042 * @param int $financialTypeId
4043 * Value of latest Financial Type.
4045 * @param int $contributionId
4048 * @param array $errors
4053 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4054 if (!empty($financialTypeId)) {
4055 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4056 if ($oldFinancialTypeId == $financialTypeId) {
4060 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4062 '1' => [$contributionId, 'Integer'],
4064 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4065 if ($result->N
> 1) {
4066 $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.');
4071 * Update related pledge payment payments.
4073 * This function has been refactored out of the back office contribution form and may
4074 * still overlap with other functions.
4076 * @param string $action
4077 * @param int $pledgePaymentID
4078 * @param int $contributionID
4079 * @param bool $adjustTotalAmount
4080 * @param float $total_amount
4081 * @param float $original_total_amount
4082 * @param int $contribution_status_id
4083 * @param int $original_contribution_status_id
4085 public static function updateRelatedPledge(
4091 $original_total_amount,
4092 $contribution_status_id,
4093 $original_contribution_status_id
4095 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4099 if ($pledgePaymentID) {
4100 //store contribution id in payment record.
4101 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4104 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4111 if (!$pledgePaymentID) {
4114 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4120 $updatePledgePaymentStatus = FALSE;
4122 // If either the status or the amount has changed we update the pledge status.
4123 if ($action & CRM_Core_Action
::ADD
) {
4124 $updatePledgePaymentStatus = TRUE;
4126 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4127 ($original_total_amount != $total_amount))
4129 $updatePledgePaymentStatus = TRUE;
4132 if ($updatePledgePaymentStatus) {
4133 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4135 $contribution_status_id,
4144 * Is there only one line item attached to the contribution.
4150 * @throws \CiviCRM_API3_Exception
4152 public static function isSingleLineItem($id) {
4153 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4154 return ($lineItemCount == 1);
4158 * Complete an order.
4160 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4162 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4164 * Moving it out of the BaseIPN class is just the first step.
4166 * @param array $input
4168 * @param \CRM_Contribute_BAO_Contribution $contribution
4169 * @param bool $isPostPaymentCreate
4170 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4171 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4172 * transitioning related elements).
4175 * @throws \CRM_Core_Exception
4176 * @throws \CiviCRM_API3_Exception
4178 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4179 $transaction = new CRM_Core_Transaction();
4180 // @todo see if we even need this - it's used further down to create an activity
4181 // but the BAO layer should create that - we just need to add a test to cover it & can
4182 // maybe remove $ids altogether.
4183 $contributionContactID = $ids['related_contact'];
4184 $participantID = $ids['participant'];
4185 $recurringContributionID = $ids['contributionRecur'];
4187 // Unset ids just to make it clear it's not used again.
4189 // The previous details are used when calculating line items so keep it before any code that 'does something'
4190 if (!empty($contribution->id
)) {
4191 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4193 $inputContributionWhiteList = [
4198 'payment_instrument_id',
4203 'contribution_status_id',
4206 'financial_type_id',
4209 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4211 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4213 $contributionParams = array_merge([
4214 'contribution_status_id' => $completedContributionStatusID,
4215 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4218 $contributionParams['payment_processor'] = $paymentProcessorId;
4220 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4221 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4224 if ($recurringContributionID) {
4225 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4227 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4229 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4230 $contributionID = (int) $contribution->id
;
4232 if ($input['component'] == 'contribute') {
4233 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4234 self
::updateMembershipBasedOnCompletionOfContribution(
4241 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4242 $participantParams['id'] = $participantID;
4243 $participantParams['status_id'] = 'Registered';
4244 civicrm_api3('Participant', 'create', $participantParams);
4248 $contributionParams['id'] = $contributionID;
4249 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4251 if (!$contributionResult) {
4252 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4255 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4257 CRM_Core_Error
::debug_log_message('Contribution record updated successfully');
4258 $transaction->commit();
4260 // @todo - check if Contribution::create does this, test, remove.
4261 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4262 $contributionParams['contribution_status_id'], $input['amount']);
4264 // create an activity record
4265 // @todo - check if Contribution::create does this, test, remove.
4266 if ($input['component'] == 'contribute') {
4268 $targetContactID = NULL;
4269 if ($contributionContactID) {
4270 $targetContactID = $contribution->contact_id
;
4271 $contribution->contact_id
= $contributionContactID;
4273 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID);
4276 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4277 civicrm_api3('Contribution', 'sendconfirmation', [
4278 'id' => $contributionID,
4279 'payment_processor_id' => $paymentProcessorId,
4281 CRM_Core_Error
::debug_log_message("Receipt sent");
4284 CRM_Core_Error
::debug_log_message("Success: Database updated");
4285 return $contributionResult;
4289 * Send receipt from contribution.
4291 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4293 * Note that the compose message part has been moved to contribution
4294 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4296 * @param array $input
4297 * Incoming data from Payment processor.
4299 * Related object IDs.
4300 * @param int $contributionID
4301 * @param bool $returnMessageText
4302 * Should text be returned instead of sent. This.
4303 * is because the function is also used to generate pdfs
4306 * @throws \CRM_Core_Exception
4307 * @throws \CiviCRM_API3_Exception
4308 * @throws \Exception
4310 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4312 $contribution = new CRM_Contribute_BAO_Contribution();
4313 $contribution->id
= $contributionID;
4314 if (!$contribution->find(TRUE)) {
4315 throw new CRM_Core_Exception('Contribution does not exist');
4317 $contribution->loadRelatedObjects($input, $ids, TRUE);
4318 // set receipt from e-mail and name in value
4319 if (!$returnMessageText) {
4320 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4322 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4323 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4324 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4325 civicrm_api3('Contribution', 'create', [
4326 'receipt_date' => 'now',
4327 'id' => $contribution->id
,
4334 * Generate From email and from name in an array values
4336 * @param array $input
4337 * @param \CRM_Contribute_BAO_Contribution $contribution
4341 public static function generateFromEmailAndName($input, $contribution) {
4342 // Use input value if supplied.
4343 if (!empty($input['receipt_from_email'])) {
4345 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4346 $input['receipt_from_email'],
4349 // if we are still empty see if we can use anything from a contribution page.
4351 if (!empty($contribution->contribution_page_id
)) {
4352 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4354 // if we are still empty see if we can use anything from a contribution page.
4355 if (!empty($pageValues['receipt_from_email'])) {
4357 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4358 $pageValues['receipt_from_email'],
4361 // If we are still empty fall back to the domain or logged in user information.
4362 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4366 * Load related memberships.
4370 * @return array $ids
4375 * Note that in theory it should be possible to retrieve these from the line_item table
4376 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4377 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4378 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4379 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4381 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4384 public function loadRelatedMembershipObjects($ids = []) {
4386 SELECT membership_id
4387 FROM civicrm_membership_payment
4388 WHERE contribution_id = %1 ";
4389 $params = [1 => [$this->id
, 'Integer']];
4390 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4392 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4393 while ($dao->fetch()) {
4394 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4395 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4399 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4400 foreach ($ids['membership'] as $id) {
4402 $membership = new CRM_Member_BAO_Membership();
4403 $membership->id
= $id;
4404 if (!$membership->find(TRUE)) {
4405 throw new Exception("Could not find membership record: $id");
4407 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4408 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4409 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4410 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4419 * Function use to store line item proportionally in in entity financial trxn table
4421 * @param array $trxnParams
4423 * @param int $trxnId
4425 * @param float $contributionTotalAmount
4427 * @throws \CiviCRM_API3_Exception
4429 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4430 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4431 if (!empty($lineItems)) {
4432 // get financial item
4433 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4435 'contribution_total_amount' => $contributionTotalAmount,
4436 'trxn_total_amount' => $trxnParams['total_amount'],
4437 'trxn_id' => $trxnId,
4439 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4444 * Checks if line items total amounts
4445 * match the contribution total amount.
4447 * @param array $params
4448 * array of order params.
4450 * @throws \API_Exception
4452 public static function checkLineItems(&$params) {
4453 $totalAmount = $params['total_amount'] ??
NULL;
4454 $lineItemAmount = 0;
4456 foreach ($params['line_items'] as &$lineItems) {
4457 foreach ($lineItems['line_item'] as &$item) {
4458 if (empty($item['financial_type_id'])) {
4459 $item['financial_type_id'] = $params['financial_type_id'];
4461 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4465 if (!isset($totalAmount)) {
4466 $params['total_amount'] = $lineItemAmount;
4469 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4471 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4472 throw new CRM_Contribute_Exception_CheckLineItemsException();
4478 * Get the financial account for the item associated with the new transaction.
4480 * @param array $params
4481 * @param int $default
4485 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4487 if (!empty($params['financial_account_id'])) {
4488 return $params['financial_account_id'];
4491 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4492 $preferredAccountsRelationships = [
4493 'Refunded' => 'Credit/Contra Revenue Account is',
4494 'Chargeback' => 'Chargeback Account is',
4497 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4498 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4499 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4501 $preferredAccountsRelationships[$contributionStatus]
4509 * ContributionPage values were being imposed onto values.
4511 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4512 * REALLY didn't want superimposed. The rest are left there in their overkill out
4515 * The rationale for making this explicit is that it was a case of carefully set values being
4516 * seemingly randonly overwritten without much care. In general I think array randomly setting
4517 * variables en mass is risky.
4519 * @param array $values
4523 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4524 $contributionPageValues = [];
4525 CRM_Contribute_BAO_ContributionPage
::setValues(
4526 $this->contribution_page_id
,
4527 $contributionPageValues
4530 // These are the values that I believe to be useful.
4533 'pay_later_receipt',
4535 'receipt_from_email',
4536 'receipt_from_name',
4540 'honoree_profile_id',
4541 'onbehalf_profile_id',
4542 'honor_block_is_active',
4543 // Kinda might be - but would be on the contribution...
4546 // Included for 'fear of regression' but can't justify any use for these....
4548 'payment_processor',
4549 'financial_type_id',
4550 'amount_block_is_active',
4555 'default_amount_id',
4559 'initial_amount_help_text',
4560 'initial_amount_label',
4562 'is_allow_other_amount',
4563 'is_billing_required',
4564 'is_confirm_enabled',
4565 'is_credit_card_only',
4567 'is_partial_payment',
4568 'is_recur_installments',
4569 'is_recur_interval',
4573 'min_initial_amount',
4574 'recur_frequency_unit',
4581 foreach ($valuesToCopy as $valueToCopy) {
4582 if (isset($contributionPageValues[$valueToCopy])) {
4583 if ($valueToCopy === 'title') {
4584 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4587 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4595 * Get values of CiviContribute Settings
4596 * and check if its enabled or not.
4597 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4598 * in serialized form. Usually this should be stored as flat settings for each form fields
4599 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4600 * settings we will live with an inconsistency because it's too hard to change for now.
4601 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4604 * @param string $name
4609 public static function checkContributeSettings($name) {
4610 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4611 return $contributeSettings[$name] ??
NULL;
4615 * Get the contribution as it is in the database before being updated.
4617 * @param int $contributionID
4619 * @return \CRM_Contribute_BAO_Contribution|null
4621 private static function getOriginalContribution($contributionID) {
4622 return self
::getValues(['id' => $contributionID]);
4626 * Get the amount for the financial item row.
4628 * Helper function to start to break down recordFinancialTransactions for readability.
4630 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4632 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4633 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4636 * @param array $params
4637 * Params as passed to contribution.create
4639 * @param string $context
4640 * changeFinancialType| changedAmount
4641 * @param array $lineItemDetails
4643 * @param bool $isARefund
4644 * Is this a refund / negative transaction.
4645 * @param int $previousLineItemTotal
4648 * @todo move recordFinancialAccounts & helper functions to their own class?
4651 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4652 if ($context == 'changedAmount') {
4653 $lineTotal = $lineItemDetails['line_total'];
4654 if ($lineTotal != $previousLineItemTotal) {
4655 $lineTotal -= $previousLineItemTotal;
4659 elseif ($context == 'changeFinancialType') {
4660 return -$lineItemDetails['line_total'];
4662 elseif ($context == 'changedStatus') {
4663 $cancelledTaxAmount = 0;
4665 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4667 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4669 elseif ($context === NULL) {
4670 // erm, yes because? but, hey, it's tested.
4671 return $lineItemDetails['line_total'];
4673 elseif (empty($lineItemDetails['line_total'])) {
4674 // follow legacy code path
4675 CRM_Core_Error
::deprecatedWarning('Deprecated bit of code, please log a ticket explaining how you got here!');
4676 return $params['total_amount'];
4679 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4684 * Get the multiplier for adjusting rows.
4686 * If we are dealing with a refund or cancellation then it will be a negative
4687 * amount to reflect the negative transaction.
4689 * If we are changing Financial Type it will be a negative amount to
4690 * adjust down the old type.
4692 * @param int $contribution_status_id
4693 * @param string $context
4697 protected static function getMultiplier($contribution_status_id, $context) {
4698 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4705 * Does this transaction reflect a payment instrument change.
4707 * @param array $params
4708 * @param array $pendingStatuses
4712 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4713 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4715 if (array_key_exists('payment_instrument_id', $params)) {
4716 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4717 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4719 //check if status is changed from Pending to Completed
4720 // do not update payment instrument changes for Pending to Completed
4721 if (!($contributionStatus == 'Completed' &&
4722 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4727 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4728 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4729 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4733 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4734 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4736 // another special case when check number is changed, create new financial records
4737 // create financial trxn with negative amount
4745 * Update the memberships associated with a contribution if it has been completed.
4747 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4748 * load them in this function. Code clean up would compensate for any minor performance implication.
4750 * @param int $contributionID
4751 * @param string $changeDate
4753 * @throws \CRM_Core_Exception
4754 * @throws \CiviCRM_API3_Exception
4756 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4757 $memberships = self
::getRelatedMemberships($contributionID);
4758 foreach ($memberships as $membership) {
4759 $membershipParams = [
4760 'id' => $membership['id'],
4761 'contact_id' => $membership['contact_id'],
4762 'is_test' => $membership['is_test'],
4763 'membership_type_id' => $membership['membership_type_id'],
4764 'membership_activity_status' => 'Completed',
4767 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4768 $membershipParams['membership_type_id'],
4769 $membershipParams['is_test'],
4770 $membershipParams['id']
4773 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4774 // this picks up membership type changes during renewals
4775 // @todo this is almost certainly an obsolete sql call, the pre-change
4776 // membership is accessible via $this->_relatedObjects
4778 SELECT membership_type_id
4779 FROM civicrm_membership_log
4780 WHERE membership_id={$membershipParams['id']}
4783 $dao = CRM_Core_DAO
::executeQuery($sql);
4784 if ($dao->fetch()) {
4785 if (!empty($dao->membership_type_id
)) {
4786 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4789 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4790 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4791 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4792 // 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.
4793 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4794 // @todo once apiv4 ships with core switch to that & find sanity.
4795 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4796 $membershipParams['membership_type_id'],
4800 // @todo remove all this stuff in favour of letting the api call further down handle in
4801 // (it is a duplication of what the api does).
4802 $dates = array_fill_keys([
4807 if ($currentMembership) {
4809 * Fixed FOR CRM-4433
4810 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4811 * when Contribution mode is notify and membership is for renewal )
4813 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4815 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4817 // @todo - we should pass membership_type_id instead of null here but not
4818 // adding as not sure of testing
4819 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4820 $changeDate, NULL, $membershipParams['num_terms']
4822 $dates['join_date'] = $currentMembership['join_date'];
4825 //get the status for membership.
4826 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4828 $dates['join_date'],
4831 $membershipParams['membership_type_id'],
4835 unset($dates['end_date']);
4836 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4837 //we might be renewing membership,
4838 //so make status override false.
4839 $membershipParams['is_override'] = FALSE;
4840 $membershipParams['status_override_end_date'] = 'null';
4841 civicrm_api3('Membership', 'create', $membershipParams);
4846 * Get payment links as they relate to a contribution.
4848 * If a payment can be made then include a payment link & if a refund is appropriate
4849 * then a refund link.
4852 * @param float $balance
4853 * @param string $contributionStatus
4856 * $actionLinks Links array containing:
4860 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4861 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4862 // In general the balance is the best way to determine if a payment can be added or not,
4863 // but not for Failed contributions, where we don't accept additional payments at the moment.
4864 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4865 // do accept more payments agains them.
4870 'url' => CRM_Utils_System
::url('civicrm/payment', [
4876 'title' => ts('Record Payment'),
4879 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4881 'url' => CRM_Utils_System
::url('civicrm/payment', [
4888 'title' => ts('Submit Credit Card payment'),
4892 'url' => CRM_Utils_System
::url('civicrm/payment', [
4898 'title' => ts('Record Refund'),
4900 return $actionLinks;
4904 * Get a query to determine the amount donated by the contact/s in the current financial year.
4906 * @param array $contactIDs
4910 public static function getAnnualQuery($contactIDs) {
4911 $contactIDs = implode(',', $contactIDs);
4912 $config = CRM_Core_Config
::singleton();
4913 $currentMonth = date('m');
4914 $currentDay = date('d');
4916 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
4918 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
4919 (int) $config->fiscalYearStart
['d'] > $currentDay
4922 $year = date('Y') - 1;
4927 $nextYear = $year +
1;
4929 if ($config->fiscalYearStart
) {
4930 $newFiscalYearStart = $config->fiscalYearStart
;
4931 if ($newFiscalYearStart['M'] < 10) {
4932 // This is just a clumsy way of adding padding.
4933 // @todo next round look for a nicer way.
4934 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
4936 if ($newFiscalYearStart['d'] < 10) {
4937 // This is just a clumsy way of adding padding.
4938 // @todo next round look for a nicer way.
4939 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
4941 $config->fiscalYearStart
= $newFiscalYearStart;
4942 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
4945 // First of January.
4948 $startDate = "$year$monthDay";
4949 $endDate = "$nextYear$monthDay";
4952 'contact_id' => 'IN (' . $contactIDs . ')',
4953 'is_test' => ' = 0',
4954 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
4956 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4957 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
4960 foreach ($whereClauses as $key => $clause) {
4961 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
4963 $whereClauseString = implode(' AND ', $clauses);
4965 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
4966 // this group by + having on contribution_status_id improves performance
4968 SELECT COUNT(*) as count,
4969 SUM(total_amount) as amount,
4970 AVG(total_amount) as average,
4972 FROM civicrm_contribution b
4973 WHERE " . $whereClauseString . "
4974 GROUP BY currency, contribution_status_id
4975 HAVING $havingClause
4981 * Assign Test Value.
4983 * @param string $fieldName
4984 * @param array $fieldDef
4985 * @param int $counter
4987 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
4988 if ($fieldName == 'tax_amount') {
4989 $this->{$fieldName} = "0.00";
4991 elseif ($fieldName == 'net_amount') {
4992 $this->{$fieldName} = "2.00";
4994 elseif ($fieldName == 'total_amount') {
4995 $this->{$fieldName} = "3.00";
4997 elseif ($fieldName == 'fee_amount') {
4998 $this->{$fieldName} = "1.00";
5001 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5006 * Check if contribution has participant/membership payment.
5008 * @param int $contributionId
5013 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5014 // get line item for contribution
5015 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5016 // check if line item is for membership or participant
5017 foreach ($lineItems as $items) {
5018 if ($items['entity_table'] == 'civicrm_participant') {
5022 elseif ($items['entity_table'] == 'civicrm_membership') {
5034 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5036 * @param array $trxnParams
5037 * Financial trxn params
5038 * @param array $contributionParams
5039 * Contribution Params
5043 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5044 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5047 $statusId = $contributionParams['contribution']->contribution_status_id
;
5048 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5049 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5050 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5051 // Return if contribution status is not completed.
5052 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5053 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5054 && $contributionParams['prevContribution']->is_pay_later
== 0
5060 $params = $trxnParams;
5061 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5062 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5063 $params['to_financial_account_id'] = $arAccountId;
5064 $params['status_id'] = array_search('Pending', $contributionStatuses);
5065 $params['is_payment'] = FALSE;
5066 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5067 self
::$_trxnIDs[] = $trxn->id
;
5068 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5072 * Calculate financial item amount when contribution is updated.
5074 * @param array $params
5075 * contribution params
5076 * @param array $amountParams
5078 * @param string $context
5082 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5083 if (!empty($params['is_quick_config'])) {
5084 $amount = $amountParams['item_amount'];
5086 $amount = $params['total_amount'];
5087 if ($context === NULL) {
5088 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5093 $amount = $amountParams['line_total'];
5094 if ($context == 'changedAmount') {
5095 $amount -= $amountParams['previous_line_total'];
5097 $amount *= $amountParams['diff'];
5103 * Retrieve Sales Tax Financial Accounts.
5109 public static function getSalesTaxFinancialAccounts() {
5110 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5111 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5112 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5113 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5114 $queryParams = [1 => [$accountRel, 'Integer']];
5115 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5116 $financialAccount = [];
5117 while ($dao->fetch()) {
5118 $financialAccount[$dao->id
] = $dao->id
;
5120 return $financialAccount;
5124 * Create tax entry in civicrm_entity_financial_trxn table.
5126 * @param array $entityParams
5128 * @param array $eftParams
5130 * @throws \CiviCRM_API3_Exception
5132 public static function createProportionalEntry($entityParams, $eftParams) {
5134 if ($entityParams['contribution_total_amount'] != 0) {
5135 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5137 // Record Entity Financial Trxn; CRM-20145
5138 $eftParams['amount'] = $paid;
5139 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5143 * Create array of last financial item id's.
5145 * @param int $contributionId
5149 public static function getLastFinancialItemIds($contributionId) {
5150 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5151 FROM civicrm_financial_item fi
5152 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5153 WHERE li.contribution_id = %1";
5154 $dao = CRM_Core_DAO
::executeQuery($sql, [
5160 $ftIds = $taxItems = [];
5161 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5162 while ($dao->fetch()) {
5163 /* if sales tax item*/
5164 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5165 $taxItems[$dao->price_field_value_id
] = [
5166 'financial_item_id' => $dao->id
,
5167 'amount' => $dao->tax_amount
,
5171 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5174 return [$ftIds, $taxItems];
5178 * Create proportional entries in civicrm_entity_financial_trxn.
5180 * @param array $entityParams
5182 * @param array $lineItems
5184 * @param array $ftIds
5186 * @param array $taxItems
5188 * @throws \CiviCRM_API3_Exception
5190 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5192 'entity_table' => 'civicrm_financial_item',
5193 'financial_trxn_id' => $entityParams['trxn_id'],
5195 foreach ($lineItems as $key => $value) {
5196 if ($value['qty'] == 0) {
5199 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5200 $entityParams['line_item_amount'] = $value['line_total'];
5201 self
::createProportionalEntry($entityParams, $eftParams);
5202 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5203 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5204 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5205 self
::createProportionalEntry($entityParams, $eftParams);
5211 * Load entities related to the contribution into $this->_relatedObjects.
5215 * @throws \CRM_Core_Exception
5217 protected function loadRelatedEntitiesByID($ids) {
5219 'contact' => 'CRM_Contact_BAO_Contact',
5220 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5221 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5222 'financialType' => 'CRM_Financial_BAO_FinancialType',
5223 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5225 foreach ($entities as $entity => $bao) {
5226 if (!empty($ids[$entity])) {
5227 $this->_relatedObjects
[$entity] = new $bao();
5228 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5229 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5230 throw new CRM_Core_Exception($entity . ' could not be loaded');
5237 * Function to replace contribution tokens.
5239 * @param array $contributionIds
5241 * @param string $subject
5243 * @param array $subjectToken
5245 * @param string $text
5247 * @param string $html
5249 * @param array $messageToken
5251 * @param bool $escapeSmarty
5254 * @throws \CiviCRM_API3_Exception
5256 public static function replaceContributionTokens(
5265 if (empty($contributionIds)) {
5268 $contributionDetails = [];
5269 foreach ($contributionIds as $id) {
5270 $result = self
::getContributionTokenValues($id, $messageToken);
5271 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5272 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5273 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5275 return $contributionDetails;
5279 * Get the contribution fields for $id and display labels where
5280 * appropriate (if the token is present).
5283 * @param array $messageToken
5286 public static function getContributionTokenValues($id, $messageToken) {
5290 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5291 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5292 if (!empty($messageToken)) {
5293 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5294 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5295 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5303 * Get invoice_number for contribution.
5305 * @param int $contributionID
5309 public static function getInvoiceNumber($contributionID) {
5310 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5311 return $invoicePrefix . $contributionID;
5318 * Load the values needed for the event message.
5320 * @param int $eventID
5321 * @param int $participantID
5322 * @param int|null $contributionID
5325 * @throws \CRM_Core_Exception
5327 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5332 $values = ['event' => []];
5334 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5335 // add custom fields for event
5336 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5338 $eventCustomGroup = [];
5339 foreach ($eventGroupTree as $key => $group) {
5340 if ($key === 'info') {
5344 foreach ($group['fields'] as $k => $customField) {
5345 $groupLabel = $group['title'];
5346 if (!empty($customField['customValue'])) {
5347 foreach ($customField['customValue'] as $customFieldValues) {
5348 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5353 $values['event']['customGroup'] = $eventCustomGroup;
5355 //get participant details
5356 $participantParams = [
5357 'id' => $participantID,
5360 $values['participant'] = [];
5362 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5363 // add custom fields for event
5364 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5365 $participantCustomGroup = [];
5366 foreach ($participantGroupTree as $key => $group) {
5367 if ($key === 'info') {
5371 foreach ($group['fields'] as $k => $customField) {
5372 $groupLabel = $group['title'];
5373 if (!empty($customField['customValue'])) {
5374 foreach ($customField['customValue'] as $customFieldValues) {
5375 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5380 $values['participant']['customGroup'] = $participantCustomGroup;
5382 //get location details
5384 'entity_id' => $eventID,
5385 'entity_table' => 'civicrm_event',
5387 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5390 'entity_table' => 'civicrm_event',
5391 'entity_id' => $eventID,
5392 'module' => 'CiviEvent',
5395 list($custom_pre_id,
5397 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5399 $values['custom_pre_id'] = $custom_pre_id;
5400 $values['custom_post_id'] = $custom_post_ids;
5402 // set lineItem for event contribution
5403 if ($contributionID) {
5404 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5405 if (!empty($participantIds)) {
5406 foreach ($participantIds as $pIDs) {
5407 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5408 if (!CRM_Utils_System
::isNull($lineItem)) {
5409 $values['lineItem'][] = $lineItem;