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 $activityParams = array_merge([
521 'activity_type_id:name' => 'Contribution',
522 'source_record_id' => $contribution->id
,
523 'activity_date_time' => $contribution->receive_date
,
524 'is_test' => (bool) $contribution->is_test
,
525 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
526 'skipRecentView' => TRUE,
527 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
528 'id' => $existingActivity['id'] ??
NULL,
530 if (!$activityParams['id']) {
531 // Don't set target contacts on update as these will have been
532 // correctly created and we risk overwriting them with
533 // 'best guess' params.
534 $activityParams['source_contact_id'] = (int) ($params['source_contact_id'] ??
(CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
));
535 $activityParams['target_contact_id'] = ($activityParams['source_contact_id'] === (int) $contribution->contact_id
) ?
[] : [$contribution->contact_id
];
537 Activity
::save(FALSE)->addRecord($activityParams)->execute();
540 // do not add to recent items for import, CRM-4399
541 if (empty($params['skipRecentView'])) {
542 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
543 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
545 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
552 $retrieveRequired = 0;
553 foreach ($titleFields as $titleField) {
554 if (!isset($contribution->$titleField)) {
555 $retrieveRequired = 1;
559 if ($retrieveRequired == 1) {
560 $contribution->find(TRUE);
562 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
563 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
566 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
567 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
568 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
572 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
573 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
574 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
578 // add the recently created Contribution
579 CRM_Utils_Recent
::add($title,
583 $contribution->contact_id
,
589 return $contribution;
593 * Get the values for pseudoconstants for name->value and reverse.
595 * @param array $defaults
596 * (reference) the default values, some of which need to be resolved.
597 * @param bool $reverse
598 * True if we want to resolve the values in the reverse direction (value -> name).
600 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
601 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
602 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
603 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
604 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
608 * Convert associative array names to values and vice-versa.
610 * This function is used by both the web form layer and the api. Note that
611 * the api needs the name => value conversion, also the view layer typically
612 * requires value => name conversion
614 * @param array $defaults
615 * @param string $property
616 * @param array $lookup
617 * @param bool $reverse
621 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
622 $id = $property . '_id';
624 $src = $reverse ?
$property : $id;
625 $dst = $reverse ?
$id : $property;
627 if (!array_key_exists($src, $defaults)) {
631 $look = $reverse ?
array_flip($lookup) : $lookup;
633 if (is_array($look)) {
634 if (!array_key_exists($defaults[$src], $look)) {
638 $defaults[$dst] = $look[$defaults[$src]];
643 * Retrieve DB object based on input parameters.
645 * It also stores all the retrieved values in the default array.
647 * @param array $params
648 * (reference ) an assoc array of name/value pairs.
649 * @param array $defaults
650 * (reference ) an assoc array to hold the name / value pairs.
651 * in a hierarchical manner
653 * (reference) the array that holds all the db ids.
655 * @return CRM_Contribute_BAO_Contribution
657 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
658 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
659 return $contribution;
663 * Combine all the importable fields from the lower levels object.
665 * The ordering is important, since currently we do not have a weight
666 * scheme. Adding weight is super important and should be done in the
667 * next week or so, before this can be called complete.
669 * @param string $contactType
670 * @param bool $status
673 * array of importable Fields
675 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
676 if (!self
::$_importableFields) {
677 if (!self
::$_importableFields) {
678 self
::$_importableFields = [];
682 $fields = ['' => ['title' => ts('- do not import -')]];
685 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
688 $note = CRM_Core_DAO_Note
::import();
689 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
690 unset($tmpFields['option_value']);
691 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
692 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
694 // Using new Dedupe rule.
696 'contact_type' => $contactType,
697 'used' => 'Unsupervised',
699 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
700 $tmpContactField = [];
701 if (is_array($fieldsArray)) {
702 foreach ($fieldsArray as $value) {
703 //skip if there is no dupe rule
704 if ($value == 'none') {
707 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
712 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
713 $tmpContactField[trim($value)] = $contactFields[trim($value)];
715 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
718 $title = $tmpContactField[trim($value)]['title'];
720 $tmpContactField[trim($value)]['title'] = $title;
724 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
725 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
726 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
727 $fields = array_merge($fields, $tmpContactField);
728 $fields = array_merge($fields, $tmpFields);
729 $fields = array_merge($fields, $note);
730 $fields = array_merge($fields, $optionFields);
731 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
732 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
733 self
::$_importableFields = $fields;
735 return self
::$_importableFields;
739 * Combine all the exportable fields from the lower level objects.
741 * @param bool $checkPermission
744 * array of exportable Fields
746 public static function &exportableFields($checkPermission = TRUE) {
747 if (!self
::$_exportableFields) {
748 if (!self
::$_exportableFields) {
749 self
::$_exportableFields = [];
752 $fields = CRM_Contribute_DAO_Contribution
::export();
753 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
754 $fields = array_merge(
756 CRM_Contribute_DAO_Product
::export(),
757 CRM_Contribute_DAO_ContributionProduct
::export(),
758 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
760 'contribution_product_id' => [
761 'title' => ts('Premium'),
762 'name' => 'contribution_product_id',
763 'where' => 'civicrm_product.id',
764 'data_type' => CRM_Utils_Type
::T_INT
,
770 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
772 $contributionPage = [
773 'contribution_page' => [
774 'title' => ts('Contribution Page'),
775 'name' => 'contribution_page',
776 'where' => 'civicrm_contribution_page.title',
777 'data_type' => CRM_Utils_Type
::T_STRING
,
781 $contributionNote = [
782 'contribution_note' => [
783 'title' => ts('Contribution Note'),
784 'name' => 'contribution_note',
785 'data_type' => CRM_Utils_Type
::T_TEXT
,
790 'contribution_batch' => [
791 'title' => ts('Batch Name'),
797 'contribution_campaign_title' => [
798 'title' => ts('Campaign Title'),
799 'name' => 'campaign_title',
800 'where' => 'civicrm_campaign.title',
801 'data_type' => CRM_Utils_Type
::T_STRING
,
804 $softCreditFields = [
805 'contribution_soft_credit_name' => [
806 'name' => 'contribution_soft_credit_name',
807 'title' => ts('Soft Credit For'),
808 'where' => 'civicrm_contact_d.display_name',
809 'data_type' => CRM_Utils_Type
::T_STRING
,
811 'contribution_soft_credit_amount' => [
812 'name' => 'contribution_soft_credit_amount',
813 'title' => ts('Soft Credit Amount'),
814 'where' => 'civicrm_contribution_soft.amount',
815 'data_type' => CRM_Utils_Type
::T_MONEY
,
817 'contribution_soft_credit_type' => [
818 'name' => 'contribution_soft_credit_type',
819 'title' => ts('Soft Credit Type'),
820 'where' => 'contribution_softcredit_type.label',
821 'data_type' => CRM_Utils_Type
::T_STRING
,
823 'contribution_soft_credit_contribution_id' => [
824 'name' => 'contribution_soft_credit_contribution_id',
825 'title' => ts('Soft Credit For Contribution ID'),
826 'where' => 'civicrm_contribution_soft.contribution_id',
827 'data_type' => CRM_Utils_Type
::T_INT
,
829 'contribution_soft_credit_contact_id' => [
830 'name' => 'contribution_soft_credit_contact_id',
831 'title' => ts('Soft Credit For Contact ID'),
832 'where' => 'civicrm_contact_d.id',
833 'data_type' => CRM_Utils_Type
::T_INT
,
837 $fields = array_merge($fields, $contributionPage,
838 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
839 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
842 self
::$_exportableFields = $fields;
845 return self
::$_exportableFields;
849 * Record an activity when a payment is received.
851 * @todo this is intended to be moved to payment BAO class as a protected function
852 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
853 * merit it's own function as it makes the code less rather than more readable.
855 * @param int $contributionId
856 * @param int $participantId
857 * @param string $totalAmount
858 * @param string $currency
859 * @param string $trxnDate
861 * @throws \CRM_Core_Exception
862 * @throws \CiviCRM_API3_Exception
864 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
865 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
867 if ($participantId) {
868 $inputParams['id'] = $participantId;
871 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
872 $entityObj = $entityObj[$participantId];
873 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
876 $entityObj = new CRM_Contribute_BAO_Contribution();
877 $entityObj->id
= $contributionId;
878 $entityObj->find(TRUE);
879 $title = ts('Contribution');
881 // @todo per block above this is not a logical splitting off of functionality.
882 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
886 * Get the value for the To Financial Account.
888 * @param $contribution
893 public static function getToFinancialAccount($contribution, $params) {
894 if (!empty($params['payment_processor_id'])) {
895 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
897 if (!empty($params['payment_instrument_id'])) {
898 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
901 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
902 $queryParams = [1 => [$relationTypeId, 'Integer']];
903 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
908 * Get memberships related to the contribution.
910 * @param int $contributionID
914 protected static function getRelatedMemberships($contributionID) {
915 $membershipPayments = civicrm_api3('MembershipPayment', 'get', [
916 'return' => 'membership_id',
917 'contribution_id' => (int) $contributionID,
920 foreach ($membershipPayments as $membershipPayment) {
921 $membershipIDs[] = $membershipPayment['membership_id'];
923 if (empty($membershipIDs)) {
926 // We could combine this with the MembershipPayment.get - we'd
927 // need to re-wrangle the params (here or in the calling function)
928 // as they would then me membership.contact_id, membership.is_test etc
929 return civicrm_api3('Membership', 'get', [
930 'id' => ['IN' => $membershipIDs],
931 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
936 * Do any accounting updates required as a result of a contribution status change.
938 * Currently we have a bit of a roundabout where adding a payment results in this being called &
939 * this may attempt to add a payment. We need to resolve that....
941 * The 'right' way to add payments or refunds is through the Payment.create api. That api
942 * then updates the contribution but this process should not also record another financial trxn.
943 * Currently we have weak detection fot that scenario & where it is detected the first returned
944 * value is FALSE - meaning 'do not continue'.
946 * We should also look at the fact that the calling function - updateFinancialAccounts
947 * bunches together some disparate processes rather than having separate appropriate
950 * @param array $params
953 * Return indicates whether the updateFinancialAccounts function should continue.
955 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
956 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
957 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
959 if ((($previousContributionStatus == 'Partially paid' && $currentContributionStatus == 'Completed')
960 ||
($previousContributionStatus == 'Pending refund' && $currentContributionStatus == 'Completed')
961 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
962 // why it is here or where it is handled instead.
963 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
964 && $currentContributionStatus == 'Partially paid'))
969 if (self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
970 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
971 $params['trxnParams']['total_amount'] = -$params['total_amount'];
973 elseif (($previousContributionStatus == 'Pending'
974 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
976 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
977 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
979 if ($currentContributionStatus == 'Cancelled') {
980 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
981 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
982 $params['trxnParams']['total_amount'] = -$params['total_amount'];
985 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
986 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
990 if (($previousContributionStatus == 'Pending'
991 ||
$previousContributionStatus == 'In Progress')
992 && ($currentContributionStatus == 'Completed')
994 if (empty($params['line_item'])) {
996 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
997 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
998 // & this can be removed
1001 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1002 // This is an update so original currency if none passed in.
1003 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1005 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1006 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1007 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1008 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1010 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1013 'entity_table' => 'civicrm_financial_item',
1015 foreach ($params['line_item'] as $fieldId => $fields) {
1016 foreach ($fields as $fieldValueId => $lineItemDetails) {
1017 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1019 1 => [$lineItemDetails['id'], 'Integer'],
1021 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1022 while ($financialItem->fetch()) {
1023 $entityParams['entity_id'] = $financialItem->id
;
1024 $entityParams['amount'] = $financialItem->amount
;
1025 foreach (self
::$_trxnIDs as $tID) {
1026 $entityParams['financial_trxn_id'] = $tID;
1027 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1038 * It is possible to override the membership id that is updated from the payment processor.
1040 * Historically Paypal does this & it still does if it determines data is messed up - see
1041 * https://lab.civicrm.org/dev/membership/issues/13
1043 * Read the comment block on repeattransaction for more information
1044 * about how things should work.
1046 * @param int $contributionID
1047 * @param array $input
1049 * @throws \CiviCRM_API3_Exception
1051 protected static function handleMembershipIDOverride($contributionID, $input) {
1052 if (!empty($input['membership_id'])) {
1053 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1054 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1059 * Update all financial items related to the line item tto have a status of paid.
1061 * @param int $lineItemID
1063 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1066 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1069 2 => [$lineItemID, 'Integer'],
1071 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1072 CRM_Core_DAO
::executeQuery($query, $fparams);
1076 * Create the financial items for the line.
1078 * @param array $params
1079 * @param string $context
1080 * @param array $fields
1081 * @param array $previousLineItems
1082 * @param array $inputParams
1083 * @param bool $isARefund
1084 * @param array $trxnIds
1085 * @param int $fieldId
1089 private static function createFinancialItemsForLine($params, $context, $fields, array $previousLineItems, array $inputParams, bool $isARefund, $trxnIds, $fieldId): array {
1090 foreach ($fields as $fieldValueId => $lineItemDetails) {
1091 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($lineItemDetails['id']);
1092 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
1093 if ($params['contribution']->receive_date
) {
1094 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
1097 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, CRM_Utils_Array
::value('financial_account_id', $prevFinancialItem));
1099 $currency = $params['prevContribution']->currency
;
1100 if ($params['contribution']->currency
) {
1101 $currency = $params['contribution']->currency
;
1103 $previousLineItemTotal = CRM_Utils_Array
::value('line_total', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1105 'transaction_date' => $receiveDate,
1106 'contact_id' => $params['prevContribution']->contact_id
,
1107 'currency' => $currency,
1108 'amount' => self
::getFinancialItemAmountFromParams($inputParams, $context, $lineItemDetails, $isARefund, $previousLineItemTotal),
1109 'description' => $prevFinancialItem['description'] ??
NULL,
1110 'status_id' => $prevFinancialItem['status_id'],
1111 'financial_account_id' => $financialAccount,
1112 'entity_table' => 'civicrm_line_item',
1113 'entity_id' => $lineItemDetails['id'],
1115 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1116 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $itemParams['amount'];
1117 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
1119 if (($lineItemDetails['tax_amount'] && $lineItemDetails['tax_amount'] !== 'null') ||
($context == 'changeFinancialType')) {
1120 $taxAmount = (float) $lineItemDetails['tax_amount'];
1121 if ($context == 'changeFinancialType' && $lineItemDetails['tax_amount'] === 'null') {
1122 // reverse the Sale Tax amount if there is no tax rate associated with new Financial Type
1123 $taxAmount = CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1125 elseif ($previousLineItemTotal != $lineItemDetails['line_total']) {
1126 $taxAmount -= CRM_Utils_Array
::value('tax_amount', CRM_Utils_Array
::value($fieldValueId, $previousLineItems), 0);
1128 if ($taxAmount != 0) {
1129 $itemParams['amount'] = self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * $taxAmount;
1130 $itemParams['description'] = CRM_Invoicing_Utils
::getTaxTerm();
1131 if ($lineItemDetails['financial_type_id']) {
1132 $itemParams['financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getSalesTaxFinancialAccount($lineItemDetails['financial_type_id']);
1134 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
1142 * Does this contributtion status update represent a refund.
1144 * @param int $previousContributionStatusID
1145 * @param int $currentContributionStatusID
1149 private static function isContributionUpdateARefund($previousContributionStatusID, $currentContributionStatusID): bool {
1150 if ('Completed' !== CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $previousContributionStatusID)) {
1153 return self
::isContributionStatusNegative($currentContributionStatusID);
1157 * Get transaction information about the contribution.
1159 * @param int $contributionId
1160 * @param int $financialTypeID
1164 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1166 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1168 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1170 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1172 ft.payment_instrument_id,
1173 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1175 FROM civicrm_contribution con
1176 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1177 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1178 AND ft.to_financial_account_id != %2
1179 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1180 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1181 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1183 WHERE con.id = %1 AND ft.is_payment = 1
1186 1 => [$contributionId, 'Integer'],
1187 2 => [$feeFinancialAccount, 'Integer'],
1189 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1190 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1192 while ($resultDAO->fetch()) {
1193 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1194 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1195 if ($resultDAO->card_type_id
) {
1196 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1197 $pantruncation = '';
1198 if ($resultDAO->pan_truncation
) {
1199 $pantruncation = ": {$resultDAO->pan_truncation}";
1201 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1204 // show payment edit link only for payments done via backoffice form
1205 $paymentEditLink = '';
1206 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1208 CRM_Core_Action
::UPDATE
=> [
1209 'name' => ts('Edit Payment'),
1210 'icon' => 'fa-pencil',
1211 'url' => 'civicrm/payment/edit',
1212 'class' => 'medium-popup',
1213 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1214 'title' => ts('Edit Payment'),
1217 $paymentEditLink = CRM_Core_Action
::formLink(
1219 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1221 'id' => $resultDAO->id
,
1222 'contribution_id' => $contributionId,
1226 'Payment.edit.action',
1234 'id' => $resultDAO->id
,
1235 'total_amount' => $resultDAO->total_amount
,
1236 'financial_type' => $resultDAO->financial_account
,
1237 'payment_instrument' => $paidByLabel,
1238 'receive_date' => $resultDAO->trxn_date
,
1239 'trxn_id' => $resultDAO->trxn_id
,
1240 'status' => $statuses[$resultDAO->status_id
],
1241 'currency' => $resultDAO->currency
,
1242 'action' => $paymentEditLink,
1244 if ($paidByName == 'Check') {
1245 $val['check_number'] = $resultDAO->check_number
;
1253 * Should an email receipt be sent for this contribution on completion.
1255 * @param array $input
1256 * @param int $contributionPageID
1257 * @param int $recurringContributionID
1260 * @throws \API_Exception
1261 * @throws \Civi\API\Exception\UnauthorizedException
1263 protected static function isEmailReceipt(array $input, $contributionPageID, $recurringContributionID): bool {
1264 if (isset($input['is_email_receipt'])) {
1265 return (bool) $input['is_email_receipt'];
1267 if ($recurringContributionID) {
1268 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1269 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1270 // 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
1271 // Instance that had the table added via an upgrade in 4.1
1272 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1273 // https://lab.civicrm.org/dev/core/issues/1245
1274 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1276 if ($contributionPageID) {
1277 return (bool) ContributionPage
::get(FALSE)->addWhere('id', '=', $contributionPageID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1279 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1287 public function addSelectWhereClause() {
1288 $whereClauses = parent
::addSelectWhereClause();
1289 if ($whereClauses !== []) {
1290 // In this case permisssions have been applied & we assume the
1291 // financialaclreport is applying these
1292 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1293 return $whereClauses;
1296 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1297 return $whereClauses;
1299 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1300 if (empty($types)) {
1301 $whereClauses['financial_type_id'] = 'IN (0)';
1304 $whereClauses['financial_type_id'] = [
1305 'IN (' . implode(',', array_keys($types)) . ')',
1308 return $whereClauses;
1312 * @param null $status
1313 * @param null $startDate
1314 * @param null $endDate
1316 * @return array|null
1318 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1322 $where[] = 'contribution_status_id = 1';
1326 $where[] = 'contribution_status_id = 3';
1331 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1334 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1336 $financialTypeACLJoin = '';
1337 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1338 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1339 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1340 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1341 if ($financialTypes) {
1342 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1343 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1346 $where[] = "c.financial_type_id IN (0)";
1350 $whereCond = implode(' AND ', $where);
1353 SELECT sum( total_amount ) as total_amount,
1354 count( c.id ) as total_count,
1356 FROM civicrm_contribution c
1357 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1358 $financialTypeACLJoin
1360 AND ( is_test = 0 OR is_test IS NULL )
1361 AND contact.is_deleted = 0
1365 $dao = CRM_Core_DAO
::executeQuery($query);
1368 while ($dao->fetch()) {
1369 $count +
= $dao->total_count
;
1370 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1374 'amount' => implode(', ', $amount),
1382 * Delete the indirect records associated with this contribution first.
1386 * @return mixed|null
1387 * $results no of deleted Contribution on success, false otherwise
1389 public static function deleteContribution($id) {
1390 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1392 $transaction = new CRM_Core_Transaction();
1395 //delete activity record
1397 'source_record_id' => $id,
1398 // activity type id for contribution
1399 'activity_type_id' => 6,
1402 CRM_Activity_BAO_Activity
::deleteActivity($params);
1404 //delete billing address if exists for this contribution.
1405 self
::deleteAddress($id);
1407 //update pledge and pledge payment, CRM-3961
1408 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1410 // remove entry from civicrm_price_set_entity, CRM-5095
1411 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1412 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1414 // cleanup line items.
1415 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1417 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1418 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1420 if ($participantId) {
1421 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1424 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1428 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1429 $noteId = key($note);
1431 CRM_Core_BAO_Note
::del($noteId, FALSE);
1434 $dao = new CRM_Contribute_DAO_Contribution();
1437 $results = $dao->delete();
1439 $transaction->commit();
1441 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1443 // delete the recently created Contribution
1444 $contributionRecent = [
1446 'type' => 'Contribution',
1448 CRM_Utils_Recent
::del($contributionRecent);
1454 * React to a financial transaction (payment) failure.
1456 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1457 * payments is important for forensic and outreach reasons.
1459 * @param int $contributionID
1460 * @param int $contactID
1461 * @param string $message
1463 * @throws \CiviCRM_API3_Exception
1465 public static function failPayment($contributionID, $contactID, $message) {
1466 civicrm_api3('activity', 'create', [
1467 'activity_type_id' => 'Failed Payment',
1468 'details' => $message,
1469 'subject' => ts('Payment failed at payment processor'),
1470 'source_record_id' => $contributionID,
1471 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1474 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1475 civicrm_api3('contribution', 'create', [
1476 'id' => $contributionID,
1477 'contribution_status_id' => 'Failed',
1482 * Check if there is a contribution with the same trxn_id or invoice_id.
1484 * @param array $input
1485 * An assoc array of name/value pairs.
1486 * @param array $duplicates
1487 * (reference) store ids of duplicate contribs.
1491 * true if duplicate, false otherwise
1493 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1495 $id = $input['id'] ??
NULL;
1497 $trxn_id = $input['trxn_id'] ??
NULL;
1498 $invoice_id = $input['invoice_id'] ??
NULL;
1504 $clause[] = "trxn_id = %1";
1505 $input[1] = [$trxn_id, 'String'];
1509 $clause[] = "invoice_id = %2";
1510 $input[2] = [$invoice_id, 'String'];
1513 if (empty($clause)) {
1517 $clause = implode(' OR ', $clause);
1519 $clause = "( $clause ) AND id != %3";
1520 $input[3] = [$id, 'Integer'];
1523 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1524 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1526 while ($dao->fetch()) {
1527 $duplicates[] = $dao->id
;
1534 * Takes an associative array and creates a contribution_product object.
1536 * the function extract all the params it needs to initialize the create a
1537 * contribution_product object. the params array could contain additional unused name/value
1540 * @param array $params
1541 * (reference) an assoc array of name/value pairs.
1543 * @return CRM_Contribute_DAO_ContributionProduct
1545 public static function addPremium(&$params) {
1546 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1547 $contributionProduct->copyValues($params);
1548 return $contributionProduct->save();
1552 * Get list of contribution fields for profile.
1553 * For now we only allow custom contribution fields to be in
1556 * @param bool $addExtraFields
1557 * True if special fields needs to be added.
1560 * the list of contribution fields
1562 public static function getContributionFields($addExtraFields = TRUE) {
1563 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1564 // @todo remove this - this line was added because payment_instrument_id was not
1565 // set to exportable - but now it is.
1566 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1568 if ($addExtraFields) {
1569 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1572 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1574 foreach ($contributionFields as $key => $var) {
1575 if ($key == 'contribution_contact_id') {
1578 elseif ($key == 'contribution_campaign_id') {
1579 $var['title'] = ts('Campaign');
1581 $fields[$key] = $var;
1584 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1589 * Add extra fields specific to contribution.
1591 public static function getSpecialContributionFields() {
1593 'contribution_soft_credit_name' => [
1594 'name' => 'contribution_soft_credit_name',
1595 'title' => ts('Soft Credit Name'),
1596 'headerPattern' => '/^soft_credit_name$/i',
1597 'where' => 'civicrm_contact_d.display_name',
1599 'contribution_soft_credit_email' => [
1600 'name' => 'contribution_soft_credit_email',
1601 'title' => ts('Soft Credit Email'),
1602 'headerPattern' => '/^soft_credit_email$/i',
1603 'where' => 'soft_email.email',
1605 'contribution_soft_credit_phone' => [
1606 'name' => 'contribution_soft_credit_phone',
1607 'title' => ts('Soft Credit Phone'),
1608 'headerPattern' => '/^soft_credit_phone$/i',
1609 'where' => 'soft_phone.phone',
1611 'contribution_soft_credit_contact_id' => [
1612 'name' => 'contribution_soft_credit_contact_id',
1613 'title' => ts('Soft Credit Contact ID'),
1614 'headerPattern' => '/^soft_credit_contact_id$/i',
1615 'where' => 'civicrm_contribution_soft.contact_id',
1617 'contribution_pcp_title' => [
1618 'name' => 'contribution_pcp_title',
1619 'title' => ts('Personal Campaign Page Title'),
1620 'headerPattern' => '/^contribution_pcp_title$/i',
1621 'where' => 'contribution_pcp.title',
1625 return $extraFields;
1629 * @param int $pageID
1633 public static function getCurrentandGoalAmount($pageID) {
1635 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1636 FROM civicrm_contribution_page p,
1637 civicrm_contribution c
1638 WHERE p.id = c.contribution_page_id
1640 AND c.cancel_date is null
1644 $config = CRM_Core_Config
::singleton();
1645 $params = [1 => [$pageID, 'Integer']];
1646 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1648 if ($dao->fetch()) {
1649 return [$dao->goal
, $dao->total
];
1652 return [NULL, NULL];
1657 * Get list of contributions which credit the passed in contact ID.
1659 * The returned array provides details about the original contribution & donor.
1661 * @param int $honorId
1662 * In Honor of Contact ID.
1665 * list of contribution fields
1666 * @todo - this is a confusing function called from one place. It has a test. It would be
1667 * nice to deprecate it.
1670 public static function getHonorContacts($honorId) {
1672 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1673 $honorDAO->contact_id
= $honorId;
1676 $type = CRM_Contribute_PseudoConstant
::financialType();
1678 while ($honorDAO->fetch()) {
1679 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1680 $contributionDAO->id
= $honorDAO->contribution_id
;
1682 if ($contributionDAO->find(TRUE)) {
1683 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1684 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1685 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1686 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1687 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1688 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1689 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1690 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1691 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1699 * Get the sort name of a contact for a particular contribution.
1702 * Id of the contribution.
1704 * @return null|string
1705 * sort name of the contact if found
1707 public static function sortName($id) {
1708 $id = CRM_Utils_Type
::escape($id, 'Integer');
1711 SELECT civicrm_contact.sort_name
1712 FROM civicrm_contribution, civicrm_contact
1713 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1714 AND civicrm_contribution.id = {$id}
1716 return CRM_Core_DAO
::singleValueQuery($query);
1720 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1722 * @param int|array $contactIDs
1726 public static function annual($contactIDs) {
1727 if (!is_array($contactIDs)) {
1728 // In practice I can't fine any evidence that this function is ever called with
1729 // anything other than a single contact id, but left like this due to .... fear.
1730 $contactIDs = explode(',', $contactIDs);
1733 $query = self
::getAnnualQuery($contactIDs);
1734 $dao = CRM_Core_DAO
::executeQuery($query);
1736 $amount = $average = [];
1737 while ($dao->fetch()) {
1738 if ($dao->count
> 0 && $dao->amount
> 0) {
1739 $count +
= $dao->count
;
1740 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1741 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1747 implode(', ', $amount),
1748 implode(', ', $average),
1755 * Check if there is a contribution with the params passed in.
1757 * Used for trxn_id,invoice_id and contribution_id
1759 * @param array $params
1760 * An assoc array of name/value pairs.
1763 * contribution id if success else NULL
1765 public static function checkDuplicateIds($params) {
1766 $dao = new CRM_Contribute_DAO_Contribution();
1770 foreach ($params as $k => $v) {
1772 $clause[] = "$k = '$v'";
1775 $clause = implode(' AND ', $clause);
1776 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1777 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1779 while ($dao->fetch()) {
1787 * Get the contribution details for component export.
1789 * @param int $exportMode
1791 * @param array $componentIds
1797 public static function getContributionDetails($exportMode, $componentIds) {
1798 $paymentDetails = [];
1799 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1801 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1802 $componentSelect = " civicrm_participant_payment.participant_id id";
1803 $additionalClause = "
1804 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1805 AND civicrm_participant_payment.participant_id {$componentClause} )
1808 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1809 $componentSelect = " civicrm_membership_payment.membership_id id";
1810 $additionalClause = "
1811 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1812 AND civicrm_membership_payment.membership_id {$componentClause} )
1815 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1816 $componentSelect = " civicrm_pledge_payment.id id";
1817 $additionalClause = "
1818 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1819 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1823 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1824 trxn_id, {$componentSelect}
1825 FROM civicrm_contribution
1826 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1827 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1828 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1829 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1830 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1831 AND option_group_contribution_status.id = contribution_status.option_group_id )
1835 $dao = CRM_Core_DAO
::executeQuery($query);
1837 while ($dao->fetch()) {
1838 $paymentDetails[$dao->id
] = [
1839 'total_amount' => $dao->total_amount
,
1840 'contribution_status' => $dao->status
,
1841 'receive_date' => $dao->receive_date
,
1842 'pay_instru' => $dao->payment_instrument
,
1843 'trxn_id' => $dao->trxn_id
,
1847 return $paymentDetails;
1851 * Create address associated with contribution record.
1853 * As long as there is one or more billing field in the parameters we will create the address.
1855 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1858 * @param array $params
1859 * @param int $billingLocationTypeID
1864 public static function createAddress($params, $billingLocationTypeID) {
1865 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1866 if ($hasBillingField) {
1867 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1868 return $address->id
;
1875 * Delete billing address record related contribution.
1877 * @param int $contributionId
1878 * @param int $contactId
1880 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1882 $contactJoin = NULL;
1884 if ($contributionId) {
1885 $clauses[] = "cc.id = {$contributionId}";
1889 $clauses[] = "cco.id = {$contactId}";
1890 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1893 if (empty($clauses)) {
1894 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1897 $condition = implode(' OR ', $clauses);
1901 FROM civicrm_address ca
1902 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1906 $dao = CRM_Core_DAO
::executeQuery($query);
1908 while ($dao->fetch()) {
1909 $params = ['id' => $dao->id
];
1910 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1915 * This function check online pending contribution associated w/
1916 * Online Event Registration or Online Membership signup.
1918 * @param int $componentId
1919 * Participant/membership id.
1920 * @param string $componentName
1924 * pending contribution id.
1926 public static function checkOnlinePendingContribution($componentId, $componentName) {
1927 $contributionId = NULL;
1928 if (!$componentId ||
1929 !in_array($componentName, ['Event', 'Membership'])
1931 return $contributionId;
1934 if ($componentName == 'Event') {
1935 $idName = 'participant_id';
1936 $componentTable = 'civicrm_participant';
1937 $paymentTable = 'civicrm_participant_payment';
1938 $source = ts('Online Event Registration');
1941 if ($componentName == 'Membership') {
1942 $idName = 'membership_id';
1943 $componentTable = 'civicrm_membership';
1944 $paymentTable = 'civicrm_membership_payment';
1945 $source = ts('Online Contribution');
1948 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1951 SELECT component.id as {$idName},
1952 componentPayment.contribution_id as contribution_id,
1953 contribution.source source,
1954 contribution.contribution_status_id as contribution_status_id,
1955 contribution.is_pay_later as is_pay_later
1956 FROM $componentTable component
1957 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1958 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1959 WHERE component.id = {$componentId}";
1961 $dao = CRM_Core_DAO
::executeQuery($query);
1963 while ($dao->fetch()) {
1964 if ($dao->contribution_id
&&
1965 $dao->is_pay_later
&&
1966 $dao->contribution_status_id
== $pendingStatusId &&
1967 strpos($dao->source
, $source) !== FALSE
1969 $contributionId = $dao->contribution_id
;
1973 return $contributionId;
1977 * Update contribution as well as related objects.
1979 * This function by-passes hooks - to address this - don't use this function.
1981 * @param array $params
1983 * @throws CRM_Core_Exception
1984 * @throws \CiviCRM_API3_Exception
1987 * Use api contribute.completetransaction
1988 * For failures use failPayment (preferably exposing by api in the process).
1991 public static function transitionComponents($params) {
1992 // get minimum required values.
1993 $contactId = $params['contact_id'] ??
NULL;
1994 $componentId = $params['component_id'] ??
NULL;
1995 $componentName = $params['componentName'] ??
NULL;
1996 $contributionId = $params['contribution_id'] ??
NULL;
1997 $contributionStatusId = $params['contribution_status_id'] ??
NULL;
1999 // if we already processed contribution object pass previous status id.
2000 $previousContriStatusId = $params['previous_contribution_status_id'] ??
NULL;
2002 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2004 // we process only ( Completed, Cancelled, or Failed ) contributions.
2005 if (!$contributionId ||
2006 !in_array($contributionStatusId, [
2007 array_search('Completed', $contributionStatuses),
2013 if (!$componentName ||
!$componentId) {
2014 // get the related component details.
2015 $componentDetails = self
::getComponentDetails($contributionId);
2018 $componentDetails['contact_id'] = $contactId;
2019 $componentDetails['component'] = $componentName;
2021 if ($componentName == 'event') {
2022 $componentDetails['participant'] = $componentId;
2025 $componentDetails['membership'] = $componentId;
2029 if (!empty($componentDetails['contact_id'])) {
2030 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2036 // do check for required ids.
2037 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2043 $input['component'] = $componentDetails['component'] ??
NULL;
2044 $ids['contribution'] = $contributionId;
2045 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2046 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2047 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2048 $ids['event'] = $componentDetails['event'] ??
NULL;
2049 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2050 $ids['contributionRecur'] = NULL;
2051 $ids['contributionPage'] = NULL;
2053 $contribution = new CRM_Contribute_BAO_Contribution();
2054 $contribution->id
= $ids['contribution'];
2055 $contribution->find();
2057 $contribution->loadRelatedObjects($input, $ids);
2059 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2060 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2061 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2063 $pledgeID = $oldStatus = NULL;
2064 $pledgePaymentIDs = [];
2065 if ($pledgePayment) {
2066 foreach ($pledgePayment as $key => $object) {
2067 $pledgePaymentIDs[] = $object->id
;
2069 $pledgeID = $pledgePayment[0]->pledge_id
;
2072 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2075 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2076 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2081 if ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
2083 // only pending contribution related object processed.
2084 if ($previousContriStatusId &&
2085 !in_array($contributionStatuses[$previousContriStatusId], [
2090 // this is case when we already processed contribution object.
2093 elseif (!$previousContriStatusId &&
2094 !in_array($contributionStatuses[$contribution->contribution_status_id
], [
2099 // this is case when we are going to process contribution object later.
2103 if (is_array($memberships)) {
2104 foreach ($memberships as $membership) {
2109 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2110 $membership->membership_type_id
,
2111 $membership->is_test
, $membership->id
2114 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2115 // this picks up membership type changes during renewals
2117 SELECT membership_type_id
2118 FROM civicrm_membership_log
2119 WHERE membership_id=$membership->id
2122 $dao = CRM_Core_DAO
::executeQuery($sql);
2123 if ($dao->fetch()) {
2124 if (!empty($dao->membership_type_id
)) {
2125 $membership->membership_type_id
= $dao->membership_type_id
;
2126 $membership->save();
2129 // else fall back to using current membership type
2130 // Figure out number of terms
2132 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2133 foreach ($lineitems as $lineitem) {
2134 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2135 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2137 // in case membership_num_terms comes through as null or zero
2138 $numterms = $numterms >= 1 ?
$numterms : 1;
2143 // CRM-15735-to update the membership status as per the contribution receive date
2145 $oldStatus = $membership->status_id
;
2146 if (!empty($params['receive_date'])) {
2147 $joinDate = $params['receive_date'];
2148 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2149 $membership->end_date
,
2150 $membership->join_date
,
2151 $params['receive_date'],
2153 $membership->membership_type_id
,
2156 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2157 $membership->save();
2160 if ($currentMembership) {
2161 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2162 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2163 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2166 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2169 //get the status for membership.
2170 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2172 $dates['join_date'],
2175 $membership->membership_type_id
,
2179 $formattedParams = [
2180 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2181 array_search('Current', $membershipStatuses)
2183 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2184 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2185 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2188 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2190 $membership->copyValues($formattedParams);
2191 $membership->save();
2193 //updating the membership log
2194 $membershipLog = [];
2195 $membershipLog = $formattedParams;
2196 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2197 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2199 $membershipLog['start_date'] = $logStartDate;
2200 $membershipLog['membership_id'] = $membership->id
;
2201 $membershipLog['modified_id'] = $membership->contact_id
;
2202 $membershipLog['modified_date'] = date('Ymd');
2203 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2205 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2207 //update related Memberships.
2208 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2210 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2211 $scheduledActivityID = CRM_Utils_Array
::value('id',
2212 civicrm_api3('Activity', 'Get',
2214 'source_record_id' => $membership->id
,
2215 'activity_type_id' => $activityType,
2216 'status_id' => 'Scheduled',
2219 'sort' => 'id DESC',
2224 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2225 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2226 if ($scheduledActivityID) {
2227 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2232 // track membership status change if any
2233 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2234 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2235 CRM_Activity_BAO_Activity
::addActivity($membership,
2236 'Change Membership Status',
2239 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2240 'source_contact_id' => $membershipLog['modified_id'],
2241 'priority_id' => 'Normal',
2246 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2252 $updatedStatusId = array_search('Registered', $participantStatuses);
2253 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2256 if ($pledgePayment) {
2257 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2264 * Returns all contribution related object ids.
2266 * @param $contributionId
2270 public static function getComponentDetails($contributionId) {
2271 $componentDetails = $pledgePayment = [];
2272 if (!$contributionId) {
2273 return $componentDetails;
2277 SELECT c.id as contribution_id,
2278 c.contact_id as contact_id,
2279 c.contribution_recur_id,
2280 mp.membership_id as membership_id,
2281 m.membership_type_id as membership_type_id,
2282 pp.participant_id as participant_id,
2283 p.event_id as event_id,
2284 pgp.id as pledge_payment_id
2285 FROM civicrm_contribution c
2286 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2287 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2288 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2289 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2290 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2291 WHERE c.id = $contributionId";
2293 $dao = CRM_Core_DAO
::executeQuery($query);
2294 $componentDetails = [];
2296 while ($dao->fetch()) {
2297 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2298 $componentDetails['contact_id'] = $dao->contact_id
;
2299 if ($dao->event_id
) {
2300 $componentDetails['event'] = $dao->event_id
;
2302 if ($dao->participant_id
) {
2303 $componentDetails['participant'] = $dao->participant_id
;
2305 if ($dao->membership_id
) {
2306 if (!isset($componentDetails['membership'])) {
2307 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2309 $componentDetails['membership'][] = $dao->membership_id
;
2310 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2312 if ($dao->pledge_payment_id
) {
2313 $pledgePayment[] = $dao->pledge_payment_id
;
2315 if ($dao->contribution_recur_id
) {
2316 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2320 if ($pledgePayment) {
2321 $componentDetails['pledge_payment'] = $pledgePayment;
2324 return $componentDetails;
2328 * @param int $contactId
2329 * @param bool $includeSoftCredit
2331 * @return null|string
2333 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2337 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2338 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2339 $liWhere = " AND i.financial_type_id IN (0)";
2340 if (!empty($financialTypes)) {
2341 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2342 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2344 $contactContributionsSQL = "
2345 SELECT contribution.id AS id
2346 FROM civicrm_contribution contribution
2347 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2348 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2352 $contactSoftCreditContributionsSQL = "
2353 SELECT contribution.id
2354 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2355 ON ( contribution.id = softContribution.contribution_id )
2356 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2357 $query = "SELECT count( x.id ) count FROM ( ";
2358 $query .= $contactContributionsSQL;
2360 if ($includeSoftCredit) {
2361 $query .= " UNION ";
2362 $query .= $contactSoftCreditContributionsSQL;
2367 return CRM_Core_DAO
::singleValueQuery($query);
2371 * Repeat a transaction as part of a recurring series.
2374 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2375 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2376 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2377 * and associated entities.
2378 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2379 * which updates the various entities and sends appropriate emails.
2381 * Gaps in the above (@todo)
2382 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2383 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2384 * 3) Repeat transaction duplicates rather than calls Order.create
2385 * 4) Use of payment.create still limited - completetransaction is more common.
2386 * 5) the template transaction is tricky - historically we used the first contribution
2387 * linked to a recurring contribution. More recently that was changed to be the most recent.
2388 * Ideally it would be an actual template - not a contribution used as a template which
2389 * would give more appropriate flexibility. Note line_items have an entity so that table
2390 * could be used for the line item template - the difficulty is the custom fields...
2391 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2392 * to load the membership(s) referred to via line items in the template transactions. Any other
2393 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2394 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2395 * - membership_payment record
2396 * - civicrm_membership.contribution_recur_id
2398 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2399 * of historical processors since this has been handled 'forever' - specifically for paypal.
2400 * albeit by an even nastier mechanism than the current input override.
2401 * The count is out on how correct related entities wind up in this case.
2403 * @param CRM_Contribute_BAO_Contribution $contribution
2404 * @param array $input
2405 * @param array $contributionParams
2407 * @return bool|array
2408 * @throws CiviCRM_API3_Exception
2410 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2411 if (!empty($contribution->id
)) {
2414 if (empty($contribution->id
)) {
2415 // Unclear why this would only be set for repeats.
2416 if (!empty($input['amount'])) {
2417 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2420 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2421 'id' => $contributionParams['contribution_recur_id'],
2423 if (!empty($recurringContribution['financial_type_id'])) {
2424 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2425 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2427 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2428 $contributionParams['contribution_recur_id'],
2429 array_intersect_key($contributionParams, [
2430 'total_amount' => TRUE,
2431 'financial_type_id' => TRUE,
2434 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2435 $contributionParams['status_id'] = 'Pending';
2437 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2438 // We permit the financial type to be overridden for single line items.
2439 // More comments on this are in getTemplateTransaction.
2440 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2443 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2445 foreach (['contact_id', 'currency', 'source', 'amount_level', 'address_id', 'on_behalf', 'source_contact_id', 'tax_amount', 'contribution_page_id'] as $fieldName) {
2446 if (isset($templateContribution[$fieldName])) {
2447 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2450 if (!empty($recurringContribution['campaign_id'])) {
2451 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2452 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2454 if (!isset($contributionParams['campaign_id']) && isset($templateContribution['campaign_id'])) {
2455 // Fall back on value from the previous contribution if not passed in as input
2456 // or loadable from the recurring contribution.
2457 $contributionParams['campaign_id'] = $templateContribution['campaign_id'];
2459 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2461 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2462 //do not create CC or BCC emails or profile notifications.
2463 //The if is just to be safe. Not sure if we can ever arrive with this unset
2464 // but per CRM-19478 it seems it can be 'null'
2465 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2466 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2469 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2470 $contribution->id
= $createContribution['id'];
2471 $contribution->copyCustomFields($templateContribution['id'], $contribution->id
);
2472 self
::handleMembershipIDOverride($contribution->id
, $input);
2473 // Add new soft credit against current $contribution.
2474 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2475 return $createContribution;
2480 * Get individual id for onbehalf contribution.
2482 * @param int $contributionId
2484 * @param int $contributorId
2488 * containing organization id and individual id
2490 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2494 if (!$contributionId) {
2498 // fetch contributor id if null
2499 if (!$contributorId) {
2500 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2501 $contributionId, 'contact_id'
2505 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2506 $activityTypeId = array_search('Contribution', $activityTypeIds);
2508 if ($activityTypeId && $contributorId) {
2510 SELECT civicrm_activity_contact.contact_id
2511 FROM civicrm_activity_contact
2512 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2513 WHERE civicrm_activity.activity_type_id = %1
2514 AND civicrm_activity.source_record_id = %2
2515 AND civicrm_activity_contact.record_type_id = %3
2518 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2519 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2522 1 => [$activityTypeId, 'Integer'],
2523 2 => [$contributionId, 'Integer'],
2524 3 => [$sourceID, 'Integer'],
2527 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2529 // for on behalf contribution source is individual and contributor is organization
2530 if ($sourceContactId && $sourceContactId != $contributorId) {
2531 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2532 // get rel type id for employee of relation
2533 foreach ($relationshipTypeIds as $id => $typeVals) {
2534 if ($typeVals['name_a_b'] == 'Employee of') {
2535 $relationshipTypeId = $id;
2540 $rel = new CRM_Contact_DAO_Relationship();
2541 $rel->relationship_type_id
= $relationshipTypeId;
2542 $rel->contact_id_a
= $sourceContactId;
2543 $rel->contact_id_b
= $contributorId;
2544 if ($rel->find(TRUE)) {
2545 $ids['individual_id'] = $rel->contact_id_a
;
2546 $ids['organization_id'] = $rel->contact_id_b
;
2557 public static function getContributionDates() {
2558 $config = CRM_Core_Config
::singleton();
2559 $currentMonth = date('m');
2560 $currentDay = date('d');
2561 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2562 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2563 (int ) $config->fiscalYearStart
['d'] > $currentDay
2566 $year = date('Y') - 1;
2571 $year = ['Y' => $year];
2572 $yearDate = $config->fiscalYearStart
;
2573 $yearDate = array_merge($year, $yearDate);
2574 $yearDate = CRM_Utils_Date
::format($yearDate);
2576 $monthDate = date('Ym') . '01';
2582 'yearDate' => $yearDate,
2583 'monthDate' => $monthDate,
2588 * Load objects relations to contribution object.
2589 * Objects are stored in the $_relatedObjects property
2590 * In the first instance we are just moving functionality from BASEIpn -
2592 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2594 * Note that the unit test for the BaseIPN class tests this function
2596 * @param array $input
2597 * Input as delivered from Payment Processor.
2599 * Ids as Loaded by Payment Processor.
2600 * @param bool $loadAll
2601 * Load all related objects - even where id not passed in? (allows API to call this).
2604 * @throws CRM_Core_Exception
2606 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2607 // @todo deprecate this function - the steps should be
2608 // 1) add additional functions like 'getRelatedMemberships'
2609 // 2) switch all calls that refer to ->_relatedObjects to
2610 // using the helper functions
2611 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2612 // 4) make ->_relatedObjects protected
2613 // 5) hone up the individual functions to not use rely on this having been called
2614 // 6) deprecate like mad
2616 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2617 if (empty($ids['contact']) && isset($this->contact_id
)) {
2618 $ids['contact'] = $this->contact_id
;
2621 if (empty($this->_component
)) {
2622 if (!empty($ids['event'])) {
2623 $this->_component
= 'event';
2626 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2630 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2631 // refactoring than anything else, and has unit test coverage.
2632 if (empty($this->financial_type_id
)) {
2636 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2641 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2642 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2643 $this->contribution_page_id
,
2646 if ($paymentProcessorID) {
2647 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2651 $ids['contributionType'] = $this->financial_type_id
;
2652 $ids['financialType'] = $this->financial_type_id
;
2653 if ($this->contribution_page_id
) {
2654 $ids['contributionPage'] = $this->contribution_page_id
;
2657 $this->loadRelatedEntitiesByID($ids);
2659 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2660 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2663 if (!empty($ids['pledge_payment'])) {
2664 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2665 if (empty($paymentID)) {
2668 $payment = new CRM_Pledge_BAO_PledgePayment();
2669 $payment->id
= $paymentID;
2670 if (!$payment->find(TRUE)) {
2671 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2673 $this->_relatedObjects
['pledge_payment'][] = $payment;
2677 // These are probably no longer accessed from anywhere
2678 // @todo remove this line, after ensuring not used.
2679 $ids = $this->loadRelatedMembershipObjects($ids);
2681 if ($this->_component
!= 'contribute') {
2682 // we are in event mode
2683 // make sure event exists and is valid
2684 $event = new CRM_Event_BAO_Event();
2685 $event->id
= $ids['event'];
2686 if ($ids['event'] &&
2689 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2692 $this->_relatedObjects
['event'] = &$event;
2694 $participant = new CRM_Event_BAO_Participant();
2695 $participant->id
= $ids['participant'];
2696 if ($ids['participant'] &&
2697 !$participant->find(TRUE)
2699 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2701 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2703 $this->_relatedObjects
['participant'] = &$participant;
2705 // get the payment processor id from event - this is inaccurate see CRM-16923
2706 // in future we should look at throwing an exception here rather than an dubious guess.
2707 if (!$paymentProcessorID) {
2708 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2709 if ($paymentProcessorID) {
2710 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2715 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2716 if (!empty($relatedContact['individual_id'])) {
2717 $ids['related_contact'] = $relatedContact['individual_id'];
2720 if ($paymentProcessorID) {
2721 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2722 $this->is_test ?
'test' : 'live'
2724 $ids['paymentProcessor'] = $paymentProcessorID;
2725 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2728 // Add contribution id to $ids. CRM-20401
2729 $ids['contribution'] = $this->id
;
2734 * Create array of message information - ie. return html version, txt version, to field
2736 * @param array $input
2737 * Incoming information.
2738 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2739 * just check presence of recur object but maintaining legacy approach
2742 * IDs of related objects.
2743 * @param array $values
2744 * Any values that may have already been compiled by calling process.
2745 * This is augmented by values 'gathered' by gatherMessageValues
2746 * @param bool $returnMessageText
2747 * Distinguishes between whether to send message or return.
2748 * message text. We are working towards this function ALWAYS returning message text & calling
2749 * function doing emails / pdfs with it
2755 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2756 $this->loadRelatedObjects($input, $ids);
2758 if (empty($this->_component
)) {
2759 $this->_component
= $input['component'] ??
NULL;
2762 //not really sure what params might be passed in but lets merge em into values
2763 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2764 $values['is_email_receipt'] = !$returnMessageText;
2765 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text', 'pay_later_receipt'] as $fld) {
2766 if (!empty($input[$fld])) {
2767 $values[$fld] = $input[$fld];
2771 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2772 //what does recur 'mean here - to do with payment processor return functionality but
2773 // what is the importance
2774 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2775 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2777 $entityID = $entity = NULL;
2778 if (isset($ids['contribution'])) {
2779 $entity = 'contribution';
2780 $entityID = $ids['contribution'];
2782 if (!empty($ids['membership'])) {
2783 //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
2784 // 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
2785 // line having loaded an array
2786 $ids['membership'] = (array) $ids['membership'];
2787 $entity = 'membership';
2788 $entityID = $ids['membership'][0];
2791 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2792 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2793 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2795 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2796 //direct mode showing billing block, so use directIPN for temporary
2797 $template->assign('contributeMode', 'directIPN');
2800 // todo remove strtolower - check consistency
2801 if (strtolower($this->_component
) == 'event') {
2802 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2803 $values['event'] = [];
2805 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2807 //get location details
2809 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2810 'entity_table' => 'civicrm_event',
2812 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2815 'entity_table' => 'civicrm_event',
2816 'entity_id' => $ids['event'],
2817 'module' => 'CiviEvent',
2820 list($custom_pre_id,
2822 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2824 $values['custom_pre_id'] = $custom_pre_id;
2825 $values['custom_post_id'] = $custom_post_ids;
2826 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2827 //and cases involving status updation through ipn
2828 // whatever that means!
2829 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2830 // perhaps we should throw an e-notice if amount is set & force total_amount?
2831 if (!empty($input['amount'])) {
2832 $values['totalAmount'] = $input['amount'];
2834 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2835 if ($values['event']['is_email_confirm']) {
2836 $values['is_email_receipt'] = 1;
2839 if (!empty($ids['contribution'])) {
2840 $values['contributionId'] = $ids['contribution'];
2843 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2844 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2848 $values['contribution_id'] = $this->id
;
2849 if (!empty($ids['related_contact'])) {
2850 $values['related_contact'] = $ids['related_contact'];
2851 if (isset($ids['onbehalf_dupe_alert'])) {
2852 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2855 'contact_id' => $ids['contact'],
2856 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2857 'Home', 'id', 'name'
2860 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2861 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display'] ??
NULL);
2864 if ($this->is_test
) {
2867 if (!empty($this->_relatedObjects
['membership'])) {
2868 foreach ($this->_relatedObjects
['membership'] as $membership) {
2869 if ($membership->id
) {
2870 $values['membership_id'] = $membership->id
;
2871 $values['isMembership'] = TRUE;
2872 $values['membership_assign'] = TRUE;
2874 // need to set the membership values here
2875 $template->assign('membership_name',
2876 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2878 $template->assign('mem_start_date', $membership->start_date
);
2879 $template->assign('mem_join_date', $membership->join_date
);
2880 $template->assign('mem_end_date', $membership->end_date
);
2881 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2882 $template->assign('mem_status', $membership_status);
2883 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2884 $values['is_pay_later'] = 1;
2886 // Pass amount to floatval as string '0.00' is considered a
2887 // valid amount and includes Fee section in the mail.
2888 if (isset($values['amount'])) {
2889 $values['amount'] = floatval($values['amount']);
2892 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2893 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2894 $template->assign('cancelSubscriptionUrl', $url);
2895 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2896 $template->assign('updateSubscriptionBillingUrl', $url);
2897 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2898 $template->assign('updateSubscriptionUrl', $url);
2901 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2904 // otherwise if its about sending emails, continue sending without return, as we
2905 // don't want to exit the loop.
2910 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2916 * Gather values for contribution mail - this function has been created
2917 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2918 * Values related to the contribution in question are gathered
2920 * @param array $input
2921 * Input into function (probably from payment processor).
2922 * @param array $values
2924 * The set of ids related to the input.
2927 * @throws \CRM_Core_Exception
2929 public function _gatherMessageValues($input, &$values, $ids = []) {
2930 // set display address of contributor
2931 $values['billingName'] = '';
2932 if ($this->address_id
) {
2933 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
2934 $addressDetails = reset($addressDetails);
2935 $values['billingName'] = $addressDetails['name'] ??
'';
2937 // Else we assign the billing address of the contribution contact.
2939 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
2940 $addressDetails = reset($addressDetails);
2942 $values['address'] = $addressDetails['display'] ??
'';
2944 if ($this->_component
=== 'contribute') {
2945 //get soft contributions
2946 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2947 if (!empty($softContributions)) {
2948 // For pcp soft credit, there is no 'soft_credit' member it comes
2949 // back in different array members, but shortly after returning from
2950 // this function it calls _assignMessageVariablesToTemplate which does
2951 // its own lookup of any pcp soft credit, so we can skip it here.
2952 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
2954 if (isset($this->contribution_page_id
)) {
2955 // This is a call we want to use less, in favour of loading related objects.
2956 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2957 if ($this->contribution_page_id
) {
2958 // This is precautionary as there are some legacy flows, but it should really be
2960 if (!isset($this->_relatedObjects
['contributionPage'])) {
2961 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2963 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
2966 // no contribution page -probably back office
2968 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2969 $values['title'] = 'Contribution';
2971 // set lineItem for contribution
2973 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2974 if (!empty($lineItems)) {
2975 $firstLineItem = reset($lineItems);
2977 if (!empty($firstLineItem['price_set_id'])) {
2978 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
2979 'id' => $firstLineItem['price_set_id'],
2980 'return' => 'is_quick_config, id',
2982 $values['priceSetID'] = $priceSet['id'];
2984 foreach ($lineItems as &$eachItem) {
2985 if (isset($this->_relatedObjects
['membership'])
2986 && is_array($this->_relatedObjects
['membership'])
2987 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2988 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date
);
2989 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date
);
2990 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date
);
2992 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2993 // However, that does create upgrade pain so would be better to be phased in.
2994 $values['useForMember'] = empty($priceSet['is_quick_config']);
2996 $values['lineItem'][0] = $lineItems;
3000 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
3004 // if this is onbehalf of contribution then set related contact
3005 if (!empty($relatedContact['individual_id'])) {
3006 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3010 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
3013 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
3016 foreach ($groupTree as $key => $group) {
3017 if ($key === 'info') {
3021 foreach ($group['fields'] as $k => $customField) {
3022 $groupLabel = $group['title'];
3023 if (!empty($customField['customValue'])) {
3024 foreach ($customField['customValue'] as $customFieldValues) {
3025 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
3030 $values['customGroup'] = $customGroup;
3032 $values['is_pay_later'] = $this->is_pay_later
;
3038 * Assign message variables to template but try to break the habit.
3040 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3041 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3042 * multiple recurring payments for processors like IATS that use tokens.
3044 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3045 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3046 * Note we send directly from this function in some cases because it is only partly refactored.
3048 * Don't call this function directly as the signature will change.
3052 * @param bool $returnMessageText
3056 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3057 // @todo - this should have a better separation of concerns - ie.
3058 // gatherMessageValues should build an array of values to be assigned to the template
3059 // and this function should assign them (assigning null if not set).
3060 // the way the pcpParams & honor Params section works is a baby-step towards this.
3061 $template = CRM_Core_Smarty
::singleton();
3062 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
3063 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
3064 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
3065 $template->assign('billingName', $values['billingName']);
3067 // For some unit tests contribution cannot contain paymentProcessor information
3068 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
3069 $template->assign('contributeMode', CRM_Core_SelectValues
::contributeMode()[$billingMode] ??
NULL);
3071 //assign honor information to receipt message
3072 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
3075 'soft_credit_type' => NULL,
3076 'honor_block_is_active' => NULL,
3078 if (isset($softRecord['soft_credit'])) {
3079 //if id of contribution page is present
3080 if (!empty($values['id'])) {
3081 $values['honor'] = [
3082 'honor_profile_values' => [],
3083 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3084 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3087 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3088 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3091 //offline contribution
3092 $softCreditTypes = $softCredits = [];
3093 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3094 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3095 $softCredits[$key] = [
3096 'Name' => $softCredit['contact_name'],
3097 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3100 $template->assign('softCreditTypes', $softCreditTypes);
3101 $template->assign('softCredits', $softCredits);
3105 $dao = new CRM_Contribute_DAO_ContributionProduct();
3106 $dao->contribution_id
= $this->id
;
3107 if ($dao->find(TRUE)) {
3108 $premiumId = $dao->product_id
;
3109 $template->assign('option', $dao->product_option
);
3111 $productDAO = new CRM_Contribute_DAO_Product();
3112 $productDAO->id
= $premiumId;
3113 $productDAO->find(TRUE);
3114 $template->assign('selectPremium', TRUE);
3115 $template->assign('product_name', $productDAO->name
);
3116 $template->assign('price', $productDAO->price
);
3117 $template->assign('sku', $productDAO->sku
);
3119 $template->assign('title', $values['title'] ??
NULL);
3120 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3121 if (!$values['amount'] && isset($this->total_amount
)) {
3122 $values['amount'] = $this->total_amount
;
3127 'pcp_display_in_roll' => NULL,
3128 'pcp_roll_nickname' => NULL,
3129 'pcp_personal_note' => NULL,
3133 if (strtolower($this->_component
) == 'contribute') {
3135 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3136 $softDAO->contribution_id
= $this->id
;
3137 if ($softDAO->find(TRUE)) {
3138 $pcpParams['pcpBlock'] = TRUE;
3139 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3140 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3141 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3143 //assign the pcp page title for email subject
3144 $pcpDAO = new CRM_PCP_DAO_PCP();
3145 $pcpDAO->id
= $softDAO->pcp_id
;
3146 if ($pcpDAO->find(TRUE)) {
3147 $pcpParams['title'] = $pcpDAO->title
;
3151 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3152 $template->assign($templateKey, $templateValue);
3155 if ($this->financial_type_id
) {
3156 $values['financial_type_id'] = $this->financial_type_id
;
3159 $template->assign('trxn_id', $this->trxn_id
);
3160 $template->assign('receive_date',
3161 CRM_Utils_Date
::processDate($this->receive_date
)
3163 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3164 $template->assign('action', $this->is_test ?
1024 : 1);
3165 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3166 $template->assign('is_monetary', 1);
3167 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3168 $template->assign('currency', $this->currency
);
3169 $template->assign('address', CRM_Utils_Address
::format($input));
3170 if (!empty($values['customGroup'])) {
3171 $template->assign('customGroup', $values['customGroup']);
3173 if (!empty($values['softContributions'])) {
3174 $template->assign('softContributions', $values['softContributions']);
3176 if ($this->_component
== 'event') {
3177 $template->assign('title', $values['event']['title']);
3178 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3180 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3181 $viewRoles[] = $participantRoles[$v];
3183 $values['event']['participant_role'] = implode(', ', $viewRoles);
3184 $template->assign('event', $values['event']);
3185 $template->assign('participant', $values['participant']);
3186 $template->assign('location', $values['location']);
3187 $template->assign('customPre', $values['custom_pre_id']);
3188 $template->assign('customPost', $values['custom_post_id']);
3191 if ($this->_relatedObjects
['participant']->is_test
) {
3195 $values['params'] = [];
3196 //to get email of primary participant.
3197 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3198 $primaryAmount[] = [
3199 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3200 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3202 //build an array of cId/pId of participants
3203 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3204 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3205 //send receipt to additional participant if exists
3206 if (count($additionalIDs)) {
3207 $template->assign('isPrimary', 0);
3208 $template->assign('customProfile', NULL);
3209 //set additionalParticipant true
3210 $values['params']['additionalParticipant'] = TRUE;
3211 foreach ($additionalIDs as $pId => $cId) {
3213 //to change the status pending to completed
3214 $additional = new CRM_Event_DAO_Participant();
3215 $additional->id
= $pId;
3216 $additional->contact_id
= $cId;
3217 $additional->find(TRUE);
3218 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3219 $additional->status_id
= 1;
3220 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3221 //if additional participant dont have email
3223 if (!$additionalParticipantInfo) {
3224 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3227 'label' => $additional->fee_level
,
3228 'amount' => $additional->fee_amount
,
3230 $primaryAmount[] = [
3231 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3232 'amount' => $additional->fee_amount
,
3234 $additional->save();
3235 $template->assign('amount', $amount);
3236 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3240 //build an array of custom profile and assigning it to template
3241 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3243 if (count($customProfile)) {
3244 $template->assign('customProfile', $customProfile);
3247 // for primary contact
3248 $values['params']['additionalParticipant'] = FALSE;
3249 $template->assign('isPrimary', 1);
3250 $template->assign('amount', $primaryAmount);
3251 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3252 if ($this->payment_instrument_id
) {
3253 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3254 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3256 // carry paylater, since we did not created billing,
3257 // so need to pull email from primary location, CRM-4395
3258 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3264 * Check whether payment processor supports
3265 * cancellation of contribution subscription
3267 * @param int $contributionId
3270 * @param bool $isNotCancelled
3274 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3275 $cacheKeyString = "$contributionId";
3276 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3278 static $supportsCancel = [];
3280 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3281 $supportsCancel[$cacheKeyString] = FALSE;
3282 $isCancelled = FALSE;
3284 if ($isNotCancelled) {
3285 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3288 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3289 if (!empty($paymentObject)) {
3290 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3293 return $supportsCancel[$cacheKeyString];
3297 * Check whether subscription is already cancelled.
3299 * @param int $contributionId
3303 * contribution status
3305 public static function isSubscriptionCancelled($contributionId) {
3307 SELECT cr.contribution_status_id
3308 FROM civicrm_contribution_recur cr
3309 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3310 WHERE con.id = %1 LIMIT 1";
3311 $params = [1 => [$contributionId, 'Integer']];
3312 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3313 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3314 if ($status == 'Cancelled') {
3321 * Create all financial accounts entry.
3323 * @param array $params
3324 * Contribution object, line item array and params for trxn.
3327 * @param array $financialTrxnValues
3329 * @return null|\CRM_Core_BAO_FinancialTrxn
3331 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3332 $skipRecords = $update = $return = $isRelatedId = FALSE;
3333 $isUpdate = !empty($params['prevContribution']);
3335 $additionalParticipantId = [];
3336 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3337 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3339 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3340 $entityId = $params['participant_id'];
3341 $entityTable = 'civicrm_participant';
3342 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3344 elseif (!empty($params['membership_id'])) {
3345 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3346 // are created off one contribution should be handled elsewhere
3347 $entityId = $params['membership_id'];
3348 $entityTable = 'civicrm_membership';
3351 $entityId = $params['contribution']->id
;
3352 $entityTable = 'civicrm_contribution';
3355 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3356 $isRelatedId = TRUE;
3359 $entityID[] = $entityId;
3360 if (!empty($additionalParticipantId)) {
3361 $entityID +
= $additionalParticipantId;
3363 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3364 if (empty($params['prevContribution'])) {
3368 $statusId = $params['contribution']->contribution_status_id
;
3370 // build line item array if its not set in $params
3371 if (empty($params['line_item']) ||
$additionalParticipantId) {
3372 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3375 if ($contributionStatus != 'Failed' &&
3376 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3378 $skipRecords = TRUE;
3383 if (in_array($contributionStatus, $pendingStatus)) {
3384 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3385 $params['financial_type_id'],
3386 'Accounts Receivable Account is'
3389 elseif (!empty($params['payment_processor'])) {
3390 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3391 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3392 'id' => $params['payment_processor'],
3393 'return' => 'payment_instrument_id',
3396 elseif (!empty($params['payment_instrument_id'])) {
3397 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3399 // dev/financial#160 - If this is a contribution update, also check for an existing payment_instrument_id.
3400 elseif ($isUpdate && $params['prevContribution']->payment_instrument_id
) {
3401 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount((int) $params['prevContribution']->payment_instrument_id
);
3404 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3405 $queryParams = [1 => [$relationTypeId, 'Integer']];
3406 $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);
3409 $totalAmount = $params['total_amount'] ??
NULL;
3410 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3411 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3413 //build financial transaction params
3415 'contribution_id' => $params['contribution']->id
,
3416 'to_financial_account_id' => $params['to_financial_account_id'],
3417 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3418 'total_amount' => $totalAmount,
3419 'fee_amount' => $params['fee_amount'] ??
NULL,
3420 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3421 'currency' => $params['contribution']->currency
,
3422 'trxn_id' => $params['contribution']->trxn_id
,
3423 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3424 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3425 // this should really default to completed (after discussion).
3426 'status_id' => $statusId,
3427 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3428 'check_number' => $params['check_number'] ??
NULL,
3429 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3430 'card_type_id' => $params['card_type_id'] ??
NULL,
3432 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3433 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3434 if (isset($params['refund_trxn_id'])) {
3435 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3436 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3439 //CRM-16259, set is_payment flag for non pending status
3440 if (!in_array($contributionStatus, $pendingStatus)) {
3441 $trxnParams['is_payment'] = 1;
3443 if (!empty($params['payment_processor'])) {
3444 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3447 if (isset($fromFinancialAccountId)) {
3448 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3451 // consider external values passed for recording transaction entry
3452 if (!empty($financialTrxnValues)) {
3453 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3455 if (empty($trxnParams['payment_processor_id'])) {
3456 unset($trxnParams['payment_processor_id']);
3459 $params['trxnParams'] = $trxnParams;
3463 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3464 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3465 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3466 if (!isset($params['trxnParams']['trxn_id'])) {
3467 // Actually I have no idea why we are overwriting any values from the previous contribution.
3468 // (filling makes sense to me). However, only protecting this value as I really really know we
3469 // don't want this one overwritten.
3471 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3473 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3475 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3476 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3477 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3479 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3480 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3483 //if financial type is changed
3484 if (!empty($params['financial_type_id']) &&
3485 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3487 $accountRelationship = 'Income Account is';
3488 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3489 $accountRelationship = 'Deferred Revenue Account is';
3491 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3492 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3493 if ($oldFinancialAccount != $newFinancialAccount) {
3494 $params['total_amount'] = 0;
3495 // If we have a fee amount set reverse this as well.
3496 if (isset($params['fee_amount'])) {
3497 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3499 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3500 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3501 $params['prevContribution']->financial_type_id
, $accountRelationship);
3504 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3505 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3506 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3509 self
::updateFinancialAccounts($params, 'changeFinancialType');
3510 $params['skipLineItem'] = FALSE;
3511 foreach ($params['line_item'] as &$lineItems) {
3512 foreach ($lineItems as &$line) {
3513 $line['financial_type_id'] = $params['financial_type_id'];
3516 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3517 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3518 $params['financial_account_id'] = $newFinancialAccount;
3519 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3520 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3521 if (isset($params['fee_amount'])) {
3522 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3524 self
::updateFinancialAccounts($params);
3525 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3526 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3528 $params['deferred_financial_account_id'] = $newFinancialAccount;
3532 //Update contribution status
3533 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3534 if (!isset($params['refund_trxn_id'])) {
3535 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3536 // gets preference over another so I am only 'protecting' a very specific tested flow
3537 // and letting natural justice take care of the rest.
3538 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3540 if (!empty($params['contribution_status_id']) &&
3541 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3543 //Update Financial Records
3544 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3545 if ($callUpdateFinancialAccounts) {
3546 self
::updateFinancialAccounts($params, 'changedStatus');
3547 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3552 // change Payment Instrument for a Completed contribution
3553 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3554 // instrument is null and now new payment instrument is added along with the payment
3555 if (!$params['contribution']->payment_instrument_id
) {
3556 $params['contribution']->find(TRUE);
3558 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3559 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3561 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3562 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3565 //if Change contribution amount
3566 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3567 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3568 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3569 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3570 if (isset($totalAmount) &&
3571 $totalAmount != $params['prevContribution']->total_amount
3573 //Update Financial Records
3574 $params['trxnParams']['from_financial_account_id'] = NULL;
3575 self
::updateFinancialAccounts($params, 'changedAmount');
3576 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3581 // Looks like we might have a data correction update.
3582 // This would be a case where a transaction id has been entered but it is incorrect &
3583 // the person goes back in & fixes it, as opposed to a new transaction.
3584 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3585 // the data fix scenario.
3587 if (isset($params['refund_trxn_id'])) {
3588 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3589 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3590 civicrm_api3('FinancialTrxn', 'create', [
3591 'id' => $refundIDs['financialTrxnId'],
3592 'trxn_id' => $params['refund_trxn_id'],
3596 $cardType = $params['card_type_id'] ??
NULL;
3597 $panTruncation = $params['pan_truncation'] ??
NULL;
3598 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3603 // records finanical trxn and entity financial trxn
3604 // also make it available as return value
3605 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3606 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3607 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3608 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3609 $params['entity_id'] = $financialTxn->id
;
3610 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3611 self
::$_trxnIDs[] = $financialTxn->id
;
3615 // record line items and financial items
3616 if (empty($params['skipLineItem'])) {
3617 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3620 // create batch entry if batch_id is passed and
3621 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3622 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3624 'batch_id' => $params['batch_id'],
3625 'entity_table' => 'civicrm_financial_trxn',
3626 'entity_id' => $financialTxn->id
,
3628 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3631 // when a fee is charged
3632 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3633 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3636 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3637 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3639 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3640 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3641 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3643 unset($params['line_item']);
3644 self
::$_trxnIDs = NULL;
3649 * Update all financial accounts entry.
3651 * @param array $params
3652 * Contribution object, line item array and params for trxn.
3654 * @param string $context
3657 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3658 * adds unpredictability.
3661 public static function updateFinancialAccounts(&$params, $context = NULL) {
3663 $inputParams = $params;
3664 $isARefund = self
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
);
3666 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3667 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3668 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount
);
3671 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3672 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3673 $params['entity_id'] = $trxn->id
;
3675 $itemParams['entity_table'] = 'civicrm_line_item';
3676 $trxnIds['id'] = $params['entity_id'];
3677 $previousLineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution']->id
);
3678 foreach ($params['line_item'] as $fieldId => $fields) {
3679 $params = self
::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3684 * Is this contribution status a reversal.
3686 * If so we would expect to record a negative value in the financial_trxn table.
3688 * @param int $status_id
3692 public static function isContributionStatusNegative($status_id) {
3693 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3694 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3698 * Check status validation on update of a contribution.
3700 * @param array $values
3701 * Previous form values before submit.
3703 * @param array $fields
3704 * The input form values.
3706 * @param array $errors
3711 public static function checkStatusValidation($values, &$fields, &$errors) {
3712 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3713 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3714 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3718 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3720 'Cancelled' => ['Completed', 'Refunded'],
3721 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3722 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3723 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3724 'Refunded' => ['Cancelled', 'Completed'],
3725 'Partially paid' => ['Completed'],
3726 'Pending refund' => ['Completed', 'Refunded'],
3727 'Failed' => ['Pending'],
3730 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3731 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3733 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3734 1 => $contributionStatuses[$values['contribution_status_id']],
3735 2 => $contributionStatuses[$fields['contribution_status_id']],
3741 * Delete contribution of contact.
3743 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3745 * @param int $contactId
3749 public static function deleteContactContribution($contactId) {
3750 $contribution = new CRM_Contribute_DAO_Contribution();
3751 $contribution->contact_id
= $contactId;
3752 $contribution->find();
3753 while ($contribution->fetch()) {
3754 self
::deleteContribution($contribution->id
);
3759 * Get options for a given contribution field.
3761 * @param string $fieldName
3762 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3763 * @param array $props whatever is known about this dao object.
3765 * @return array|bool
3766 * @see CRM_Core_DAO::buildOptions
3769 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3770 $className = __CLASS__
;
3772 if (isset($props['orderColumn'])) {
3773 $params['orderColumn'] = $props['orderColumn'];
3775 switch ($fieldName) {
3776 // This field is not part of this object but the api supports it
3777 case 'payment_processor':
3778 $className = 'CRM_Contribute_BAO_ContributionPage';
3779 // Filter results by contribution page
3780 if (!empty($props['contribution_page_id'])) {
3781 $page = civicrm_api('contribution_page', 'getsingle', [
3783 'id' => ($props['contribution_page_id']),
3785 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3786 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3790 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3791 case 'honor_type_id':
3792 $className = 'CRM_Contribute_BAO_ContributionSoft';
3793 $fieldName = 'soft_credit_type_id';
3794 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3797 case 'contribution_status_id':
3798 if ($context !== 'validate') {
3799 $params['condition'] = "v.name <> 'Template'";
3802 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3806 * Validate financial type.
3808 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3810 * @param int $financialTypeId
3811 * Financial Type id.
3813 * @param string $relationName
3815 * @return array|bool
3817 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3818 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3820 if (!$financialAccount) {
3821 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3827 * @param int $targetCid
3828 * @param $activityType
3829 * @param string $title
3830 * @param int $contributionId
3831 * @param string $totalAmount
3832 * @param string $currency
3833 * @param string $trxn_date
3835 * @throws \CRM_Core_Exception
3836 * @throws \CiviCRM_API3_Exception
3838 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3839 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3840 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3841 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3842 // source record id would be the contribution id
3843 $srcRecId = $contributionId;
3847 'source_contact_id' => $targetCid,
3848 'source_record_id' => $srcRecId,
3849 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3850 'subject' => $subject,
3851 'activity_date_time' => $date,
3852 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3853 'skipRecentView' => TRUE,
3856 // create activity with target contacts
3857 $session = CRM_Core_Session
::singleton();
3858 $id = $session->get('userID');
3860 $activityParams['source_contact_id'] = $id;
3861 $activityParams['target_contact_id'][] = $targetCid;
3863 civicrm_api3('Activity', 'create', $activityParams);
3867 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3870 * @param string $component
3871 * @param bool $getTrxnInfo
3875 * @throws \CRM_Core_Exception
3876 * @throws \CiviCRM_API3_Exception
3878 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3879 // @todo deprecate passing in component - always call with contribution.
3880 if ($component == 'event') {
3881 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3883 if (!$contributionId) {
3884 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3885 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3886 $id = $primaryParticipantId;
3888 if (!$contributionId) {
3893 elseif ($component == 'membership') {
3894 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3897 $contributionId = $id;
3900 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3901 // but need to unpick the whole trxn_id it's returning first.
3902 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3903 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3905 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3906 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3908 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3910 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3912 $contribution = civicrm_api3('Contribution', 'getsingle', [
3913 'id' => $contributionId,
3917 'contribution_status_id',
3918 'financial_type_id',
3922 $info['payLater'] = $contribution['is_pay_later'];
3923 $info['contribution_status'] = $contribution['contribution_status'];
3924 $info['currency'] = $contribution['currency'];
3926 $info['total'] = $total;
3927 $info['paid'] = $total - $paymentBalance;
3928 $info['balance'] = $paymentBalance;
3930 $info['component'] = $component;
3931 if ($getTrxnInfo && $baseTrxnId) {
3932 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
3935 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
3940 * Get the outstanding balance on a contribution.
3942 * @param int $contributionId
3943 * @param float $contributionTotal
3944 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
3948 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
3949 if ($contributionTotal === NULL) {
3950 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3953 return (float) CRM_Utils_Money
::subtractCurrencies(
3955 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
3956 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
3961 * Get the tax amount (misnamed function).
3963 * @param array $params
3966 * @throws \CiviCRM_API3_Exception
3968 protected static function checkTaxAmount($params) {
3969 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3971 // Update contribution.
3972 if (!empty($params['id'])) {
3973 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
3974 // there are no tax implications - early return.
3975 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
3978 if (empty($params['prevContribution'])) {
3979 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
3982 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
3983 if (!isset($params[$field])) {
3984 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
3985 // Tax amount gets added back on later....
3986 $params['total_amount'] = $params['prevContribution']->total_amount
-
3987 $params['prevContribution']->tax_amount
;
3990 $params[$field] = $params['prevContribution']->$field;
3991 if ($params[$field] != $params['prevContribution']->$field) {
3997 self
::calculateMissingAmountParams($params, $params['id']);
3998 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
3999 // Assign tax Amount on update of contribution
4000 if (!empty($params['prevContribution']->tax_amount
)) {
4001 $params['tax_amount'] = 'null';
4002 foreach ($params['line_item'] as $setID => $priceField) {
4003 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4004 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4011 // New Contribution and update of contribution with tax rate financial type
4012 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4013 empty($params['skipLineItem'])) {
4014 $taxRateParams = $taxRates[$params['financial_type_id']];
4015 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4016 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4018 foreach ($params['line_item'] as $setID => $priceField) {
4019 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4020 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4023 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4025 elseif (isset($params['api.line_item.create'])) {
4026 // Update total amount of contribution using lineItem
4027 $taxAmountArray = [];
4028 foreach ($params['api.line_item.create'] as $key => $value) {
4029 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4030 $taxRate = $taxRates[$value['financial_type_id']];
4031 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4032 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4035 $params['tax_amount'] = array_sum($taxAmountArray);
4036 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4043 * Check financial type validation on update of a contribution.
4045 * @param int $financialTypeId
4046 * Value of latest Financial Type.
4048 * @param int $contributionId
4051 * @param array $errors
4056 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4057 if (!empty($financialTypeId)) {
4058 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4059 if ($oldFinancialTypeId == $financialTypeId) {
4063 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4065 '1' => [$contributionId, 'Integer'],
4067 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4068 if ($result->N
> 1) {
4069 $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.');
4074 * Update related pledge payment payments.
4076 * This function has been refactored out of the back office contribution form and may
4077 * still overlap with other functions.
4079 * @param string $action
4080 * @param int $pledgePaymentID
4081 * @param int $contributionID
4082 * @param bool $adjustTotalAmount
4083 * @param float $total_amount
4084 * @param float $original_total_amount
4085 * @param int $contribution_status_id
4086 * @param int $original_contribution_status_id
4088 public static function updateRelatedPledge(
4094 $original_total_amount,
4095 $contribution_status_id,
4096 $original_contribution_status_id
4098 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4102 if ($pledgePaymentID) {
4103 //store contribution id in payment record.
4104 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4107 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4114 if (!$pledgePaymentID) {
4117 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4123 $updatePledgePaymentStatus = FALSE;
4125 // If either the status or the amount has changed we update the pledge status.
4126 if ($action & CRM_Core_Action
::ADD
) {
4127 $updatePledgePaymentStatus = TRUE;
4129 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4130 ($original_total_amount != $total_amount))
4132 $updatePledgePaymentStatus = TRUE;
4135 if ($updatePledgePaymentStatus) {
4136 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4138 $contribution_status_id,
4147 * Is there only one line item attached to the contribution.
4153 * @throws \CiviCRM_API3_Exception
4155 public static function isSingleLineItem($id) {
4156 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4157 return ($lineItemCount == 1);
4161 * Complete an order.
4163 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4165 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4167 * Moving it out of the BaseIPN class is just the first step.
4169 * @param array $input
4171 * @param \CRM_Contribute_BAO_Contribution $contribution
4172 * @param bool $isPostPaymentCreate
4173 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4174 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4175 * transitioning related elements).
4178 * @throws \CRM_Core_Exception
4179 * @throws \CiviCRM_API3_Exception
4181 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4182 $transaction = new CRM_Core_Transaction();
4183 // @todo see if we even need this - it's used further down to create an activity
4184 // but the BAO layer should create that - we just need to add a test to cover it & can
4185 // maybe remove $ids altogether.
4186 $participantID = $ids['participant'];
4187 $recurringContributionID = $ids['contributionRecur'];
4189 // Unset ids just to make it clear it's not used again.
4191 // The previous details are used when calculating line items so keep it before any code that 'does something'
4192 if (!empty($contribution->id
)) {
4193 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(['id' => $contribution->id
]);
4195 $inputContributionWhiteList = [
4200 'payment_instrument_id',
4205 'contribution_status_id',
4208 'financial_type_id',
4211 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
4213 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4215 $contributionParams = array_merge([
4216 'contribution_status_id' => $completedContributionStatusID,
4217 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4220 $contributionParams['payment_processor'] = $paymentProcessorId;
4222 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4223 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4226 if ($recurringContributionID) {
4227 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4229 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4231 $contributionResult = self
::repeatTransaction($contribution, $input, $contributionParams);
4232 $contributionID = (int) $contribution->id
;
4234 if ($input['component'] == 'contribute') {
4235 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4236 self
::updateMembershipBasedOnCompletionOfContribution(
4243 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4244 $participantParams['id'] = $participantID;
4245 $participantParams['status_id'] = 'Registered';
4246 civicrm_api3('Participant', 'create', $participantParams);
4250 $contributionParams['id'] = $contributionID;
4251 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4253 if (!$contributionResult) {
4254 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4257 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4259 $transaction->commit();
4260 \Civi
::log()->info("Contribution {$contributionParams['id']} updated successfully");
4262 // @todo - check if Contribution::create does this, test, remove.
4263 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4264 $contributionParams['contribution_status_id'], $input['amount']);
4266 if (self
::isEmailReceipt($input, $contribution->contribution_page_id
, $recurringContributionID)) {
4267 civicrm_api3('Contribution', 'sendconfirmation', [
4268 'id' => $contributionID,
4269 'payment_processor_id' => $paymentProcessorId,
4271 \Civi
::log()->info("Contribution {$contributionParams['id']} Receipt sent");
4274 return $contributionResult;
4278 * Send receipt from contribution.
4280 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4282 * Note that the compose message part has been moved to contribution
4283 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4285 * @param array $input
4286 * Incoming data from Payment processor.
4288 * Related object IDs.
4289 * @param int $contributionID
4290 * @param bool $returnMessageText
4291 * Should text be returned instead of sent. This.
4292 * is because the function is also used to generate pdfs
4295 * @throws \CRM_Core_Exception
4296 * @throws \CiviCRM_API3_Exception
4297 * @throws \Exception
4299 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4301 $contribution = new CRM_Contribute_BAO_Contribution();
4302 $contribution->id
= $contributionID;
4303 if (!$contribution->find(TRUE)) {
4304 throw new CRM_Core_Exception('Contribution does not exist');
4306 $contribution->loadRelatedObjects($input, $ids, TRUE);
4307 // set receipt from e-mail and name in value
4308 if (!$returnMessageText) {
4309 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4311 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4312 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4313 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4314 civicrm_api3('Contribution', 'create', [
4315 'receipt_date' => 'now',
4316 'id' => $contribution->id
,
4323 * Generate From email and from name in an array values
4325 * @param array $input
4326 * @param \CRM_Contribute_BAO_Contribution $contribution
4330 public static function generateFromEmailAndName($input, $contribution) {
4331 // Use input value if supplied.
4332 if (!empty($input['receipt_from_email'])) {
4334 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4335 $input['receipt_from_email'],
4338 // if we are still empty see if we can use anything from a contribution page.
4340 if (!empty($contribution->contribution_page_id
)) {
4341 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4343 // if we are still empty see if we can use anything from a contribution page.
4344 if (!empty($pageValues['receipt_from_email'])) {
4346 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4347 $pageValues['receipt_from_email'],
4350 // If we are still empty fall back to the domain or logged in user information.
4351 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4355 * Load related memberships.
4359 * @return array $ids
4364 * Note that in theory it should be possible to retrieve these from the line_item table
4365 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4366 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4367 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4368 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4370 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4373 public function loadRelatedMembershipObjects($ids = []) {
4375 SELECT membership_id
4376 FROM civicrm_membership_payment
4377 WHERE contribution_id = %1 ";
4378 $params = [1 => [$this->id
, 'Integer']];
4379 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4381 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4382 while ($dao->fetch()) {
4383 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4384 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4388 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4389 foreach ($ids['membership'] as $id) {
4391 $membership = new CRM_Member_BAO_Membership();
4392 $membership->id
= $id;
4393 if (!$membership->find(TRUE)) {
4394 throw new Exception("Could not find membership record: $id");
4396 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4397 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4398 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4399 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4408 * Function use to store line item proportionally in in entity financial trxn table
4410 * @param array $trxnParams
4412 * @param int $trxnId
4414 * @param float $contributionTotalAmount
4416 * @throws \CiviCRM_API3_Exception
4418 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4419 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4420 if (!empty($lineItems)) {
4421 // get financial item
4422 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4424 'contribution_total_amount' => $contributionTotalAmount,
4425 'trxn_total_amount' => $trxnParams['total_amount'],
4426 'trxn_id' => $trxnId,
4428 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4433 * Checks if line items total amounts
4434 * match the contribution total amount.
4436 * @param array $params
4437 * array of order params.
4439 * @throws \API_Exception
4441 public static function checkLineItems(&$params) {
4442 $totalAmount = $params['total_amount'] ??
NULL;
4443 $lineItemAmount = 0;
4445 foreach ($params['line_items'] as &$lineItems) {
4446 foreach ($lineItems['line_item'] as &$item) {
4447 if (empty($item['financial_type_id'])) {
4448 $item['financial_type_id'] = $params['financial_type_id'];
4450 $lineItemAmount +
= $item['line_total'] +
($item['tax_amount'] ??
0.00);
4454 if (!isset($totalAmount)) {
4455 $params['total_amount'] = $lineItemAmount;
4458 $currency = $params['currency'] ?? CRM_Core_Config
::singleton()->defaultCurrency
;
4460 if (!CRM_Utils_Money
::equals($totalAmount, $lineItemAmount, $currency)) {
4461 throw new CRM_Contribute_Exception_CheckLineItemsException();
4467 * Get the financial account for the item associated with the new transaction.
4469 * @param array $params
4470 * @param int $default
4474 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4476 if (!empty($params['financial_account_id'])) {
4477 return $params['financial_account_id'];
4480 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4481 $preferredAccountsRelationships = [
4482 'Refunded' => 'Credit/Contra Revenue Account is',
4483 'Chargeback' => 'Chargeback Account is',
4486 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4487 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4488 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4490 $preferredAccountsRelationships[$contributionStatus]
4498 * ContributionPage values were being imposed onto values.
4500 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4501 * REALLY didn't want superimposed. The rest are left there in their overkill out
4504 * The rationale for making this explicit is that it was a case of carefully set values being
4505 * seemingly randonly overwritten without much care. In general I think array randomly setting
4506 * variables en mass is risky.
4508 * @param array $values
4512 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4513 $contributionPageValues = [];
4514 CRM_Contribute_BAO_ContributionPage
::setValues(
4515 $this->contribution_page_id
,
4516 $contributionPageValues
4519 // These are the values that I believe to be useful.
4522 'pay_later_receipt',
4524 'receipt_from_email',
4525 'receipt_from_name',
4529 'honoree_profile_id',
4530 'onbehalf_profile_id',
4531 'honor_block_is_active',
4532 // Kinda might be - but would be on the contribution...
4535 // Included for 'fear of regression' but can't justify any use for these....
4537 'payment_processor',
4538 'financial_type_id',
4539 'amount_block_is_active',
4544 'default_amount_id',
4548 'initial_amount_help_text',
4549 'initial_amount_label',
4551 'is_allow_other_amount',
4552 'is_billing_required',
4553 'is_confirm_enabled',
4554 'is_credit_card_only',
4556 'is_partial_payment',
4557 'is_recur_installments',
4558 'is_recur_interval',
4562 'min_initial_amount',
4563 'recur_frequency_unit',
4570 foreach ($valuesToCopy as $valueToCopy) {
4571 if (isset($contributionPageValues[$valueToCopy])) {
4572 if ($valueToCopy === 'title') {
4573 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4576 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4584 * Get values of CiviContribute Settings
4585 * and check if its enabled or not.
4586 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4587 * in serialized form. Usually this should be stored as flat settings for each form fields
4588 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4589 * settings we will live with an inconsistency because it's too hard to change for now.
4590 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4593 * @param string $name
4598 public static function checkContributeSettings($name) {
4599 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4600 return $contributeSettings[$name] ??
NULL;
4604 * Get the contribution as it is in the database before being updated.
4606 * @param int $contributionID
4608 * @return \CRM_Contribute_BAO_Contribution|null
4610 private static function getOriginalContribution($contributionID) {
4611 return self
::getValues(['id' => $contributionID]);
4615 * Get the amount for the financial item row.
4617 * Helper function to start to break down recordFinancialTransactions for readability.
4619 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4621 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4622 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4625 * @param array $params
4626 * Params as passed to contribution.create
4628 * @param string $context
4629 * changeFinancialType| changedAmount
4630 * @param array $lineItemDetails
4632 * @param bool $isARefund
4633 * Is this a refund / negative transaction.
4634 * @param int $previousLineItemTotal
4637 * @todo move recordFinancialAccounts & helper functions to their own class?
4640 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4641 if ($context == 'changedAmount') {
4642 $lineTotal = $lineItemDetails['line_total'];
4643 if ($lineTotal != $previousLineItemTotal) {
4644 $lineTotal -= $previousLineItemTotal;
4648 elseif ($context == 'changeFinancialType') {
4649 return -$lineItemDetails['line_total'];
4651 elseif ($context == 'changedStatus') {
4652 $cancelledTaxAmount = 0;
4654 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $lineItemDetails, '0.00');
4656 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total'] +
(float) $cancelledTaxAmount);
4658 elseif ($context === NULL) {
4659 // erm, yes because? but, hey, it's tested.
4660 return $lineItemDetails['line_total'];
4662 elseif (empty($lineItemDetails['line_total'])) {
4663 // follow legacy code path
4664 CRM_Core_Error
::deprecatedWarning('Deprecated bit of code, please log a ticket explaining how you got here!');
4665 return $params['total_amount'];
4668 return self
::getMultiplier($params['contribution']->contribution_status_id
, $context) * ((float) $lineItemDetails['line_total']);
4673 * Get the multiplier for adjusting rows.
4675 * If we are dealing with a refund or cancellation then it will be a negative
4676 * amount to reflect the negative transaction.
4678 * If we are changing Financial Type it will be a negative amount to
4679 * adjust down the old type.
4681 * @param int $contribution_status_id
4682 * @param string $context
4686 protected static function getMultiplier($contribution_status_id, $context) {
4687 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($contribution_status_id)) {
4694 * Does this transaction reflect a payment instrument change.
4696 * @param array $params
4697 * @param array $pendingStatuses
4701 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4702 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4704 if (array_key_exists('payment_instrument_id', $params)) {
4705 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4706 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4708 //check if status is changed from Pending to Completed
4709 // do not update payment instrument changes for Pending to Completed
4710 if (!($contributionStatus == 'Completed' &&
4711 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4716 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4717 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4718 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4722 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4723 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4725 // another special case when check number is changed, create new financial records
4726 // create financial trxn with negative amount
4734 * Update the memberships associated with a contribution if it has been completed.
4736 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4737 * load them in this function. Code clean up would compensate for any minor performance implication.
4739 * @param int $contributionID
4740 * @param string $changeDate
4742 * @throws \CRM_Core_Exception
4743 * @throws \CiviCRM_API3_Exception
4745 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4746 $memberships = self
::getRelatedMemberships($contributionID);
4747 foreach ($memberships as $membership) {
4748 $membershipParams = [
4749 'id' => $membership['id'],
4750 'contact_id' => $membership['contact_id'],
4751 'is_test' => $membership['is_test'],
4752 'membership_type_id' => $membership['membership_type_id'],
4753 'membership_activity_status' => 'Completed',
4756 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4757 $membershipParams['membership_type_id'],
4758 $membershipParams['is_test'],
4759 $membershipParams['id']
4762 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4763 // this picks up membership type changes during renewals
4764 // @todo this is almost certainly an obsolete sql call, the pre-change
4765 // membership is accessible via $this->_relatedObjects
4767 SELECT membership_type_id
4768 FROM civicrm_membership_log
4769 WHERE membership_id={$membershipParams['id']}
4772 $dao = CRM_Core_DAO
::executeQuery($sql);
4773 if ($dao->fetch()) {
4774 if (!empty($dao->membership_type_id
)) {
4775 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4778 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4779 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4780 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4781 // 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.
4782 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4783 // @todo once apiv4 ships with core switch to that & find sanity.
4784 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4785 $membershipParams['membership_type_id'],
4789 // @todo remove all this stuff in favour of letting the api call further down handle in
4790 // (it is a duplication of what the api does).
4791 $dates = array_fill_keys([
4796 if ($currentMembership) {
4798 * Fixed FOR CRM-4433
4799 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4800 * when Contribution mode is notify and membership is for renewal )
4802 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4804 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4806 // @todo - we should pass membership_type_id instead of null here but not
4807 // adding as not sure of testing
4808 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4809 $changeDate, NULL, $membershipParams['num_terms']
4811 $dates['join_date'] = $currentMembership['join_date'];
4814 //get the status for membership.
4815 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4817 $dates['join_date'],
4820 $membershipParams['membership_type_id'],
4824 unset($dates['end_date']);
4825 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4826 //we might be renewing membership,
4827 //so make status override false.
4828 $membershipParams['is_override'] = FALSE;
4829 $membershipParams['status_override_end_date'] = 'null';
4830 civicrm_api3('Membership', 'create', $membershipParams);
4835 * Get payment links as they relate to a contribution.
4837 * If a payment can be made then include a payment link & if a refund is appropriate
4838 * then a refund link.
4841 * @param float $balance
4842 * @param string $contributionStatus
4845 * $actionLinks Links array containing:
4849 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4850 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4851 // In general the balance is the best way to determine if a payment can be added or not,
4852 // but not for Failed contributions, where we don't accept additional payments at the moment.
4853 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4854 // do accept more payments agains them.
4859 'url' => CRM_Utils_System
::url('civicrm/payment', [
4865 'title' => ts('Record Payment'),
4868 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4870 'url' => CRM_Utils_System
::url('civicrm/payment', [
4877 'title' => ts('Submit Credit Card payment'),
4881 'url' => CRM_Utils_System
::url('civicrm/payment', [
4887 'title' => ts('Record Refund'),
4889 return $actionLinks;
4893 * Get a query to determine the amount donated by the contact/s in the current financial year.
4895 * @param array $contactIDs
4899 public static function getAnnualQuery($contactIDs) {
4900 $contactIDs = implode(',', $contactIDs);
4901 $config = CRM_Core_Config
::singleton();
4902 $currentMonth = date('m');
4903 $currentDay = date('d');
4905 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
4907 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
4908 (int) $config->fiscalYearStart
['d'] > $currentDay
4911 $year = date('Y') - 1;
4916 $nextYear = $year +
1;
4918 if ($config->fiscalYearStart
) {
4919 $newFiscalYearStart = $config->fiscalYearStart
;
4920 if ($newFiscalYearStart['M'] < 10) {
4921 // This is just a clumsy way of adding padding.
4922 // @todo next round look for a nicer way.
4923 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
4925 if ($newFiscalYearStart['d'] < 10) {
4926 // This is just a clumsy way of adding padding.
4927 // @todo next round look for a nicer way.
4928 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
4930 $config->fiscalYearStart
= $newFiscalYearStart;
4931 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
4934 // First of January.
4937 $startDate = "$year$monthDay";
4938 $endDate = "$nextYear$monthDay";
4941 'contact_id' => 'IN (' . $contactIDs . ')',
4942 'is_test' => ' = 0',
4943 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
4945 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4946 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
4949 foreach ($whereClauses as $key => $clause) {
4950 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
4952 $whereClauseString = implode(' AND ', $clauses);
4954 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
4955 // this group by + having on contribution_status_id improves performance
4957 SELECT COUNT(*) as count,
4958 SUM(total_amount) as amount,
4959 AVG(total_amount) as average,
4961 FROM civicrm_contribution b
4962 WHERE " . $whereClauseString . "
4963 GROUP BY currency, contribution_status_id
4964 HAVING $havingClause
4970 * Assign Test Value.
4972 * @param string $fieldName
4973 * @param array $fieldDef
4974 * @param int $counter
4976 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
4977 if ($fieldName == 'tax_amount') {
4978 $this->{$fieldName} = "0.00";
4980 elseif ($fieldName == 'net_amount') {
4981 $this->{$fieldName} = "2.00";
4983 elseif ($fieldName == 'total_amount') {
4984 $this->{$fieldName} = "3.00";
4986 elseif ($fieldName == 'fee_amount') {
4987 $this->{$fieldName} = "1.00";
4990 parent
::assignTestValues($fieldName, $fieldDef, $counter);
4995 * Check if contribution has participant/membership payment.
4997 * @param int $contributionId
5002 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5003 // get line item for contribution
5004 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5005 // check if line item is for membership or participant
5006 foreach ($lineItems as $items) {
5007 if ($items['entity_table'] == 'civicrm_participant') {
5011 elseif ($items['entity_table'] == 'civicrm_membership') {
5023 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5025 * @param array $trxnParams
5026 * Financial trxn params
5027 * @param array $contributionParams
5028 * Contribution Params
5032 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5033 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
5036 $statusId = $contributionParams['contribution']->contribution_status_id
;
5037 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5038 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5039 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5040 // Return if contribution status is not completed.
5041 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5042 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5043 && $contributionParams['prevContribution']->is_pay_later
== 0
5049 $params = $trxnParams;
5050 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5051 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5052 $params['to_financial_account_id'] = $arAccountId;
5053 $params['status_id'] = array_search('Pending', $contributionStatuses);
5054 $params['is_payment'] = FALSE;
5055 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5056 self
::$_trxnIDs[] = $trxn->id
;
5057 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5061 * Calculate financial item amount when contribution is updated.
5063 * @param array $params
5064 * contribution params
5065 * @param array $amountParams
5067 * @param string $context
5071 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5072 if (!empty($params['is_quick_config'])) {
5073 $amount = $amountParams['item_amount'];
5075 $amount = $params['total_amount'];
5076 if ($context === NULL) {
5077 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5082 $amount = $amountParams['line_total'];
5083 if ($context == 'changedAmount') {
5084 $amount -= $amountParams['previous_line_total'];
5086 $amount *= $amountParams['diff'];
5092 * Retrieve Sales Tax Financial Accounts.
5098 public static function getSalesTaxFinancialAccounts() {
5099 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5100 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5101 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5102 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5103 $queryParams = [1 => [$accountRel, 'Integer']];
5104 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5105 $financialAccount = [];
5106 while ($dao->fetch()) {
5107 $financialAccount[$dao->id
] = $dao->id
;
5109 return $financialAccount;
5113 * Create tax entry in civicrm_entity_financial_trxn table.
5115 * @param array $entityParams
5117 * @param array $eftParams
5119 * @throws \CiviCRM_API3_Exception
5121 public static function createProportionalEntry($entityParams, $eftParams) {
5123 if ($entityParams['contribution_total_amount'] != 0) {
5124 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5126 // Record Entity Financial Trxn; CRM-20145
5127 $eftParams['amount'] = $paid;
5128 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5132 * Create array of last financial item id's.
5134 * @param int $contributionId
5138 public static function getLastFinancialItemIds($contributionId) {
5139 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5140 FROM civicrm_financial_item fi
5141 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5142 WHERE li.contribution_id = %1";
5143 $dao = CRM_Core_DAO
::executeQuery($sql, [
5149 $ftIds = $taxItems = [];
5150 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5151 while ($dao->fetch()) {
5152 /* if sales tax item*/
5153 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5154 $taxItems[$dao->price_field_value_id
] = [
5155 'financial_item_id' => $dao->id
,
5156 'amount' => $dao->tax_amount
,
5160 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5163 return [$ftIds, $taxItems];
5167 * Create proportional entries in civicrm_entity_financial_trxn.
5169 * @param array $entityParams
5171 * @param array $lineItems
5173 * @param array $ftIds
5175 * @param array $taxItems
5177 * @throws \CiviCRM_API3_Exception
5179 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5181 'entity_table' => 'civicrm_financial_item',
5182 'financial_trxn_id' => $entityParams['trxn_id'],
5184 foreach ($lineItems as $key => $value) {
5185 if ($value['qty'] == 0) {
5188 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5189 $entityParams['line_item_amount'] = $value['line_total'];
5190 self
::createProportionalEntry($entityParams, $eftParams);
5191 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5192 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5193 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5194 self
::createProportionalEntry($entityParams, $eftParams);
5200 * Load entities related to the contribution into $this->_relatedObjects.
5204 * @throws \CRM_Core_Exception
5206 protected function loadRelatedEntitiesByID($ids) {
5208 'contact' => 'CRM_Contact_BAO_Contact',
5209 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5210 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5211 'financialType' => 'CRM_Financial_BAO_FinancialType',
5212 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5214 foreach ($entities as $entity => $bao) {
5215 if (!empty($ids[$entity])) {
5216 $this->_relatedObjects
[$entity] = new $bao();
5217 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5218 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5219 throw new CRM_Core_Exception($entity . ' could not be loaded');
5226 * Function to replace contribution tokens.
5228 * @param array $contributionIds
5230 * @param string $subject
5232 * @param array $subjectToken
5234 * @param string $text
5236 * @param string $html
5238 * @param array $messageToken
5240 * @param bool $escapeSmarty
5243 * @throws \CiviCRM_API3_Exception
5245 public static function replaceContributionTokens(
5254 if (empty($contributionIds)) {
5257 $contributionDetails = [];
5258 foreach ($contributionIds as $id) {
5259 $result = self
::getContributionTokenValues($id, $messageToken);
5260 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5261 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5262 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5264 return $contributionDetails;
5268 * Get the contribution fields for $id and display labels where
5269 * appropriate (if the token is present).
5272 * @param array $messageToken
5275 public static function getContributionTokenValues($id, $messageToken) {
5279 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5280 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5281 if (!empty($messageToken)) {
5282 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5283 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5284 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
5292 * Get invoice_number for contribution.
5294 * @param int $contributionID
5298 public static function getInvoiceNumber($contributionID) {
5299 if ($invoicePrefix = self
::checkContributeSettings('invoice_prefix')) {
5300 return $invoicePrefix . $contributionID;
5307 * Load the values needed for the event message.
5309 * @param int $eventID
5310 * @param int $participantID
5311 * @param int|null $contributionID
5314 * @throws \CRM_Core_Exception
5316 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5321 $values = ['event' => []];
5323 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
5324 // add custom fields for event
5325 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
5327 $eventCustomGroup = [];
5328 foreach ($eventGroupTree as $key => $group) {
5329 if ($key === 'info') {
5333 foreach ($group['fields'] as $k => $customField) {
5334 $groupLabel = $group['title'];
5335 if (!empty($customField['customValue'])) {
5336 foreach ($customField['customValue'] as $customFieldValues) {
5337 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5342 $values['event']['customGroup'] = $eventCustomGroup;
5344 //get participant details
5345 $participantParams = [
5346 'id' => $participantID,
5349 $values['participant'] = [];
5351 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
5352 // add custom fields for event
5353 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
5354 $participantCustomGroup = [];
5355 foreach ($participantGroupTree as $key => $group) {
5356 if ($key === 'info') {
5360 foreach ($group['fields'] as $k => $customField) {
5361 $groupLabel = $group['title'];
5362 if (!empty($customField['customValue'])) {
5363 foreach ($customField['customValue'] as $customFieldValues) {
5364 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5369 $values['participant']['customGroup'] = $participantCustomGroup;
5371 //get location details
5373 'entity_id' => $eventID,
5374 'entity_table' => 'civicrm_event',
5376 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5379 'entity_table' => 'civicrm_event',
5380 'entity_id' => $eventID,
5381 'module' => 'CiviEvent',
5384 list($custom_pre_id,
5386 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5388 $values['custom_pre_id'] = $custom_pre_id;
5389 $values['custom_post_id'] = $custom_post_ids;
5391 // set lineItem for event contribution
5392 if ($contributionID) {
5393 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5394 if (!empty($participantIds)) {
5395 foreach ($participantIds as $pIDs) {
5396 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5397 if (!CRM_Utils_System
::isNull($lineItem)) {
5398 $values['lineItem'][] = $lineItem;