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\ActivityContact
;
14 use Civi\Api4\Contribution
;
15 use Civi\Api4\ContributionRecur
;
16 use Civi\Api4\LineItem
;
17 use Civi\Api4\ContributionSoft
;
18 use Civi\Api4\PaymentProcessor
;
19 use Civi\Api4\PledgePayment
;
24 * @copyright CiviCRM LLC https://civicrm.org/licensing
26 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
29 * Static field for all the contribution information that we can potentially import
33 public static $_importableFields = NULL;
36 * Static field for all the contribution information that we can potentially export
40 public static $_exportableFields = NULL;
43 * Static field to hold financial trxn id's.
47 public static $_trxnIDs = NULL;
50 * Field for all the objects related to this contribution.
53 * 1) deprecated function transitionComponents
54 * 2) function to send contribution receipts _assignMessageVariablesToTemplate
55 * 3) some invoice code that is copied from 2
56 * 4) odds & sods that need to be investigated and fixed.
58 * However, it is no longer used by completeOrder.
60 * @var \CRM_Member_BAO_Membership|\CRM_Event_BAO_Participant[]
64 public $_relatedObjects = [];
67 * Field for the component - either 'event' (participant) or 'contribute'
68 * (any item related to a contribution page e.g. membership, pledge, contribution)
69 * This is used for composing messages because they have dependency on the
70 * contribution_page or event page - although over time we may eliminate that
73 * "contribution"\"event"
75 public $_component = NULL;
78 * Possibly obsolete variable.
80 * If you use it please explain why it is set in the create function here.
84 public $trxn_result_code;
89 public function __construct() {
90 parent
::__construct();
94 * Takes an associative array and creates a contribution object.
96 * the function extract all the params it needs to initialize the create a
97 * contribution object. the params array could contain additional unused name/value
100 * @param array $params
101 * (reference ) an assoc array of name/value pairs.
103 * @return \CRM_Contribute_BAO_Contribution
104 * @throws \CRM_Core_Exception
105 * @throws \CiviCRM_API3_Exception
107 public static function add(&$params) {
108 if (empty($params)) {
112 $contributionID = $params['id'] ??
NULL;
113 $action = $contributionID ?
'edit' : 'create';
115 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
116 $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)]);
117 throw new CRM_Core_Exception($message);
120 //set defaults in create mode
121 if (!$contributionID) {
122 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
123 if (empty($params['invoice_number']) && CRM_Invoicing_Utils
::isInvoicingEnabled()) {
124 $nextContributionID = CRM_Core_DAO
::singleValueQuery("SELECT COALESCE(MAX(id) + 1, 1) FROM civicrm_contribution");
125 $params['invoice_number'] = self
::getInvoiceNumber($nextContributionID);
129 $contributionStatusID = $params['contribution_status_id'] ??
NULL;
130 if (CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $contributionStatusID) === 'Partially paid' && empty($params['is_post_payment_create'])) {
131 CRM_Core_Error
::deprecatedFunctionWarning('Setting status to partially paid other than by using Payment.create is deprecated and unreliable');
133 if (!$contributionStatusID) {
134 // Since the fee amount is expecting this (later on) ensure it is always set.
135 // It would only not be set for an update where it is unchanged.
136 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', [
137 'id' => $contributionID,
138 'return' => 'contribution_status_id',
141 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['contribution_status_id']);
144 && !empty($params['membership_id'])
145 && Civi
::settings()->get('deferred_revenue_enabled')
147 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
148 if ($memberStartDate) {
149 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
152 self
::calculateMissingAmountParams($params, $contributionID);
154 if (!empty($params['payment_instrument_id'])) {
155 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
156 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
157 $params['check_number'] = 'null';
161 $setPrevContribution = TRUE;
162 if ($contributionID && $setPrevContribution) {
163 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
165 $previousContributionStatus = ($contributionID && !empty($params['prevContribution'])) ? CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', (int) $params['prevContribution']->contribution_status_id
) : NULL;
167 if ($contributionID && !empty($params['revenue_recognition_date'])
168 && !($previousContributionStatus === 'Pending')
169 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
171 unset($params['revenue_recognition_date']);
174 // Get Line Items if we don't have them already.
175 if (empty($params['line_item'])) {
176 CRM_Price_BAO_LineItem
::getLineItemArray($params, $contributionID ?
[$contributionID] : NULL);
179 // We should really ALWAYS calculate tax amount off the line items.
180 // In order to be a bit cautious we are just messaging rather than
181 // overwriting in cases where we were not previously setting it here.
182 $taxAmount = $lineTotal = 0;
183 foreach ($params['line_item'] ??
[] as $lineItems) {
184 foreach ($lineItems as $lineItem) {
185 $taxAmount +
= (float) ($lineItem['tax_amount'] ??
0);
186 $lineTotal +
= (float) ($lineItem['line_total'] ??
0);
189 if (($params['tax_amount'] ??
'') === 'null') {
190 CRM_Core_Error
::deprecatedWarning('tax_amount should be not passed in (preferable) or a float');
192 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
193 isset($params['financial_type_id']))) {
194 $params['tax_amount'] = $taxAmount;
196 if (isset($params['tax_amount']) && empty($params['skipLineItem'])
197 && !CRM_Utils_Money
::equals($params['tax_amount'], $taxAmount, ($params['currency'] ?? Civi
::settings()->get('defaultCurrency')))
199 CRM_Core_Error
::deprecatedWarning('passing in incorrect tax amounts is deprecated');
202 CRM_Utils_Hook
::pre($action, 'Contribution', $contributionID, $params);
204 $contribution = new CRM_Contribute_BAO_Contribution();
205 $contribution->copyValues($params);
207 $contribution->id
= $contributionID;
209 if (empty($contribution->id
)) {
210 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
211 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
212 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
216 $result = $contribution->save();
218 // Add financial_trxn details as part of fix for CRM-4724
219 $contribution->trxn_result_code
= $params['trxn_result_code'] ??
NULL;
220 $contribution->payment_processor
= $params['payment_processor'] ??
NULL;
222 //add Account details
223 $params['contribution'] = $contribution;
224 if (empty($params['is_post_payment_create'])) {
225 // If this is being called from the Payment.create api/ BAO then that Entity
226 // takes responsibility for the financial transactions. In fact calling Payment.create
227 // to add payments & having it call completetransaction and / or contribution.create
228 // to update related entities is the preferred flow.
229 // Note that leveraging this parameter for any other code flow is not supported and
230 // is likely to break in future and / or cause serious problems in your data.
231 // https://github.com/civicrm/civicrm-core/pull/14673
232 self
::recordFinancialAccounts($params);
235 if (self
::isUpdateToRecurringContribution($params)) {
236 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
237 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
239 $params['receive_date'] ??
'now'
243 $params['contribution_id'] = $contribution->id
;
245 if (!empty($params['custom']) &&
246 is_array($params['custom'])
248 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
, $action);
251 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
253 CRM_Utils_Hook
::post($action, 'Contribution', $contribution->id
, $contribution);
258 * Is this contribution updating an existing recurring contribution.
260 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
261 * pending payment is being confirmed (or failing).
263 * @param array $params
267 public static function isUpdateToRecurringContribution($params) {
268 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
271 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
274 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
277 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
278 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
285 * Get defaults for new entity.
289 public static function getDefaults() {
291 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
292 FALSE, FALSE, FALSE, 'AND is_default = 1')
294 'contribution_status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
295 'receive_date' => date('Y-m-d H:i:s'),
300 * Fetch the object and store the values in the values array.
302 * @param array $params
303 * Input parameters to find object.
304 * @param array $values
305 * Output values of the object.
307 * The array that holds all the db ids.
309 * @return CRM_Contribute_BAO_Contribution|null
310 * The found object or null
312 public static function getValues($params, &$values = [], &$ids = []) {
313 if (empty($params)) {
316 $contribution = new CRM_Contribute_BAO_Contribution();
318 $contribution->copyValues($params);
320 if ($contribution->find(TRUE)) {
321 $ids['contribution'] = $contribution->id
;
323 CRM_Core_DAO
::storeValues($contribution, $values);
325 return $contribution;
327 // return by reference
333 * Get the values and resolve the most common mappings.
335 * Since contribution status is resolved in almost every function that calls getValues it makes
336 * sense to have an extra function to resolve it rather than repeat the code.
338 * Think carefully before adding more mappings to be resolved as there could be performance implications
339 * if this function starts to be called from more iterative functions.
341 * @param array $params
342 * Input parameters to find object.
345 * Array of the found contribution.
346 * @throws CRM_Core_Exception
348 public static function getValuesWithMappings($params) {
350 $contribution = self
::getValues($params, $values, $ids);
351 if (is_null($contribution)) {
352 throw new CRM_Core_Exception('No contribution found');
354 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
359 * Calculate net_amount & fee_amount if they are not set.
361 * Net amount should be total - fee.
362 * This should only be called for new contributions.
364 * @param array $params
365 * Params for a new contribution before they are saved.
366 * @param int|null $contributionID
367 * Contribution ID if we are dealing with an update.
369 * @throws \CiviCRM_API3_Exception
371 public static function calculateMissingAmountParams(&$params, $contributionID) {
372 if (!$contributionID && (!isset($params['fee_amount']) ||
$params['fee_amount'] === '')) {
373 if (isset($params['total_amount']) && isset($params['net_amount'])) {
374 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
377 $params['fee_amount'] = 0;
380 if (!isset($params['net_amount'])) {
381 if (!$contributionID) {
382 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
385 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
386 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
387 // net_amount may need adjusting.
388 $contribution = civicrm_api3('Contribution', 'getsingle', [
389 'id' => $contributionID,
390 'return' => ['total_amount', 'net_amount', 'fee_amount'],
392 $totalAmount = (isset($params['total_amount']) ?
(float) $params['total_amount'] : (float) CRM_Utils_Array
::value('total_amount', $contribution));
393 $feeAmount = (isset($params['fee_amount']) ?
(float) $params['fee_amount'] : (float) CRM_Utils_Array
::value('fee_amount', $contribution));
394 $params['net_amount'] = $totalAmount - $feeAmount;
402 * @param $billingLocationTypeID
406 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
407 $hasBillingField = FALSE;
416 //build address array
418 $addressParams['location_type_id'] = $billingLocationTypeID;
419 $addressParams['is_billing'] = 1;
421 $billingFirstName = $params['billing_first_name'] ??
NULL;
422 $billingMiddleName = $params['billing_middle_name'] ??
NULL;
423 $billingLastName = $params['billing_last_name'] ??
NULL;
424 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
426 foreach ($billingFields as $value) {
427 $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"] ??
NULL;
428 if (!empty($addressParams[$value])) {
429 $hasBillingField = TRUE;
432 return [$hasBillingField, $addressParams];
436 * Get address params ready to be passed to the payment processor.
438 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
439 * To create an address we need state_province_id.
441 * @param array $params
442 * @param int $billingLocationTypeID
446 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
447 [$hasBillingField, $addressParams] = self
::getBillingAddressParams($params, $billingLocationTypeID);
448 foreach ($addressParams as $name => $field) {
449 if (substr($name, 0, 8) == 'billing_') {
450 $addressParams[substr($name, 9)] = $addressParams[$field];
453 return [$hasBillingField, $addressParams];
457 * Get the number of terms for this contribution for a given membership type
458 * based on querying the line item table and relevant price field values
459 * Note that any one contribution should only be able to have one line item relating to a particular membership
462 * @param int $membershipTypeID
464 * @param int $contributionID
468 public static function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
469 $numTerms = CRM_Core_DAO
::singleValueQuery("
470 SELECT v.membership_num_terms FROM civicrm_line_item li
471 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
472 WHERE contribution_id = %1 AND membership_type_id = %2",
473 [1 => [$contributionID, 'Integer'], 2 => [$membershipTypeID, 'Integer']]
475 // default of 1 is precautionary
476 return empty($numTerms) ?
1 : $numTerms;
480 * Takes an associative array and creates a contribution object.
482 * @param array $params
483 * (reference ) an assoc array of name/value pairs.
485 * @return CRM_Contribute_BAO_Contribution
487 * @throws \API_Exception
488 * @throws \CRM_Core_Exception
489 * @throws \CiviCRM_API3_Exception
491 public static function create(&$params) {
493 $transaction = new CRM_Core_Transaction();
496 $contribution = self
::add($params);
498 catch (CRM_Core_Exception
$e) {
499 $transaction->rollback();
503 $params['contribution_id'] = $contribution->id
;
504 $session = CRM_Core_Session
::singleton();
506 if (!empty($params['note'])) {
508 'entity_table' => 'civicrm_contribution',
509 'note' => $params['note'],
510 'entity_id' => $contribution->id
,
511 'contact_id' => $session->get('userID'),
513 if (!$noteParams['contact_id']) {
514 $noteParams['contact_id'] = $params['contact_id'];
516 CRM_Core_BAO_Note
::add($noteParams);
519 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
521 if (!empty($params['id']) && !empty($params['contribution_status_id'])
523 self
::disconnectPledgePaymentsIfCancelled((int) $params['id'], CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']));
525 $transaction->commit();
527 if (empty($contribution->contact_id
)) {
528 $contribution->find(TRUE);
531 $isCompleted = ('Completed' === CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
));
532 if (!empty($params['on_behalf'])
535 $existingActivity = Activity
::get(FALSE)->setWhere([
536 ['source_record_id', '=', $contribution->id
],
537 ['activity_type_id:name', '=', 'Contribution'],
538 ])->execute()->first();
541 'activity_type_id:name' => 'Contribution',
542 'source_record_id' => $contribution->id
,
543 'activity_date_time' => $contribution->receive_date
,
544 'is_test' => (bool) $contribution->is_test
,
545 'status_id:name' => $isCompleted ?
'Completed' : 'Scheduled',
546 'skipRecentView' => TRUE,
547 'subject' => CRM_Activity_BAO_Activity
::getActivitySubject($contribution),
548 'campaign_id' => !is_numeric($contribution->campaign_id
) ?
NULL : $contribution->campaign_id
,
549 'id' => $existingActivity['id'] ??
NULL,
551 if (!$activityParams['id']) {
552 $activityParams['source_contact_id'] = (int) ($params['source_contact_id'] ??
(CRM_Core_Session
::getLoggedInContactID() ?
: $contribution->contact_id
));
553 $activityParams['target_contact_id'] = ($activityParams['source_contact_id'] === (int) $contribution->contact_id
) ?
[] : [$contribution->contact_id
];
556 [$sourceContactId, $targetContactId] = self
::getActivitySourceAndTarget($activityParams['id']);
558 if (empty($targetContactId) && $sourceContactId != $contribution->contact_id
) {
559 // If no target contact exists and the source contact is not equal to
560 // the contribution contact, update the source contact
561 $activityParams['source_contact_id'] = $contribution->contact_id
;
563 elseif (isset($targetContactId) && $targetContactId != $contribution->contact_id
) {
564 // If a target contact exists and it is not equal to the contribution
565 // contact, update the target contact
566 $activityParams['target_contact_id'] = [$contribution->contact_id
];
569 Activity
::save(FALSE)->addRecord($activityParams)->execute();
572 // do not add to recent items for import, CRM-4399
573 if (empty($params['skipRecentView'])) {
574 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
575 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
577 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
584 $retrieveRequired = 0;
585 foreach ($titleFields as $titleField) {
586 if (!isset($contribution->$titleField)) {
587 $retrieveRequired = 1;
591 if ($retrieveRequired == 1) {
592 $contribution->find(TRUE);
594 $financialType = CRM_Contribute_PseudoConstant
::financialType($contribution->financial_type_id
);
595 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $financialType . ')';
598 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
599 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
600 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
604 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
605 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
606 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
610 // add the recently created Contribution
611 CRM_Utils_Recent
::add($title,
615 $contribution->contact_id
,
621 return $contribution;
625 * Get the values for pseudoconstants for name->value and reverse.
627 * @param array $defaults
628 * (reference) the default values, some of which need to be resolved.
629 * @param bool $reverse
630 * True if we want to resolve the values in the reverse direction (value -> name).
632 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
633 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
634 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
635 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'), $reverse);
636 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
640 * Convert associative array names to values and vice-versa.
642 * This function is used by both the web form layer and the api. Note that
643 * the api needs the name => value conversion, also the view layer typically
644 * requires value => name conversion
646 * @param array $defaults
647 * @param string $property
648 * @param array $lookup
649 * @param bool $reverse
653 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
654 $id = $property . '_id';
656 $src = $reverse ?
$property : $id;
657 $dst = $reverse ?
$id : $property;
659 if (!array_key_exists($src, $defaults)) {
663 $look = $reverse ?
array_flip($lookup) : $lookup;
665 if (is_array($look)) {
666 if (!array_key_exists($defaults[$src], $look)) {
670 $defaults[$dst] = $look[$defaults[$src]];
675 * Retrieve DB object based on input parameters.
677 * It also stores all the retrieved values in the default array.
679 * @param array $params
680 * (reference ) an assoc array of name/value pairs.
681 * @param array $defaults
682 * (reference ) an assoc array to hold the name / value pairs.
683 * in a hierarchical manner
685 * (reference) the array that holds all the db ids.
687 * @return CRM_Contribute_BAO_Contribution
689 public static function retrieve(&$params, &$defaults = [], &$ids = []) {
690 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
691 return $contribution;
695 * Combine all the importable fields from the lower levels object.
697 * The ordering is important, since currently we do not have a weight
698 * scheme. Adding weight is super important and should be done in the
699 * next week or so, before this can be called complete.
701 * @param string $contactType
702 * @param bool $status
705 * array of importable Fields
707 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
708 if (!self
::$_importableFields) {
709 if (!self
::$_importableFields) {
710 self
::$_importableFields = [];
714 $fields = ['' => ['title' => ts('- do not import -')]];
717 $fields = ['' => ['title' => ts('- Contribution Fields -')]];
720 $note = CRM_Core_DAO_Note
::import();
721 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
722 unset($tmpFields['option_value']);
723 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
724 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
726 // Using new Dedupe rule.
728 'contact_type' => $contactType,
729 'used' => 'Unsupervised',
731 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
732 $tmpContactField = [];
733 if (is_array($fieldsArray)) {
734 foreach ($fieldsArray as $value) {
735 //skip if there is no dupe rule
736 if ($value == 'none') {
739 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
744 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
745 $tmpContactField[trim($value)] = $contactFields[trim($value)];
747 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
750 $title = $tmpContactField[trim($value)]['title'];
752 $tmpContactField[trim($value)]['title'] = $title;
756 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
757 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
758 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
759 $fields = array_merge($fields, $tmpContactField);
760 $fields = array_merge($fields, $tmpFields);
761 $fields = array_merge($fields, $note);
762 $fields = array_merge($fields, $optionFields);
763 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
764 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
765 self
::$_importableFields = $fields;
767 return self
::$_importableFields;
771 * Combine all the exportable fields from the lower level objects.
773 * @param bool $checkPermission
776 * array of exportable Fields
778 public static function &exportableFields($checkPermission = TRUE) {
779 if (!self
::$_exportableFields) {
780 if (!self
::$_exportableFields) {
781 self
::$_exportableFields = [];
784 $fields = CRM_Contribute_DAO_Contribution
::export();
785 if (CRM_Contribute_BAO_Query
::isSiteHasProducts()) {
786 $fields = array_merge(
788 CRM_Contribute_DAO_Product
::export(),
789 CRM_Contribute_DAO_ContributionProduct
::export(),
790 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
792 'contribution_product_id' => [
793 'title' => ts('Premium'),
794 'name' => 'contribution_product_id',
795 'where' => 'civicrm_product.id',
796 'data_type' => CRM_Utils_Type
::T_INT
,
802 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
804 $contributionPage = [
805 'contribution_page' => [
806 'title' => ts('Contribution Page'),
807 'name' => 'contribution_page',
808 'where' => 'civicrm_contribution_page.title',
809 'data_type' => CRM_Utils_Type
::T_STRING
,
813 $contributionNote = [
814 'contribution_note' => [
815 'title' => ts('Contribution Note'),
816 'name' => 'contribution_note',
817 'data_type' => CRM_Utils_Type
::T_TEXT
,
822 'contribution_batch' => [
823 'title' => ts('Batch Name'),
829 'contribution_campaign_title' => [
830 'title' => ts('Campaign Title'),
831 'name' => 'campaign_title',
832 'where' => 'civicrm_campaign.title',
833 'data_type' => CRM_Utils_Type
::T_STRING
,
836 $softCreditFields = [
837 'contribution_soft_credit_name' => [
838 'name' => 'contribution_soft_credit_name',
839 'title' => ts('Soft Credit For'),
840 'where' => 'civicrm_contact_d.display_name',
841 'data_type' => CRM_Utils_Type
::T_STRING
,
843 'contribution_soft_credit_amount' => [
844 'name' => 'contribution_soft_credit_amount',
845 'title' => ts('Soft Credit Amount'),
846 'where' => 'civicrm_contribution_soft.amount',
847 'data_type' => CRM_Utils_Type
::T_MONEY
,
849 'contribution_soft_credit_type' => [
850 'name' => 'contribution_soft_credit_type',
851 'title' => ts('Soft Credit Type'),
852 'where' => 'contribution_softcredit_type.label',
853 'data_type' => CRM_Utils_Type
::T_STRING
,
855 'contribution_soft_credit_contribution_id' => [
856 'name' => 'contribution_soft_credit_contribution_id',
857 'title' => ts('Soft Credit For Contribution ID'),
858 'where' => 'civicrm_contribution_soft.contribution_id',
859 'data_type' => CRM_Utils_Type
::T_INT
,
861 'contribution_soft_credit_contact_id' => [
862 'name' => 'contribution_soft_credit_contact_id',
863 'title' => ts('Soft Credit For Contact ID'),
864 'where' => 'civicrm_contact_d.id',
865 'data_type' => CRM_Utils_Type
::T_INT
,
869 $fields = array_merge($fields, $contributionPage,
870 $contributionNote, $extraFields, $softCreditFields, $financialAccount, $campaignTitle,
871 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
874 self
::$_exportableFields = $fields;
877 return self
::$_exportableFields;
881 * Record an activity when a payment is received.
883 * @todo this is intended to be moved to payment BAO class as a protected function
884 * on that class. Currently being cleaned up. The addActivityForPayment doesn't really
885 * merit it's own function as it makes the code less rather than more readable.
887 * @param int $contributionId
888 * @param int $participantId
889 * @param string $totalAmount
890 * @param string $currency
891 * @param string $trxnDate
893 * @throws \CRM_Core_Exception
894 * @throws \CiviCRM_API3_Exception
896 public static function recordPaymentActivity($contributionId, $participantId, $totalAmount, $currency, $trxnDate) {
897 $activityType = ($totalAmount < 0) ?
'Refund' : 'Payment';
899 if ($participantId) {
900 $inputParams['id'] = $participantId;
903 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
904 $entityObj = $entityObj[$participantId];
905 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
908 $entityObj = new CRM_Contribute_BAO_Contribution();
909 $entityObj->id
= $contributionId;
910 $entityObj->find(TRUE);
911 $title = ts('Contribution');
913 // @todo per block above this is not a logical splitting off of functionality.
914 self
::addActivityForPayment($entityObj->contact_id
, $activityType, $title, $contributionId, $totalAmount, $currency, $trxnDate);
918 * Get the value for the To Financial Account.
920 * @param $contribution
925 public static function getToFinancialAccount($contribution, $params) {
926 if (!empty($params['payment_processor_id'])) {
927 return CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor_id'], NULL, 'civicrm_payment_processor');
929 if (!empty($params['payment_instrument_id'])) {
930 return CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
933 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
934 $queryParams = [1 => [$relationTypeId, 'Integer']];
935 return CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
940 * Get memberships related to the contribution.
942 * @param int $contributionID
945 * @throws \API_Exception
947 protected static function getRelatedMemberships(int $contributionID): array {
948 $membershipIDs = array_keys((array) LineItem
::get(FALSE)
949 ->addWhere('contribution_id', '=', $contributionID)
950 ->addWhere('entity_table', '=', 'civicrm_membership')
951 ->addSelect('entity_id')
952 ->execute()->indexBy('entity_id'));
954 $doubleCheckParams = [
955 'return' => 'membership_id',
956 'contribution_id' => $contributionID,
958 if (!empty($membershipIDs)) {
959 $doubleCheckParams['membership_id'] = ['NOT IN' => $membershipIDs];
961 $membershipPayments = civicrm_api3('MembershipPayment', 'get', $doubleCheckParams)['values'];
962 if (!empty($membershipPayments)) {
964 CRM_Core_Error
::deprecatedWarning('Not having valid line items for membership payments is invalid.');
965 foreach ($membershipPayments as $membershipPayment) {
966 $membershipIDs[] = $membershipPayment['membership_id'];
969 if (empty($membershipIDs)) {
972 // We could combine this with the MembershipPayment.get - we'd
973 // need to re-wrangle the params (here or in the calling function)
974 // as they would then me membership.contact_id, membership.is_test etc
975 return civicrm_api3('Membership', 'get', [
976 'id' => ['IN' => $membershipIDs],
977 'return' => ['id', 'contact_id', 'membership_type_id', 'is_test', 'status_id', 'end_date'],
982 * Do any accounting updates required as a result of a contribution status change.
984 * Currently we have a bit of a roundabout where adding a payment results in this being called &
985 * this may attempt to add a payment. We need to resolve that....
987 * The 'right' way to add payments or refunds is through the Payment.create api. That api
988 * then updates the contribution but this process should not also record another financial trxn.
989 * Currently we have weak detection fot that scenario & where it is detected the first returned
990 * value is FALSE - meaning 'do not continue'.
992 * We should also look at the fact that the calling function - updateFinancialAccounts
993 * bunches together some disparate processes rather than having separate appropriate
996 * @param array $params
999 * Return indicates whether the updateFinancialAccounts function should continue.
1001 private static function updateFinancialAccountsOnContributionStatusChange(&$params) {
1002 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
1003 $currentContributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
1005 if ((($previousContributionStatus === 'Partially paid' && $currentContributionStatus === 'Completed')
1006 ||
($previousContributionStatus === 'Pending refund' && $currentContributionStatus === 'Completed')
1007 // This concept of pay_later as different to any other sort of pending is deprecated & it's unclear
1008 // why it is here or where it is handled instead.
1009 ||
($previousContributionStatus === 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
1010 && $currentContributionStatus === 'Partially paid'))
1015 if (CRM_Contribute_BAO_FinancialProcessor
::isContributionUpdateARefund($params['prevContribution']->contribution_status_id
, $params['contribution']->contribution_status_id
)) {
1016 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1017 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1019 elseif (($previousContributionStatus === 'Pending'
1020 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus === 'In Progress'
1022 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
1023 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
1025 if ($currentContributionStatus === 'Cancelled') {
1026 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1027 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
1028 $params['trxnParams']['total_amount'] = -$params['total_amount'];
1031 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1032 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
1036 if (($previousContributionStatus === 'Pending'
1037 ||
$previousContributionStatus === 'In Progress')
1038 && ($currentContributionStatus === 'Completed')
1040 if (empty($params['line_item'])) {
1042 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
1043 // when creating recurring membership payment - there are 2 lines to comment out in contributionPageTest if fixed
1044 // & this can be removed
1047 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1048 // This is an update so original currency if none passed in.
1049 $params['trxnParams']['currency'] = CRM_Utils_Array
::value('currency', $params, $params['prevContribution']->currency
);
1051 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
1052 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
1053 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
1054 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
1056 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
1059 'entity_table' => 'civicrm_financial_item',
1061 foreach ($params['line_item'] as $fieldId => $fields) {
1062 foreach ($fields as $fieldValueId => $lineItemDetails) {
1063 self
::updateFinancialItemForLineItemToPaid($lineItemDetails['id']);
1065 1 => [$lineItemDetails['id'], 'Integer'],
1067 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
1068 while ($financialItem->fetch()) {
1069 $entityParams['entity_id'] = $financialItem->id
;
1070 $entityParams['amount'] = $financialItem->amount
;
1071 foreach (self
::$_trxnIDs as $tID) {
1072 $entityParams['financial_trxn_id'] = $tID;
1073 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
1084 * It is possible to override the membership id that is updated from the payment processor.
1086 * Historically Paypal does this & it still does if it determines data is messed up - see
1087 * https://lab.civicrm.org/dev/membership/issues/13
1089 * Read the comment block on repeattransaction for more information
1090 * about how things should work.
1092 * @param int $contributionID
1093 * @param array $input
1095 * @throws \CiviCRM_API3_Exception
1097 protected static function handleMembershipIDOverride($contributionID, $input) {
1098 if (!empty($input['membership_id'])) {
1099 Civi
::log()->debug('The related membership id has been overridden - this may impact data - see https://github.com/civicrm/civicrm-core/pull/15053');
1100 civicrm_api3('MembershipPayment', 'create', ['contribution_id' => $contributionID, 'membership_id' => $input['membership_id']]);
1105 * Update all financial items related to the line item tto have a status of paid.
1107 * @param int $lineItemID
1109 private static function updateFinancialItemForLineItemToPaid($lineItemID) {
1112 CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_FinancialItem', 'status_id', 'Paid'),
1115 2 => [$lineItemID, 'Integer'],
1117 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
1118 CRM_Core_DAO
::executeQuery($query, $fparams);
1122 * Get transaction information about the contribution.
1124 * @param int $contributionId
1125 * @param int $financialTypeID
1129 protected static function getContributionTransactionInformation($contributionId, int $financialTypeID) {
1131 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Expense Account is');
1133 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
1135 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
1137 ft.payment_instrument_id,
1138 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id, ft.id
1140 FROM civicrm_contribution con
1141 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
1142 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
1143 AND ft.to_financial_account_id != %2
1144 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
1145 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
1146 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
1148 WHERE con.id = %1 AND ft.is_payment = 1
1151 1 => [$contributionId, 'Integer'],
1152 2 => [$feeFinancialAccount, 'Integer'],
1154 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
1155 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label');
1157 while ($resultDAO->fetch()) {
1158 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1159 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
1160 if ($resultDAO->card_type_id
) {
1161 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id
);
1162 $pantruncation = '';
1163 if ($resultDAO->pan_truncation
) {
1164 $pantruncation = ": {$resultDAO->pan_truncation}";
1166 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
1169 // show payment edit link only for payments done via backoffice form
1170 $paymentEditLink = '';
1171 if (empty($resultDAO->payment_processor_id
) && CRM_Core_Permission
::check('edit contributions')) {
1173 CRM_Core_Action
::UPDATE
=> [
1174 'name' => ts('Edit Payment'),
1175 'icon' => 'fa-pencil',
1176 'url' => 'civicrm/payment/edit',
1177 'class' => 'medium-popup',
1178 'qs' => "reset=1&id=%%id%%&contribution_id=%%contribution_id%%",
1179 'title' => ts('Edit Payment'),
1182 $paymentEditLink = CRM_Core_Action
::formLink(
1184 CRM_Core_Action
::mask([CRM_Core_Permission
::EDIT
]),
1186 'id' => $resultDAO->id
,
1187 'contribution_id' => $contributionId,
1191 'Payment.edit.action',
1199 'id' => $resultDAO->id
,
1200 'total_amount' => $resultDAO->total_amount
,
1201 'financial_type' => $resultDAO->financial_account
,
1202 'payment_instrument' => $paidByLabel,
1203 'receive_date' => $resultDAO->trxn_date
,
1204 'trxn_id' => $resultDAO->trxn_id
,
1205 'status' => $statuses[$resultDAO->status_id
],
1206 'currency' => $resultDAO->currency
,
1207 'action' => $paymentEditLink,
1209 if ($paidByName === 'Check') {
1210 $val['check_number'] = $resultDAO->check_number
;
1218 * Should an email receipt be sent for this contribution on completion.
1220 * @param array $input
1221 * @param int $contributionID
1222 * @param int $recurringContributionID
1225 * @throws \API_Exception
1227 protected static function isEmailReceipt(array $input, int $contributionID, $recurringContributionID): bool {
1228 if (isset($input['is_email_receipt'])) {
1229 return (bool) $input['is_email_receipt'];
1231 if ($recurringContributionID) {
1232 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
1233 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
1234 // 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
1235 // Instance that had the table added via an upgrade in 4.1
1236 // see also https://github.com/civicrm/civicrm-svn/commit/7f39befd60bc735408d7866b02b3ac7fff1d4eea#diff-9ad8e290180451a2d6eacbd3d1ca7966R354
1237 // https://lab.civicrm.org/dev/core/issues/1245
1238 return (bool) ContributionRecur
::get(FALSE)->addWhere('id', '=', $recurringContributionID)->addSelect('is_email_receipt')->execute()->first()['is_email_receipt'];
1240 $contributionPage = Contribution
::get(FALSE)
1241 ->addSelect('contribution_page_id.is_email_receipt')
1242 ->addWhere('contribution_page_id', 'IS NOT NULL')
1243 ->addWhere('id', '=', $contributionID)
1244 ->execute()->first();
1246 if (!empty($contributionPage)) {
1247 return (bool) $contributionPage['contribution_page_id.is_email_receipt'];
1249 // This would be the case for backoffice (where is_email_receipt is not passed in) or events, where Event::sendMail will filter
1255 * Disconnect pledge payments from cancelled or failed contributions.
1257 * If the contribution has been cancelled or has failed check to
1258 * see if it is linked to a pledge and unlink it.
1260 * @param int $pledgePaymentID
1261 * @param string $contributionStatus
1263 * @throws \API_Exception
1264 * @throws \Civi\API\Exception\UnauthorizedException
1266 protected static function disconnectPledgePaymentsIfCancelled(int $pledgePaymentID, $contributionStatus): void
{
1267 if (!in_array($contributionStatus, ['Failed', 'Cancelled'], TRUE)) {
1270 // Check first since just doing an update could be locking under load.
1271 $pledgePayment = PledgePayment
::get(FALSE)
1272 ->addWhere('contribution_id', '=', $pledgePaymentID)
1273 ->setSelect(['id', 'pledge_id', 'scheduled_date', 'scheduled_amount'])
1276 if (!empty($pledgePayment)) {
1277 PledgePayment
::update(FALSE)->setValues([
1278 'contribution_id' => NULL,
1279 'actual_amount' => NULL,
1280 'status_id:name' => 'Pending',
1281 // We need to set these fields for now because the PledgePayment::create
1282 // function doesn't handled updates well at the moment. Test cover
1283 // in testCancelOrderWithPledge.
1284 'scheduled_date' => $pledgePayment['scheduled_date'],
1285 'installment_amount' => $pledgePayment['scheduled_amount'],
1286 'installments' => 1,
1287 'pledge_id' => $pledgePayment['pledge_id'],
1288 ])->addWhere('id', '=', $pledgePayment['id'])->execute();
1295 public function addSelectWhereClause() {
1296 $whereClauses = parent
::addSelectWhereClause();
1297 if ($whereClauses !== []) {
1298 // In this case permisssions have been applied & we assume the
1299 // financialaclreport is applying these
1300 // https://github.com/JMAConsulting/biz.jmaconsulting.financialaclreport/blob/master/financialaclreport.php#L107
1301 return $whereClauses;
1304 if (!CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1305 return $whereClauses;
1307 $types = CRM_Financial_BAO_FinancialType
::getAllEnabledAvailableFinancialTypes();
1308 if (empty($types)) {
1309 $whereClauses['financial_type_id'] = 'IN (0)';
1312 $whereClauses['financial_type_id'] = [
1313 'IN (' . implode(',', array_keys($types)) . ')',
1316 return $whereClauses;
1320 * @param null $status
1321 * @param null $startDate
1322 * @param null $endDate
1324 * @return array|null
1326 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
1330 $where[] = 'contribution_status_id = 1';
1334 $where[] = 'contribution_status_id = 3';
1339 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
1342 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
1344 $financialTypeACLJoin = '';
1345 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1346 $financialTypeACLJoin = " LEFT JOIN civicrm_line_item i ON (i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution') ";
1347 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
1348 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1349 if ($financialTypes) {
1350 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1351 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1354 $where[] = "c.financial_type_id IN (0)";
1358 $whereCond = implode(' AND ', $where);
1361 SELECT sum( total_amount ) as total_amount,
1362 count( c.id ) as total_count,
1364 FROM civicrm_contribution c
1365 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
1366 $financialTypeACLJoin
1368 AND ( is_test = 0 OR is_test IS NULL )
1369 AND contact.is_deleted = 0
1373 $dao = CRM_Core_DAO
::executeQuery($query);
1376 while ($dao->fetch()) {
1377 $count +
= $dao->total_count
;
1378 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
1382 'amount' => implode(', ', $amount),
1390 * Delete the indirect records associated with this contribution first.
1394 * @return mixed|null
1395 * $results no of deleted Contribution on success, false otherwise
1397 public static function deleteContribution($id) {
1398 CRM_Utils_Hook
::pre('delete', 'Contribution', $id);
1400 $transaction = new CRM_Core_Transaction();
1403 //delete activity record
1405 'source_record_id' => $id,
1406 // activity type id for contribution
1407 'activity_type_id' => 6,
1410 CRM_Activity_BAO_Activity
::deleteActivity($params);
1412 //delete billing address if exists for this contribution.
1413 self
::deleteAddress($id);
1415 //update pledge and pledge payment, CRM-3961
1416 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1418 // remove entry from civicrm_price_set_entity, CRM-5095
1419 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1420 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1422 // cleanup line items.
1423 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1425 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1426 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1428 if ($participantId) {
1429 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1432 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1436 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1437 $noteId = key($note);
1439 CRM_Core_BAO_Note
::deleteRecord(['id' => $noteId]);
1442 $dao = new CRM_Contribute_DAO_Contribution();
1445 $results = $dao->delete();
1447 $transaction->commit();
1449 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1455 * React to a financial transaction (payment) failure.
1457 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1458 * payments is important for forensic and outreach reasons.
1460 * @param int $contributionID
1461 * @param int $contactID
1462 * @param string $message
1464 * @throws \CiviCRM_API3_Exception
1466 public static function failPayment($contributionID, $contactID, $message) {
1467 civicrm_api3('activity', 'create', [
1468 'activity_type_id' => 'Failed Payment',
1469 'details' => $message,
1470 'subject' => ts('Payment failed at payment processor'),
1471 'source_record_id' => $contributionID,
1472 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() : $contactID,
1475 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1476 civicrm_api3('contribution', 'create', [
1477 'id' => $contributionID,
1478 'contribution_status_id' => 'Failed',
1483 * Check if there is a contribution with the same trxn_id or invoice_id.
1485 * @param array $input
1486 * An assoc array of name/value pairs.
1487 * @param array $duplicates
1488 * (reference) store ids of duplicate contribs.
1492 * true if duplicate, false otherwise
1494 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1496 $id = $input['id'] ??
NULL;
1498 $trxn_id = $input['trxn_id'] ??
NULL;
1499 $invoice_id = $input['invoice_id'] ??
NULL;
1505 $clause[] = 'trxn_id = %1';
1506 $input[1] = [$trxn_id, 'String'];
1510 $clause[] = "invoice_id = %2";
1511 $input[2] = [$invoice_id, 'String'];
1514 if (empty($clause)) {
1518 $clause = implode(' OR ', $clause);
1520 $clause = "( $clause ) AND id != %3";
1521 $input[3] = [$id, 'Integer'];
1524 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1525 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1527 while ($dao->fetch()) {
1528 $duplicates[] = $dao->id
;
1535 * Takes an associative array and creates a contribution_product object.
1537 * the function extract all the params it needs to initialize the create a
1538 * contribution_product object. the params array could contain additional unused name/value
1541 * @param array $params
1542 * (reference) an assoc array of name/value pairs.
1544 * @return CRM_Contribute_DAO_ContributionProduct
1546 public static function addPremium(&$params) {
1547 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1548 $contributionProduct->copyValues($params);
1549 return $contributionProduct->save();
1553 * Get list of contribution fields for profile.
1554 * For now we only allow custom contribution fields to be in
1557 * @param bool $addExtraFields
1558 * True if special fields needs to be added.
1561 * the list of contribution fields
1563 public static function getContributionFields($addExtraFields = TRUE) {
1564 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1565 // @todo remove this - this line was added because payment_instrument_id was not
1566 // set to exportable - but now it is.
1567 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1569 if ($addExtraFields) {
1570 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1573 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1575 foreach ($contributionFields as $key => $var) {
1576 if ($key === 'contribution_contact_id') {
1579 elseif ($key === 'contribution_campaign_id') {
1580 $var['title'] = ts('Campaign');
1582 $fields[$key] = $var;
1585 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1590 * Add extra fields specific to contribution.
1592 public static function getSpecialContributionFields() {
1594 'contribution_soft_credit_name' => [
1595 'name' => 'contribution_soft_credit_name',
1596 'title' => ts('Soft Credit Name'),
1597 'headerPattern' => '/^soft_credit_name$/i',
1598 'where' => 'civicrm_contact_d.display_name',
1600 'contribution_soft_credit_email' => [
1601 'name' => 'contribution_soft_credit_email',
1602 'title' => ts('Soft Credit Email'),
1603 'headerPattern' => '/^soft_credit_email$/i',
1604 'where' => 'soft_email.email',
1606 'contribution_soft_credit_phone' => [
1607 'name' => 'contribution_soft_credit_phone',
1608 'title' => ts('Soft Credit Phone'),
1609 'headerPattern' => '/^soft_credit_phone$/i',
1610 'where' => 'soft_phone.phone',
1612 'contribution_soft_credit_contact_id' => [
1613 'name' => 'contribution_soft_credit_contact_id',
1614 'title' => ts('Soft Credit Contact ID'),
1615 'headerPattern' => '/^soft_credit_contact_id$/i',
1616 'where' => 'civicrm_contribution_soft.contact_id',
1618 'contribution_pcp_title' => [
1619 'name' => 'contribution_pcp_title',
1620 'title' => ts('Personal Campaign Page Title'),
1621 'headerPattern' => '/^contribution_pcp_title$/i',
1622 'where' => 'contribution_pcp.title',
1626 return $extraFields;
1630 * @param int $pageID
1634 public static function getCurrentandGoalAmount($pageID) {
1636 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1637 FROM civicrm_contribution_page p,
1638 civicrm_contribution c
1639 WHERE p.id = c.contribution_page_id
1641 AND c.cancel_date is null
1645 $config = CRM_Core_Config
::singleton();
1646 $params = [1 => [$pageID, 'Integer']];
1647 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1649 if ($dao->fetch()) {
1650 return [$dao->goal
, $dao->total
];
1653 return [NULL, NULL];
1658 * Get list of contributions which credit the passed in contact ID.
1660 * The returned array provides details about the original contribution & donor.
1662 * @param int $honorId
1663 * In Honor of Contact ID.
1666 * list of contribution fields
1667 * @todo - this is a confusing function called from one place. It has a test. It would be
1668 * nice to deprecate it.
1671 public static function getHonorContacts($honorId) {
1673 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1674 $honorDAO->contact_id
= $honorId;
1677 $type = CRM_Contribute_PseudoConstant
::financialType();
1679 while ($honorDAO->fetch()) {
1680 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1681 $contributionDAO->id
= $honorDAO->contribution_id
;
1683 if ($contributionDAO->find(TRUE)) {
1684 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1685 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1686 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1687 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1688 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1689 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1690 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1691 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1692 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
, 'label');
1700 * Get the sort name of a contact for a particular contribution.
1703 * Id of the contribution.
1705 * @return null|string
1706 * sort name of the contact if found
1708 public static function sortName($id) {
1709 $id = CRM_Utils_Type
::escape($id, 'Integer');
1712 SELECT civicrm_contact.sort_name
1713 FROM civicrm_contribution, civicrm_contact
1714 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1715 AND civicrm_contribution.id = {$id}
1717 return CRM_Core_DAO
::singleValueQuery($query);
1721 * Generate summary of amount received in the current fiscal year to date from the contact or contacts.
1723 * @param int|array $contactIDs
1727 public static function annual($contactIDs) {
1728 if (!is_array($contactIDs)) {
1729 // In practice I can't fine any evidence that this function is ever called with
1730 // anything other than a single contact id, but left like this due to .... fear.
1731 $contactIDs = explode(',', $contactIDs);
1734 $query = self
::getAnnualQuery($contactIDs);
1735 $dao = CRM_Core_DAO
::executeQuery($query);
1737 $amount = $average = [];
1738 while ($dao->fetch()) {
1739 if ($dao->count
> 0 && $dao->amount
> 0) {
1740 $count +
= $dao->count
;
1741 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1742 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1748 implode(', ', $amount),
1749 implode(', ', $average),
1756 * Check if there is a contribution with the params passed in.
1758 * Used for trxn_id,invoice_id and contribution_id
1760 * @param array $params
1761 * An assoc array of name/value pairs.
1764 * contribution id if success else NULL
1766 public static function checkDuplicateIds($params) {
1767 $dao = new CRM_Contribute_DAO_Contribution();
1771 foreach ($params as $k => $v) {
1773 $clause[] = "$k = '$v'";
1776 $clause = implode(' AND ', $clause);
1777 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1778 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1780 while ($dao->fetch()) {
1788 * Get the contribution details for component export.
1790 * @param int $exportMode
1792 * @param array $componentIds
1798 public static function getContributionDetails($exportMode, $componentIds) {
1799 $paymentDetails = [];
1800 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1802 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1803 $componentSelect = " civicrm_participant_payment.participant_id id";
1804 $additionalClause = "
1805 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1806 AND civicrm_participant_payment.participant_id {$componentClause} )
1809 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1810 $componentSelect = " civicrm_membership_payment.membership_id id";
1811 $additionalClause = "
1812 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1813 AND civicrm_membership_payment.membership_id {$componentClause} )
1816 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1817 $componentSelect = " civicrm_pledge_payment.id id";
1818 $additionalClause = "
1819 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1820 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1824 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1825 trxn_id, {$componentSelect}
1826 FROM civicrm_contribution
1827 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1828 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1829 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1830 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1831 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1832 AND option_group_contribution_status.id = contribution_status.option_group_id )
1836 $dao = CRM_Core_DAO
::executeQuery($query);
1838 while ($dao->fetch()) {
1839 $paymentDetails[$dao->id
] = [
1840 'total_amount' => $dao->total_amount
,
1841 'contribution_status' => $dao->status
,
1842 'receive_date' => $dao->receive_date
,
1843 'pay_instru' => $dao->payment_instrument
,
1844 'trxn_id' => $dao->trxn_id
,
1848 return $paymentDetails;
1852 * Create address associated with contribution record.
1854 * As long as there is one or more billing field in the parameters we will create the address.
1856 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1859 * @param array $params
1860 * @param int $billingLocationTypeID
1865 public static function createAddress($params, $billingLocationTypeID) {
1866 [$hasBillingField, $addressParams] = self
::getBillingAddressParams($params, $billingLocationTypeID);
1867 if ($hasBillingField) {
1868 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1869 return $address->id
;
1876 * Delete billing address record related contribution.
1878 * @param int $contributionId
1879 * @param int $contactId
1881 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1883 $contactJoin = NULL;
1885 if ($contributionId) {
1886 $clauses[] = "cc.id = {$contributionId}";
1890 $clauses[] = "cco.id = {$contactId}";
1891 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1894 if (empty($clauses)) {
1895 throw new CRM_Core_Exception('No Where clauses defined when deleting address');
1898 $condition = implode(' OR ', $clauses);
1902 FROM civicrm_address ca
1903 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1907 $dao = CRM_Core_DAO
::executeQuery($query);
1909 while ($dao->fetch()) {
1910 $params = ['id' => $dao->id
];
1911 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1916 * This function check online pending contribution associated w/
1917 * Online Event Registration or Online Membership signup.
1919 * @param int $componentId
1920 * Participant/membership id.
1921 * @param string $componentName
1925 * pending contribution id.
1927 public static function checkOnlinePendingContribution($componentId, $componentName) {
1928 $contributionId = NULL;
1929 if (!$componentId ||
1930 !in_array($componentName, ['Event', 'Membership'])
1932 return $contributionId;
1935 if ($componentName === 'Event') {
1936 $idName = 'participant_id';
1937 $componentTable = 'civicrm_participant';
1938 $paymentTable = 'civicrm_participant_payment';
1939 $source = ts('Online Event Registration');
1942 if ($componentName === 'Membership') {
1943 $idName = 'membership_id';
1944 $componentTable = 'civicrm_membership';
1945 $paymentTable = 'civicrm_membership_payment';
1946 $source = ts('Online Contribution');
1949 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1952 SELECT component.id as {$idName},
1953 componentPayment.contribution_id as contribution_id,
1954 contribution.source source,
1955 contribution.contribution_status_id as contribution_status_id,
1956 contribution.is_pay_later as is_pay_later
1957 FROM $componentTable component
1958 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1959 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1960 WHERE component.id = {$componentId}";
1962 $dao = CRM_Core_DAO
::executeQuery($query);
1964 while ($dao->fetch()) {
1965 if ($dao->contribution_id
&&
1966 $dao->is_pay_later
&&
1967 $dao->contribution_status_id
== $pendingStatusId &&
1968 strpos($dao->source
, $source) !== FALSE
1970 $contributionId = $dao->contribution_id
;
1974 return $contributionId;
1978 * Update contribution as well as related objects.
1980 * This function by-passes hooks - to address this - don't use this function.
1982 * @param array $params
1984 * @throws CRM_Core_Exception
1985 * @throws \CiviCRM_API3_Exception
1988 * Use api contribute.completetransaction
1989 * For failures use failPayment (preferably exposing by api in the process).
1992 public static function transitionComponents($params) {
1993 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution_status_id']);
1994 $previousStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['previous_contribution_status_id']);
1995 // @todo fix the one place that calls this function to use Payment.create
1997 // get minimum required values.
1998 $contributionId = $params['contribution_id'];
1999 $contributionStatusId = $params['contribution_status_id'];
2001 // we process only ( Completed, Cancelled, or Failed ) contributions.
2002 if (!$contributionId ||
$contributionStatus !== 'Completed') {
2006 // get the related component details.
2007 $componentDetails = self
::getComponentDetails($contributionId);
2009 if (!empty($componentDetails['contact_id'])) {
2010 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2016 // do check for required ids.
2017 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
2023 $input['component'] = $componentDetails['component'] ??
NULL;
2024 $ids['contribution'] = $contributionId;
2025 $ids['contact'] = $componentDetails['contact_id'] ??
NULL;
2026 $ids['membership'] = $componentDetails['membership'] ??
NULL;
2027 $ids['participant'] = $componentDetails['participant'] ??
NULL;
2028 $ids['event'] = $componentDetails['event'] ??
NULL;
2029 $ids['pledge_payment'] = $componentDetails['pledge_payment'] ??
NULL;
2030 $ids['contributionRecur'] = NULL;
2031 $ids['contributionPage'] = NULL;
2033 $contribution = new CRM_Contribute_BAO_Contribution();
2034 $contribution->id
= $ids['contribution'];
2035 $contribution->find();
2037 $contribution->loadRelatedObjects($input, $ids);
2039 $memberships = $contribution->_relatedObjects
['membership'] ??
[];
2040 $participant = $contribution->_relatedObjects
['participant'] ??
[];
2041 $pledgePayment = $contribution->_relatedObjects
['pledge_payment'] ??
[];
2043 $pledgeID = $oldStatus = NULL;
2044 $pledgePaymentIDs = [];
2045 if ($pledgePayment) {
2046 foreach ($pledgePayment as $key => $object) {
2047 $pledgePaymentIDs[] = $object->id
;
2049 $pledgeID = $pledgePayment[0]->pledge_id
;
2052 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
2055 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
2056 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
2062 // only pending contribution related object processed.
2063 if (!in_array($previousStatus, ['Pending', 'Partially paid'])) {
2064 // this is case when we already processed contribution object.
2068 if (is_array($memberships)) {
2069 foreach ($memberships as $membership) {
2074 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
2075 $membership->membership_type_id
,
2076 $membership->is_test
, $membership->id
2079 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
2080 // this picks up membership type changes during renewals
2082 SELECT membership_type_id
2083 FROM civicrm_membership_log
2084 WHERE membership_id=$membership->id
2087 $dao = CRM_Core_DAO
::executeQuery($sql);
2088 if ($dao->fetch()) {
2089 if (!empty($dao->membership_type_id
)) {
2090 $membership->membership_type_id
= $dao->membership_type_id
;
2091 $membership->save();
2094 // else fall back to using current membership type
2095 // Figure out number of terms
2097 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
2098 foreach ($lineitems as $lineitem) {
2099 if ($membership->membership_type_id
== ($lineitem['membership_type_id'] ??
NULL)) {
2100 $numterms = $lineitem['membership_num_terms'] ??
NULL;
2102 // in case membership_num_terms comes through as null or zero
2103 $numterms = $numterms >= 1 ?
$numterms : 1;
2108 // CRM-15735-to update the membership status as per the contribution receive date
2110 $oldStatus = $membership->status_id
;
2111 if (!empty($params['receive_date'])) {
2112 $joinDate = $params['receive_date'];
2113 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
2114 $membership->end_date
,
2115 $membership->join_date
,
2116 $params['receive_date'],
2118 $membership->membership_type_id
,
2121 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
2122 $membership->save();
2125 if ($currentMembership) {
2126 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2127 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
2128 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2131 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
2134 //get the status for membership.
2135 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
2137 $dates['join_date'],
2140 $membership->membership_type_id
,
2144 $formattedParams = [
2145 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
2146 array_search('Current', $membershipStatuses)
2148 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
2149 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
2150 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
2153 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
2155 $membership->copyValues($formattedParams);
2156 $membership->save();
2158 //updating the membership log
2159 $membershipLog = $formattedParams;
2160 $logStartDate = CRM_Utils_Date
::customFormat($dates['log_start_date'] ??
NULL, $format);
2161 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
2163 $membershipLog['start_date'] = $logStartDate;
2164 $membershipLog['membership_id'] = $membership->id
;
2165 $membershipLog['modified_id'] = $membership->contact_id
;
2166 $membershipLog['modified_date'] = date('Ymd');
2167 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
2169 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2171 //update related Memberships.
2172 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
2174 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2175 $scheduledActivityID = CRM_Utils_Array
::value('id',
2176 civicrm_api3('Activity', 'Get',
2178 'source_record_id' => $membership->id
,
2179 'activity_type_id' => $activityType,
2180 'status_id' => 'Scheduled',
2183 'sort' => 'id DESC',
2188 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2189 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2190 if ($scheduledActivityID) {
2191 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $membership->contact_id
, ['id' => $scheduledActivityID]);
2196 // track membership status change if any
2197 if (!empty($oldStatus) && $membership->status_id
!= $oldStatus) {
2198 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
2199 CRM_Activity_BAO_Activity
::addActivity($membership,
2200 'Change Membership Status',
2203 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2204 'source_contact_id' => $membershipLog['modified_id'],
2205 'priority_id' => 'Normal',
2210 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
2216 $updatedStatusId = array_search('Registered', $participantStatuses);
2217 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
2220 if ($pledgePayment) {
2221 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2227 * Returns all contribution related object ids.
2229 * @param $contributionId
2233 public static function getComponentDetails($contributionId) {
2234 $componentDetails = $pledgePayment = [];
2235 if (!$contributionId) {
2236 return $componentDetails;
2240 SELECT c.id as contribution_id,
2241 c.contact_id as contact_id,
2242 c.contribution_recur_id,
2243 mp.membership_id as membership_id,
2244 m.membership_type_id as membership_type_id,
2245 pp.participant_id as participant_id,
2246 p.event_id as event_id,
2247 pgp.id as pledge_payment_id
2248 FROM civicrm_contribution c
2249 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2250 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2251 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2252 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2253 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2254 WHERE c.id = $contributionId";
2256 $dao = CRM_Core_DAO
::executeQuery($query);
2257 $componentDetails = [];
2259 while ($dao->fetch()) {
2260 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2261 $componentDetails['contact_id'] = $dao->contact_id
;
2262 if ($dao->event_id
) {
2263 $componentDetails['event'] = $dao->event_id
;
2265 if ($dao->participant_id
) {
2266 $componentDetails['participant'] = $dao->participant_id
;
2268 if ($dao->membership_id
) {
2269 if (!isset($componentDetails['membership'])) {
2270 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2272 $componentDetails['membership'][] = $dao->membership_id
;
2273 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2275 if ($dao->pledge_payment_id
) {
2276 $pledgePayment[] = $dao->pledge_payment_id
;
2278 if ($dao->contribution_recur_id
) {
2279 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2283 if ($pledgePayment) {
2284 $componentDetails['pledge_payment'] = $pledgePayment;
2287 return $componentDetails;
2291 * @param int $contactId
2292 * @param bool $includeSoftCredit
2294 * @return null|string
2296 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2300 $financialTypes = CRM_Financial_BAO_FinancialType
::getAllAvailableFinancialTypes();
2301 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2302 $liWhere = " AND i.financial_type_id IN (0)";
2303 if (!empty($financialTypes)) {
2304 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2305 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2307 $contactContributionsSQL = "
2308 SELECT contribution.id AS id
2309 FROM civicrm_contribution contribution
2310 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2311 WHERE contribution.is_test = 0 AND contribution.is_template != '1' AND contribution.contact_id = {$contactId}
2315 $contactSoftCreditContributionsSQL = "
2316 SELECT contribution.id
2317 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2318 ON ( contribution.id = softContribution.contribution_id )
2319 WHERE contribution.is_test = 0 AND contribution.is_template != '1' AND softContribution.contact_id = {$contactId} ";
2320 $query = "SELECT count( x.id ) count FROM ( ";
2321 $query .= $contactContributionsSQL;
2323 if ($includeSoftCredit) {
2324 $query .= " UNION ";
2325 $query .= $contactSoftCreditContributionsSQL;
2330 return CRM_Core_DAO
::singleValueQuery($query);
2334 * Repeat a transaction as part of a recurring series.
2337 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2338 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2339 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2340 * and associated entities.
2341 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2342 * which updates the various entities and sends appropriate emails.
2344 * Gaps in the above (
2346 * @param array $input
2348 * @param array $contributionParams
2350 * @return bool|array
2351 * @throws \API_Exception
2352 * @throws \CiviCRM_API3_Exception
2353 * @throws \Civi\API\Exception\UnauthorizedException
2355 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2356 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2357 * 3) Repeat transaction duplicates rather than calls Order.create
2358 * 4) Use of payment.create still limited - completetransaction is more common.
2359 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2360 * to load the membership(s) referred to via line items in the template transactions. Any other
2361 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2362 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2363 * - membership_payment record
2364 * - civicrm_membership.contribution_recur_id
2366 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2367 * of historical processors since this has been handled 'forever' - specifically for paypal.
2368 * albeit by an even nastier mechanism than the current input override.
2369 * The count is out on how correct related entities wind up in this case.
2371 protected static function repeatTransaction(array $input, array $contributionParams) {
2372 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2373 (int) $contributionParams['contribution_recur_id'],
2375 'total_amount' => $input['total_amount'] ??
NULL,
2376 'financial_type_id' => $input['financial_type_id'] ??
NULL,
2377 'campaign_id' => $input['campaign_id'] ??
NULL,
2378 // array_filter with strlen filters out NULL, '' and FALSE but not 0.
2381 $contributionParams['line_item'] = $templateContribution['line_item'];
2382 $contributionParams['status_id'] = 'Pending';
2384 foreach (['contact_id', 'campaign_id', 'financial_type_id', 'currency', 'source', 'amount_level', 'address_id', 'on_behalf', 'source_contact_id', 'tax_amount', 'contribution_page_id', 'total_amount'] as $fieldName) {
2385 if (isset($templateContribution[$fieldName])) {
2386 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2390 $contributionParams['source'] = $contributionParams['source'] ??
ts('Recurring contribution');
2392 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2393 $temporaryObject = new CRM_Contribute_BAO_Contribution();
2394 $temporaryObject->copyCustomFields($templateContribution['id'], $createContribution['id']);
2395 self
::handleMembershipIDOverride($createContribution['id'], $input);
2396 // Add new soft credit against current $contribution.
2397 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($contributionParams['contribution_recur_id'], $createContribution['id']);
2398 return $createContribution;
2402 * Get individual id for onbehalf contribution.
2404 * @param int $contributionId
2406 * @param int $contributorId
2410 * containing organization id and individual id
2412 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2416 if (!$contributionId) {
2420 // fetch contributor id if null
2421 if (!$contributorId) {
2422 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2423 $contributionId, 'contact_id'
2427 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2428 $activityTypeId = array_search('Contribution', $activityTypeIds);
2430 if ($activityTypeId && $contributorId) {
2432 SELECT civicrm_activity_contact.contact_id
2433 FROM civicrm_activity_contact
2434 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2435 WHERE civicrm_activity.activity_type_id = %1
2436 AND civicrm_activity.source_record_id = %2
2437 AND civicrm_activity_contact.record_type_id = %3
2440 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2441 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2444 1 => [$activityTypeId, 'Integer'],
2445 2 => [$contributionId, 'Integer'],
2446 3 => [$sourceID, 'Integer'],
2449 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2451 // for on behalf contribution source is individual and contributor is organization
2452 if ($sourceContactId && $sourceContactId != $contributorId) {
2453 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2454 // get rel type id for employee of relation
2455 foreach ($relationshipTypeIds as $id => $typeVals) {
2456 if ($typeVals['name_a_b'] == 'Employee of') {
2457 $relationshipTypeId = $id;
2462 $rel = new CRM_Contact_DAO_Relationship();
2463 $rel->relationship_type_id
= $relationshipTypeId;
2464 $rel->contact_id_a
= $sourceContactId;
2465 $rel->contact_id_b
= $contributorId;
2466 if ($rel->find(TRUE)) {
2467 $ids['individual_id'] = $rel->contact_id_a
;
2468 $ids['organization_id'] = $rel->contact_id_b
;
2479 public static function getContributionDates() {
2480 $config = CRM_Core_Config
::singleton();
2481 $currentMonth = date('m');
2482 $currentDay = date('d');
2483 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2484 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2485 (int ) $config->fiscalYearStart
['d'] > $currentDay
2488 $year = date('Y') - 1;
2493 $year = ['Y' => $year];
2494 $yearDate = $config->fiscalYearStart
;
2495 $yearDate = array_merge($year, $yearDate);
2496 $yearDate = CRM_Utils_Date
::format($yearDate);
2498 $monthDate = date('Ym') . '01';
2504 'yearDate' => $yearDate,
2505 'monthDate' => $monthDate,
2510 * Load objects relations to contribution object.
2511 * Objects are stored in the $_relatedObjects property
2512 * In the first instance we are just moving functionality from BASEIpn -
2514 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2516 * Note that the unit test for the BaseIPN class tests this function
2518 * @param array $input
2519 * Input as delivered from Payment Processor.
2521 * Ids as Loaded by Payment Processor.
2522 * @param bool $loadAll
2523 * Load all related objects - even where id not passed in? (allows API to call this).
2526 * @throws CRM_Core_Exception
2528 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2529 // @todo deprecate this function - the steps should be
2530 // 1) add additional functions like 'getRelatedMemberships'
2531 // 2) switch all calls that refer to ->_relatedObjects to
2532 // using the helper functions
2533 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2534 // 4) make ->_relatedObjects protected
2535 // 5) hone up the individual functions to not use rely on this having been called
2536 // 6) deprecate like mad
2538 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2539 if (empty($ids['contact']) && isset($this->contact_id
)) {
2540 $ids['contact'] = $this->contact_id
;
2543 if (empty($this->_component
)) {
2544 if (!empty($ids['event'])) {
2545 $this->_component
= 'event';
2548 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2552 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2553 // refactoring than anything else, and has unit test coverage.
2554 if (empty($this->financial_type_id
)) {
2558 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2563 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id
) {
2564 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2565 $this->contribution_page_id
,
2568 if ($paymentProcessorID) {
2569 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2573 $ids['contributionType'] = $this->financial_type_id
;
2574 $ids['financialType'] = $this->financial_type_id
;
2575 if ($this->contribution_page_id
) {
2576 $ids['contributionPage'] = $this->contribution_page_id
;
2579 $this->loadRelatedEntitiesByID($ids);
2581 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2582 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2585 if (!empty($ids['pledge_payment'])) {
2586 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2587 if (empty($paymentID)) {
2590 $payment = new CRM_Pledge_BAO_PledgePayment();
2591 $payment->id
= $paymentID;
2592 if (!$payment->find(TRUE)) {
2593 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2595 $this->_relatedObjects
['pledge_payment'][] = $payment;
2599 // These are probably no longer accessed from anywhere
2600 // @todo remove this line, after ensuring not used.
2601 $ids = $this->loadRelatedMembershipObjects($ids);
2603 if ($this->_component
!= 'contribute') {
2604 // we are in event mode
2605 // make sure event exists and is valid
2606 $event = new CRM_Event_BAO_Event();
2607 $event->id
= $ids['event'];
2608 if ($ids['event'] &&
2611 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2614 $this->_relatedObjects
['event'] = &$event;
2616 $participant = new CRM_Event_BAO_Participant();
2617 $participant->id
= $ids['participant'];
2618 if ($ids['participant'] &&
2619 !$participant->find(TRUE)
2621 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2623 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2625 $this->_relatedObjects
['participant'] = &$participant;
2627 // get the payment processor id from event - this is inaccurate see CRM-16923
2628 // in future we should look at throwing an exception here rather than an dubious guess.
2629 if (!$paymentProcessorID) {
2630 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2631 if ($paymentProcessorID) {
2632 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2637 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($this->id
);
2638 if (!empty($relatedContact['individual_id'])) {
2639 $ids['related_contact'] = $relatedContact['individual_id'];
2642 if ($paymentProcessorID) {
2643 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2644 $this->is_test ?
'test' : 'live'
2646 $ids['paymentProcessor'] = $paymentProcessorID;
2647 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2650 // Add contribution id to $ids. CRM-20401
2651 $ids['contribution'] = $this->id
;
2656 * Create array of message information - ie. return html version, txt version, to field
2658 * @param array $input
2659 * Incoming information.
2660 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2661 * just check presence of recur object but maintaining legacy approach
2664 * IDs of related objects.
2665 * @param array $values
2666 * Any values that may have already been compiled by calling process.
2667 * This is augmented by values 'gathered' by gatherMessageValues
2668 * @param bool $returnMessageText
2669 * Distinguishes between whether to send message or return.
2670 * message text. We are working towards this function ALWAYS returning message text & calling
2671 * function doing emails / pdfs with it
2677 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2678 $this->loadRelatedObjects($input, $ids, TRUE);
2680 if (empty($this->_component
)) {
2681 $this->_component
= $input['component'] ??
NULL;
2684 //not really sure what params might be passed in but lets merge em into values
2685 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2686 $values['is_email_receipt'] = !$returnMessageText;
2687 foreach (['receipt_date', 'cc_receipt', 'bcc_receipt', 'receipt_from_name', 'receipt_from_email', 'receipt_text', 'pay_later_receipt'] as $fld) {
2688 if (!empty($input[$fld])) {
2689 $values[$fld] = $input[$fld];
2693 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2694 //what does recur 'mean here - to do with payment processor return functionality but
2695 // what is the importance
2696 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2697 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2699 $entityID = $entity = NULL;
2700 if (isset($ids['contribution'])) {
2701 $entity = 'contribution';
2702 $entityID = $ids['contribution'];
2704 if (!empty($ids['membership'])) {
2705 //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
2706 // 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
2707 // line having loaded an array
2708 $ids['membership'] = (array) $ids['membership'];
2709 $entity = 'membership';
2710 $entityID = $ids['membership'][0];
2713 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2714 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2715 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2717 // todo remove strtolower - check consistency
2718 if (strtolower($this->_component
) === 'event') {
2719 $eventParams = ['id' => $this->_relatedObjects
['participant']->event_id
];
2720 $values['event'] = [];
2722 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2724 //get location details
2726 'entity_id' => $this->_relatedObjects
['participant']->event_id
,
2727 'entity_table' => 'civicrm_event',
2729 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2732 'entity_table' => 'civicrm_event',
2733 'entity_id' => $ids['event'],
2734 'module' => 'CiviEvent',
2737 [$custom_pre_id, $custom_post_ids] = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2739 $values['custom_pre_id'] = $custom_pre_id;
2740 $values['custom_post_id'] = $custom_post_ids;
2741 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2742 //and cases involving status updation through ipn
2743 // whatever that means!
2744 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2745 // perhaps we should throw an e-notice if amount is set & force total_amount?
2746 if (!empty($input['amount'])) {
2747 $values['totalAmount'] = $input['amount'];
2749 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2750 if ($values['event']['is_email_confirm']) {
2751 $values['is_email_receipt'] = 1;
2754 if (!empty($ids['contribution'])) {
2755 $values['contributionId'] = $ids['contribution'];
2758 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2759 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2763 $values['contribution_id'] = $this->id
;
2764 if (!empty($ids['related_contact'])) {
2765 $values['related_contact'] = $ids['related_contact'];
2766 if (isset($ids['onbehalf_dupe_alert'])) {
2767 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2770 'contact_id' => $ids['contact'],
2771 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2772 'Home', 'id', 'name'
2775 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2776 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display'] ??
NULL);
2779 if ($this->is_test
) {
2782 if (!empty($this->_relatedObjects
['membership'])) {
2783 foreach ($this->_relatedObjects
['membership'] as $membership) {
2784 if ($membership->id
) {
2785 $values['membership_id'] = $membership->id
;
2786 $values['isMembership'] = TRUE;
2787 $values['membership_assign'] = TRUE;
2789 // need to set the membership values here
2790 $template->assign('membership_name',
2791 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2793 $template->assign('mem_start_date', $membership->start_date
);
2794 $template->assign('mem_join_date', $membership->join_date
);
2795 $template->assign('mem_end_date', $membership->end_date
);
2796 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2797 $template->assign('mem_status', $membership_status);
2798 if ($membership_status === 'Pending' && $membership->is_pay_later
== 1) {
2799 $values['is_pay_later'] = 1;
2801 // Pass amount to floatval as string '0.00' is considered a
2802 // valid amount and includes Fee section in the mail.
2803 if (isset($values['amount'])) {
2804 $values['amount'] = floatval($values['amount']);
2807 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2808 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2809 $template->assign('cancelSubscriptionUrl', $url);
2810 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2811 $template->assign('updateSubscriptionBillingUrl', $url);
2812 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2813 $template->assign('updateSubscriptionUrl', $url);
2816 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2819 // otherwise if its about sending emails, continue sending without return, as we
2820 // don't want to exit the loop.
2825 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2831 * Gather values for contribution mail - this function has been created
2832 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2833 * Values related to the contribution in question are gathered
2835 * @param array $input
2836 * Input into function (probably from payment processor).
2837 * @param array $values
2839 * The set of ids related to the input.
2842 * @throws \CRM_Core_Exception
2844 public function _gatherMessageValues($input, &$values, $ids = []) {
2845 // set display address of contributor
2846 $values['billingName'] = '';
2847 if ($this->address_id
) {
2848 $addressDetails = CRM_Core_BAO_Address
::getValues(['id' => $this->address_id
], FALSE, 'id');
2849 $addressDetails = reset($addressDetails);
2850 $values['billingName'] = $addressDetails['name'] ??
'';
2852 // Else we assign the billing address of the contribution contact.
2854 $addressDetails = (array) CRM_Core_BAO_Address
::getValues(['contact_id' => $this->contact_id
, 'is_billing' => 1]);
2855 $addressDetails = reset($addressDetails);
2857 $values['address'] = $addressDetails['display'] ??
'';
2859 if ($this->_component
=== 'contribute') {
2860 //get soft contributions
2861 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2862 if (!empty($softContributions)) {
2863 // For pcp soft credit, there is no 'soft_credit' member it comes
2864 // back in different array members, but shortly after returning from
2865 // this function it calls _assignMessageVariablesToTemplate which does
2866 // its own lookup of any pcp soft credit, so we can skip it here.
2867 $values['softContributions'] = $softContributions['soft_credit'] ??
NULL;
2869 if (isset($this->contribution_page_id
)) {
2870 // This is a call we want to use less, in favour of loading related objects.
2871 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2872 if ($this->contribution_page_id
) {
2873 // This is precautionary as there are some legacy flows, but it should really be
2875 if (!isset($this->_relatedObjects
['contributionPage'])) {
2876 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id
]);
2878 CRM_Contribute_BAO_Contribution_Utils
::overrideDefaultCurrency($values);
2881 // no contribution page -probably back office
2883 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2884 $values['title'] = 'Contribution';
2886 // set lineItem for contribution
2888 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2889 if (!empty($lineItems)) {
2890 $firstLineItem = reset($lineItems);
2892 if (!empty($firstLineItem['price_set_id'])) {
2893 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
2894 'id' => $firstLineItem['price_set_id'],
2895 'return' => 'is_quick_config, id',
2897 $values['priceSetID'] = $priceSet['id'];
2899 foreach ($lineItems as &$eachItem) {
2900 if ($eachItem['entity_table'] === 'civicrm_membership') {
2901 $membership = reset(civicrm_api3('Membership', 'get', [
2902 'id' => $eachItem['entity_id'],
2903 'return' => ['join_date', 'start_date', 'end_date'],
2906 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($membership['join_date']);
2907 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($membership['start_date']);
2908 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($membership['end_date']);
2911 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2912 // However, that does create upgrade pain so would be better to be phased in.
2913 $values['useForMember'] = empty($priceSet['is_quick_config']);
2915 $values['lineItem'][0] = $lineItems;
2919 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2923 // if this is onbehalf of contribution then set related contact
2924 if (!empty($relatedContact['individual_id'])) {
2925 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2929 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects
['participant']->id
, $this->id
));
2932 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', NULL, $this->id
);
2935 foreach ($groupTree as $key => $group) {
2936 if ($key === 'info') {
2940 foreach ($group['fields'] as $k => $customField) {
2941 $groupLabel = $group['title'];
2942 if (!empty($customField['customValue'])) {
2943 foreach ($customField['customValue'] as $customFieldValues) {
2944 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
2949 $values['customGroup'] = $customGroup;
2951 $values['is_pay_later'] = $this->is_pay_later
;
2957 * Assign message variables to template but try to break the habit.
2959 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2960 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2961 * multiple recurring payments for processors like IATS that use tokens.
2963 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2964 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2965 * Note we send directly from this function in some cases because it is only partly refactored.
2967 * Don't call this function directly as the signature will change.
2971 * @param bool $returnMessageText
2975 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2976 // @todo - this should have a better separation of concerns - ie.
2977 // gatherMessageValues should build an array of values to be assigned to the template
2978 // and this function should assign them (assigning null if not set).
2979 // the way the pcpParams & honor Params section works is a baby-step towards this.
2980 $template = CRM_Core_Smarty
::singleton();
2981 $template->assign('billingName', $values['billingName']);
2983 //assign honor information to receipt message
2984 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2987 'soft_credit_type' => NULL,
2988 'honor_block_is_active' => NULL,
2990 if (isset($softRecord['soft_credit'])) {
2991 //if id of contribution page is present
2992 if (!empty($values['id'])) {
2993 $values['honor'] = [
2994 'honor_profile_values' => [],
2995 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2996 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2999 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3000 $honorParams['honor_block_is_active'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3003 //offline contribution
3004 $softCreditTypes = $softCredits = [];
3005 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3006 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3007 $softCredits[$key] = [
3008 'Name' => $softCredit['contact_name'],
3009 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
3012 $template->assign('softCreditTypes', $softCreditTypes);
3013 $template->assign('softCredits', $softCredits);
3017 $dao = new CRM_Contribute_DAO_ContributionProduct();
3018 $dao->contribution_id
= $this->id
;
3019 if ($dao->find(TRUE)) {
3020 $premiumId = $dao->product_id
;
3021 $template->assign('option', $dao->product_option
);
3023 $productDAO = new CRM_Contribute_DAO_Product();
3024 $productDAO->id
= $premiumId;
3025 $productDAO->find(TRUE);
3026 $template->assign('selectPremium', TRUE);
3027 $template->assign('product_name', $productDAO->name
);
3028 $template->assign('price', $productDAO->price
);
3029 $template->assign('sku', $productDAO->sku
);
3031 $template->assign('title', $values['title'] ??
NULL);
3032 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
3033 if (!$values['amount'] && isset($this->total_amount
)) {
3034 $values['amount'] = $this->total_amount
;
3039 'pcp_display_in_roll' => NULL,
3040 'pcp_roll_nickname' => NULL,
3041 'pcp_personal_note' => NULL,
3045 if (strtolower($this->_component
) == 'contribute') {
3047 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3048 $softDAO->contribution_id
= $this->id
;
3049 if ($softDAO->find(TRUE)) {
3050 $pcpParams['pcpBlock'] = TRUE;
3051 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll
;
3052 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname
;
3053 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note
;
3055 //assign the pcp page title for email subject
3056 $pcpDAO = new CRM_PCP_DAO_PCP();
3057 $pcpDAO->id
= $softDAO->pcp_id
;
3058 if ($pcpDAO->find(TRUE)) {
3059 $pcpParams['title'] = $pcpDAO->title
;
3063 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3064 $template->assign($templateKey, $templateValue);
3067 if ($this->financial_type_id
) {
3068 $values['financial_type_id'] = $this->financial_type_id
;
3071 $template->assign('trxn_id', $this->trxn_id
);
3072 $template->assign('receive_date',
3073 CRM_Utils_Date
::processDate($this->receive_date
)
3075 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
3076 $template->assign('action', $this->is_test ?
1024 : 1);
3077 $template->assign('receipt_text', $values['receipt_text'] ??
NULL);
3078 $template->assign('is_monetary', 1);
3079 $template->assign('is_recur', !empty($this->contribution_recur_id
));
3080 $template->assign('currency', $this->currency
);
3081 $template->assign('address', CRM_Utils_Address
::format($input));
3082 if (!empty($values['customGroup'])) {
3083 $template->assign('customGroup', $values['customGroup']);
3085 if (!empty($values['softContributions'])) {
3086 $template->assign('softContributions', $values['softContributions']);
3088 if ($this->_component
== 'event') {
3089 $template->assign('title', $values['event']['title']);
3090 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
3092 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
3093 $viewRoles[] = $participantRoles[$v];
3095 $values['event']['participant_role'] = implode(', ', $viewRoles);
3096 $template->assign('event', $values['event']);
3097 $template->assign('participant', $values['participant']);
3098 $template->assign('location', $values['location']);
3099 $template->assign('customPre', $values['custom_pre_id']);
3100 $template->assign('customPost', $values['custom_post_id']);
3103 if ($this->_relatedObjects
['participant']->is_test
) {
3107 $values['params'] = [];
3108 //to get email of primary participant.
3109 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
3110 $primaryAmount[] = [
3111 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
3112 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
3114 //build an array of cId/pId of participants
3115 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
3116 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
3117 //send receipt to additional participant if exists
3118 if (count($additionalIDs)) {
3119 $template->assign('isPrimary', 0);
3120 $template->assign('customProfile', NULL);
3121 //set additionalParticipant true
3122 $values['params']['additionalParticipant'] = TRUE;
3123 foreach ($additionalIDs as $pId => $cId) {
3125 //to change the status pending to completed
3126 $additional = new CRM_Event_DAO_Participant();
3127 $additional->id
= $pId;
3128 $additional->contact_id
= $cId;
3129 $additional->find(TRUE);
3130 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
3131 $additional->status_id
= 1;
3132 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
3133 //if additional participant dont have email
3135 if (!$additionalParticipantInfo) {
3136 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
3139 'label' => $additional->fee_level
,
3140 'amount' => $additional->fee_amount
,
3142 $primaryAmount[] = [
3143 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
3144 'amount' => $additional->fee_amount
,
3146 $additional->save();
3147 $template->assign('amount', $amount);
3148 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3152 //build an array of custom profile and assigning it to template
3153 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
3155 if (count($customProfile)) {
3156 $template->assign('customProfile', $customProfile);
3159 // for primary contact
3160 $values['params']['additionalParticipant'] = FALSE;
3161 $template->assign('isPrimary', 1);
3162 $template->assign('amount', $primaryAmount);
3163 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
3164 if ($this->payment_instrument_id
) {
3165 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
3166 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
3168 // carry paylater, since we did not created billing,
3169 // so need to pull email from primary location, CRM-4395
3170 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3176 * Check whether payment processor supports
3177 * cancellation of contribution subscription
3179 * @param int $contributionId
3182 * @param bool $isNotCancelled
3186 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3187 $cacheKeyString = "$contributionId";
3188 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3190 static $supportsCancel = [];
3192 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3193 $supportsCancel[$cacheKeyString] = FALSE;
3194 $isCancelled = FALSE;
3196 if ($isNotCancelled) {
3197 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3200 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3201 if (!empty($paymentObject)) {
3202 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3205 return $supportsCancel[$cacheKeyString];
3209 * Check whether subscription is already cancelled.
3211 * @param int $contributionId
3215 * contribution status
3217 public static function isSubscriptionCancelled($contributionId) {
3219 SELECT cr.contribution_status_id
3220 FROM civicrm_contribution_recur cr
3221 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3222 WHERE con.id = %1 LIMIT 1";
3223 $params = [1 => [$contributionId, 'Integer']];
3224 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3225 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
3226 if ($status == 'Cancelled') {
3233 * Create all financial accounts entry.
3235 * @param array $params
3236 * Contribution object, line item array and params for trxn.
3239 * @return null|\CRM_Core_BAO_FinancialTrxn
3241 public static function recordFinancialAccounts(&$params) {
3242 $skipRecords = $return = FALSE;
3243 $isUpdate = !empty($params['prevContribution']);
3245 $additionalParticipantId = [];
3246 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3247 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3249 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3250 $entityId = $params['participant_id'];
3251 $entityTable = 'civicrm_participant';
3252 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3254 elseif (!empty($params['membership_id'])) {
3255 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3256 // are created off one contribution should be handled elsewhere
3257 $entityId = $params['membership_id'];
3258 $entityTable = 'civicrm_membership';
3261 $entityId = $params['contribution']->id
;
3262 $entityTable = 'civicrm_contribution';
3265 $entityID[] = $entityId;
3266 if (!empty($additionalParticipantId)) {
3267 $entityID +
= $additionalParticipantId;
3268 // build line item array if necessary
3269 if ($additionalParticipantId) {
3270 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
3273 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3274 if (empty($params['prevContribution'])) {
3278 $statusId = $params['contribution']->contribution_status_id
;
3280 if ($contributionStatus != 'Failed' &&
3281 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3283 $skipRecords = TRUE;
3288 if (in_array($contributionStatus, $pendingStatus)) {
3289 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3290 $params['financial_type_id'],
3291 'Accounts Receivable Account is'
3294 elseif (!empty($params['payment_processor'])) {
3295 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3296 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3297 'id' => $params['payment_processor'],
3298 'return' => 'payment_instrument_id',
3301 elseif (!empty($params['payment_instrument_id'])) {
3302 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3304 // dev/financial#160 - If this is a contribution update, also check for an existing payment_instrument_id.
3305 elseif ($isUpdate && $params['prevContribution']->payment_instrument_id
) {
3306 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount((int) $params['prevContribution']->payment_instrument_id
);
3309 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3310 $queryParams = [1 => [$relationTypeId, 'Integer']];
3311 $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);
3314 $totalAmount = $params['total_amount'] ??
NULL;
3315 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3316 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3318 //build financial transaction params
3320 'contribution_id' => $params['contribution']->id
,
3321 'to_financial_account_id' => $params['to_financial_account_id'],
3322 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3323 'total_amount' => $totalAmount,
3324 'fee_amount' => $params['fee_amount'] ??
NULL,
3325 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3326 'currency' => $params['contribution']->currency
,
3327 'trxn_id' => $params['contribution']->trxn_id
,
3328 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3329 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3330 // this should really default to completed (after discussion).
3331 'status_id' => $statusId,
3332 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3333 'check_number' => $params['check_number'] ??
NULL,
3334 'pan_truncation' => $params['pan_truncation'] ??
NULL,
3335 'card_type_id' => $params['card_type_id'] ??
NULL,
3337 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3338 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3339 if (isset($params['refund_trxn_id'])) {
3340 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3341 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3344 //CRM-16259, set is_payment flag for non pending status
3345 if (!in_array($contributionStatus, $pendingStatus)) {
3346 $trxnParams['is_payment'] = 1;
3348 if (!empty($params['payment_processor'])) {
3349 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3352 if (empty($trxnParams['payment_processor_id'])) {
3353 unset($trxnParams['payment_processor_id']);
3356 $params['trxnParams'] = $trxnParams;
3360 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3361 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3362 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3363 if (!isset($params['trxnParams']['trxn_id'])) {
3364 // Actually I have no idea why we are overwriting any values from the previous contribution.
3365 // (filling makes sense to me). However, only protecting this value as I really really know we
3366 // don't want this one overwritten.
3368 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3370 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3372 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3373 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3374 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3376 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3377 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3380 //if financial type is changed
3381 if (!empty($params['financial_type_id']) &&
3382 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3384 $accountRelationship = 'Income Account is';
3385 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3386 $accountRelationship = 'Deferred Revenue Account is';
3388 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id
, $accountRelationship);
3389 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3390 if ($oldFinancialAccount != $newFinancialAccount) {
3391 $params['total_amount'] = 0;
3392 // If we have a fee amount set reverse this as well.
3393 if (isset($params['fee_amount'])) {
3394 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3396 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3397 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3398 $params['prevContribution']->financial_type_id
, $accountRelationship);
3401 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3402 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3403 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3406 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params, 'changeFinancialType');
3407 $params['skipLineItem'] = FALSE;
3408 foreach ($params['line_item'] as &$lineItems) {
3409 foreach ($lineItems as &$line) {
3410 $line['financial_type_id'] = $params['financial_type_id'];
3413 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3414 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3415 $params['financial_account_id'] = $newFinancialAccount;
3416 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3417 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3418 if (isset($params['fee_amount'])) {
3419 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3421 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params);
3422 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE);
3423 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3425 $params['deferred_financial_account_id'] = $newFinancialAccount;
3429 //Update contribution status
3430 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3431 if (!isset($params['refund_trxn_id'])) {
3432 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3433 // gets preference over another so I am only 'protecting' a very specific tested flow
3434 // and letting natural justice take care of the rest.
3435 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3437 if (!empty($params['contribution_status_id']) &&
3438 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3440 //Update Financial Records
3441 $callUpdateFinancialAccounts = self
::updateFinancialAccountsOnContributionStatusChange($params);
3442 if ($callUpdateFinancialAccounts) {
3443 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params, 'changedStatus');
3444 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3449 // change Payment Instrument for a Completed contribution
3450 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3451 // instrument is null and now new payment instrument is added along with the payment
3452 if (!$params['contribution']->payment_instrument_id
) {
3453 $params['contribution']->find(TRUE);
3455 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3456 $params['trxnParams']['check_number'] = $params['check_number'] ??
NULL;
3458 if (self
::isPaymentInstrumentChange($params, $pendingStatus)) {
3459 $updated = CRM_Core_BAO_FinancialTrxn
::updateFinancialAccountsOnPaymentInstrumentChange($params);
3462 //if Change contribution amount
3463 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ??
NULL;
3464 $params['trxnParams']['net_amount'] = $params['net_amount'] ??
NULL;
3465 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3466 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3467 if (isset($totalAmount) &&
3468 $totalAmount != $params['prevContribution']->total_amount
3470 //Update Financial Records
3471 $params['trxnParams']['from_financial_account_id'] = NULL;
3472 CRM_Contribute_BAO_FinancialProcessor
::updateFinancialAccounts($params, 'changedAmount');
3473 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3478 // Looks like we might have a data correction update.
3479 // This would be a case where a transaction id has been entered but it is incorrect &
3480 // the person goes back in & fixes it, as opposed to a new transaction.
3481 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3482 // the data fix scenario.
3484 if (isset($params['refund_trxn_id'])) {
3485 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3486 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3487 civicrm_api3('FinancialTrxn', 'create', [
3488 'id' => $refundIDs['financialTrxnId'],
3489 'trxn_id' => $params['refund_trxn_id'],
3493 $cardType = $params['card_type_id'] ??
NULL;
3494 $panTruncation = $params['pan_truncation'] ??
NULL;
3495 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3500 // records finanical trxn and entity financial trxn
3501 // also make it available as return value
3502 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3503 $trxnParams['pan_truncation'] = $params['pan_truncation'] ??
NULL;
3504 $trxnParams['card_type_id'] = $params['card_type_id'] ??
NULL;
3505 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3506 $params['entity_id'] = $financialTxn->id
;
3507 self
::$_trxnIDs[] = $financialTxn->id
;
3510 // record line items and financial items
3511 if (empty($params['skipLineItem'])) {
3512 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3515 // create batch entry if batch_id is passed and
3516 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3517 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3519 'batch_id' => $params['batch_id'],
3520 'entity_table' => 'civicrm_financial_trxn',
3521 'entity_id' => $financialTxn->id
,
3523 CRM_Batch_BAO_EntityBatch
::create($entityParams);
3526 // when a fee is charged
3527 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3528 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3531 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3532 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3534 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3535 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3536 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3538 unset($params['line_item']);
3539 self
::$_trxnIDs = NULL;
3544 * Is this contribution status a reversal.
3546 * If so we would expect to record a negative value in the financial_trxn table.
3548 * @param int $status_id
3552 public static function isContributionStatusNegative($status_id) {
3553 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3554 return in_array(CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3558 * Check status validation on update of a contribution.
3560 * @param array $values
3561 * Previous form values before submit.
3563 * @param array $fields
3564 * The input form values.
3566 * @param array $errors
3571 public static function checkStatusValidation($values, &$fields, &$errors) {
3572 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3573 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3574 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3578 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3580 'Cancelled' => ['Completed', 'Refunded'],
3581 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3582 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3583 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3584 'Refunded' => ['Cancelled', 'Completed'],
3585 'Partially paid' => ['Completed'],
3586 'Pending refund' => ['Completed', 'Refunded'],
3587 'Failed' => ['Pending'],
3590 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3591 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3593 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3594 1 => $contributionStatuses[$values['contribution_status_id']],
3595 2 => $contributionStatuses[$fields['contribution_status_id']],
3601 * Delete contribution of contact.
3603 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3605 * @param int $contactId
3609 public static function deleteContactContribution($contactId) {
3610 $contribution = new CRM_Contribute_DAO_Contribution();
3611 $contribution->contact_id
= $contactId;
3612 $contribution->find();
3613 while ($contribution->fetch()) {
3614 self
::deleteContribution($contribution->id
);
3619 * Get options for a given contribution field.
3621 * @param string $fieldName
3622 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3623 * @param array $props whatever is known about this dao object.
3625 * @return array|bool
3626 * @see CRM_Core_DAO::buildOptions
3629 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3630 $className = __CLASS__
;
3632 if (isset($props['orderColumn'])) {
3633 $params['orderColumn'] = $props['orderColumn'];
3635 switch ($fieldName) {
3636 // This field is not part of this object but the api supports it
3637 case 'payment_processor':
3638 $className = 'CRM_Contribute_BAO_ContributionPage';
3639 // Filter results by contribution page
3640 if (!empty($props['contribution_page_id'])) {
3641 $page = civicrm_api('contribution_page', 'getsingle', [
3643 'id' => ($props['contribution_page_id']),
3645 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3646 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3650 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3651 case 'honor_type_id':
3652 $className = 'CRM_Contribute_BAO_ContributionSoft';
3653 $fieldName = 'soft_credit_type_id';
3654 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3657 case 'contribution_status_id':
3658 if ($context !== 'validate') {
3659 $params['condition'] = "v.name <> 'Template'";
3662 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3666 * Validate financial type.
3668 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3670 * @param int $financialTypeId
3671 * Financial Type id.
3673 * @param string $relationName
3675 * @return array|bool
3677 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3678 $financialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeId, $relationName);
3680 if (!$financialAccount) {
3681 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3687 * @param int $targetCid
3688 * @param $activityType
3689 * @param string $title
3690 * @param int $contributionId
3691 * @param string $totalAmount
3692 * @param string $currency
3693 * @param string $trxn_date
3695 * @throws \CRM_Core_Exception
3696 * @throws \CiviCRM_API3_Exception
3698 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
3699 $paymentAmount = CRM_Utils_Money
::format($totalAmount, $currency);
3700 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3701 $date = CRM_Utils_Date
::isoToMysql($trxn_date);
3702 // source record id would be the contribution id
3703 $srcRecId = $contributionId;
3707 'source_contact_id' => $targetCid,
3708 'source_record_id' => $srcRecId,
3709 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
3710 'subject' => $subject,
3711 'activity_date_time' => $date,
3712 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
3713 'skipRecentView' => TRUE,
3716 // create activity with target contacts
3717 $session = CRM_Core_Session
::singleton();
3718 $id = $session->get('userID');
3720 $activityParams['source_contact_id'] = $id;
3721 $activityParams['target_contact_id'][] = $targetCid;
3723 civicrm_api3('Activity', 'create', $activityParams);
3727 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3730 * @param string $component
3731 * @param bool $getTrxnInfo
3735 * @throws \CRM_Core_Exception
3736 * @throws \CiviCRM_API3_Exception
3738 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
3739 // @todo deprecate passing in component - always call with contribution.
3740 if ($component == 'event') {
3741 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3743 if (!$contributionId) {
3744 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3745 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3746 $id = $primaryParticipantId;
3748 if (!$contributionId) {
3753 elseif ($component == 'membership') {
3754 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
3757 $contributionId = $id;
3760 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
3761 // but need to unpick the whole trxn_id it's returning first.
3762 $oldCalculation = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3763 $baseTrxnId = !empty($oldCalculation['trxn_id']) ?
$oldCalculation['trxn_id'] : NULL;
3765 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3766 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3768 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3770 $paymentBalance = CRM_Contribute_BAO_Contribution
::getContributionBalance($contributionId, $total);
3772 $contribution = civicrm_api3('Contribution', 'getsingle', [
3773 'id' => $contributionId,
3777 'contribution_status_id',
3778 'financial_type_id',
3782 $info['payLater'] = $contribution['is_pay_later'];
3783 $info['contribution_status'] = $contribution['contribution_status'];
3784 $info['currency'] = $contribution['currency'];
3786 $info['total'] = $total;
3787 $info['paid'] = $total - $paymentBalance;
3788 $info['balance'] = $paymentBalance;
3790 $info['component'] = $component;
3791 if ($getTrxnInfo && $baseTrxnId) {
3792 $info['transaction'] = self
::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
3795 $info['payment_links'] = self
::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
3800 * Get the outstanding balance on a contribution.
3802 * @param int $contributionId
3803 * @param float $contributionTotal
3804 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
3807 * @throws \CRM_Core_Exception
3809 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
3810 if ($contributionTotal === NULL) {
3811 $contributionTotal = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
3814 return (float) CRM_Utils_Money
::subtractCurrencies(
3816 CRM_Core_BAO_FinancialTrxn
::getTotalPayments($contributionId, TRUE),
3817 CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
3822 * Check financial type validation on update of a contribution.
3824 * @param int $financialTypeId
3825 * Value of latest Financial Type.
3827 * @param int $contributionId
3830 * @param array $errors
3835 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3836 if (!empty($financialTypeId)) {
3837 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3838 if ($oldFinancialTypeId == $financialTypeId) {
3842 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3844 '1' => [$contributionId, 'Integer'],
3846 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3847 if ($result->N
> 1) {
3848 $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.');
3853 * Update related pledge payment payments.
3855 * This function has been refactored out of the back office contribution form and may
3856 * still overlap with other functions.
3858 * @param string $action
3859 * @param int $pledgePaymentID
3860 * @param int $contributionID
3861 * @param bool $adjustTotalAmount
3862 * @param float $total_amount
3863 * @param float $original_total_amount
3864 * @param int $contribution_status_id
3865 * @param int $original_contribution_status_id
3867 public static function updateRelatedPledge(
3873 $original_total_amount,
3874 $contribution_status_id,
3875 $original_contribution_status_id
3877 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
3881 if ($pledgePaymentID) {
3882 //store contribution id in payment record.
3883 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3886 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3893 if (!$pledgePaymentID) {
3896 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3902 $updatePledgePaymentStatus = FALSE;
3904 // If either the status or the amount has changed we update the pledge status.
3905 if ($action & CRM_Core_Action
::ADD
) {
3906 $updatePledgePaymentStatus = TRUE;
3908 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3909 ($original_total_amount != $total_amount))
3911 $updatePledgePaymentStatus = TRUE;
3914 if ($updatePledgePaymentStatus) {
3915 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3917 $contribution_status_id,
3926 * Is there only one line item attached to the contribution.
3932 * @throws \CiviCRM_API3_Exception
3934 public static function isSingleLineItem($id) {
3935 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
3936 return ($lineItemCount == 1);
3940 * Complete an order.
3942 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
3944 * Currently overloaded to complete a transaction & repeat a transaction - fix!
3946 * Moving it out of the BaseIPN class is just the first step.
3948 * @param array $input
3949 * @param int $recurringContributionID
3950 * @param int|null $contributionID
3951 * @param bool $isPostPaymentCreate
3952 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
3953 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
3954 * transitioning related elements).
3957 * @throws \API_Exception
3958 * @throws \CRM_Core_Exception
3959 * @throws \CiviCRM_API3_Exception
3961 public static function completeOrder($input, $recurringContributionID, $contributionID, $isPostPaymentCreate = FALSE) {
3962 $transaction = new CRM_Core_Transaction();
3964 $inputContributionWhiteList = [
3969 'payment_instrument_id',
3974 'contribution_status_id',
3977 'financial_type_id',
3980 $paymentProcessorId = $input['payment_processor_id'] ??
NULL;
3982 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
3984 $contributionParams = array_merge([
3985 'contribution_status_id' => $completedContributionStatusID,
3986 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
3989 $contributionParams['payment_processor'] = $paymentProcessorId;
3991 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
3992 $contributionParams['payment_instrument_id'] = PaymentProcessor
::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
3995 if ($recurringContributionID) {
3996 $contributionParams['contribution_recur_id'] = $recurringContributionID;
3999 if (!$contributionID) {
4000 $contributionResult = self
::repeatTransaction($input, $contributionParams);
4001 $contributionID = $contributionResult['id'];
4004 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4005 self
::updateMembershipBasedOnCompletionOfContribution(
4007 $input['trxn_date'] ??
date('YmdHis')
4011 $participantPayments = civicrm_api3('ParticipantPayment', 'get', ['contribution_id' => $contributionID, 'return' => 'participant_id', 'sequential' => 1])['values'];
4012 if (!empty($participantPayments) && empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4013 foreach ($participantPayments as $participantPayment) {
4014 $participantParams['id'] = $participantPayment['participant_id'];
4015 $participantParams['status_id'] = 'Registered';
4016 civicrm_api3('Participant', 'create', $participantParams);
4020 $contributionParams['id'] = $contributionID;
4021 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4023 if (empty($contributionResult)) {
4024 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4027 $transaction->commit();
4028 \Civi
::log()->info("Contribution {$contributionParams['id']} updated successfully");
4030 $contributionSoft = ContributionSoft
::get(FALSE)
4031 ->addWhere('contribution_id', '=', $contributionID)
4032 ->addWhere('pcp_id', '>', 0)
4034 ->execute()->first();
4035 if (!empty($contributionSoft)) {
4036 CRM_Contribute_BAO_ContributionSoft
::pcpNotifyOwner($contributionID, $contributionSoft);
4038 // @todo - check if Contribution::create does this, test, remove.
4039 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4040 $contributionParams['contribution_status_id'], $input['amount']);
4042 if (self
::isEmailReceipt($input, $contributionID, $recurringContributionID)) {
4043 civicrm_api3('Contribution', 'sendconfirmation', [
4044 'id' => $contributionID,
4045 'payment_processor_id' => $paymentProcessorId,
4047 \Civi
::log()->info("Contribution {$contributionParams['id']} Receipt sent");
4050 return $contributionResult;
4054 * Send receipt from contribution.
4056 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4058 * Note that the compose message part has been moved to contribution
4059 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4061 * @param array $input
4062 * Incoming data from Payment processor.
4064 * Related object IDs.
4065 * @param int $contributionID
4066 * @param bool $returnMessageText
4067 * Should text be returned instead of sent. This.
4068 * is because the function is also used to generate pdfs
4071 * @throws \CRM_Core_Exception
4072 * @throws \CiviCRM_API3_Exception
4073 * @throws \Exception
4075 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4077 $contribution = new CRM_Contribute_BAO_Contribution();
4078 $contribution->id
= $contributionID;
4079 if (!$contribution->find(TRUE)) {
4080 throw new CRM_Core_Exception('Contribution does not exist');
4082 // set receipt from e-mail and name in value
4083 if (!$returnMessageText) {
4084 [$values['receipt_from_name'], $values['receipt_from_email']] = self
::generateFromEmailAndName($input, $contribution);
4086 $values['contribution_status'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id
);
4087 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4088 if ((!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4089 civicrm_api3('Contribution', 'create', [
4090 'receipt_date' => 'now',
4091 'id' => $contribution->id
,
4098 * Generate From email and from name in an array values
4100 * @param array $input
4101 * @param \CRM_Contribute_BAO_Contribution $contribution
4105 public static function generateFromEmailAndName($input, $contribution) {
4106 // Use input value if supplied.
4107 if (!empty($input['receipt_from_email'])) {
4109 CRM_Utils_Array
::value('receipt_from_name', $input, ''),
4110 $input['receipt_from_email'],
4113 // if we are still empty see if we can use anything from a contribution page.
4115 if (!empty($contribution->contribution_page_id
)) {
4116 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id
]);
4118 // if we are still empty see if we can use anything from a contribution page.
4119 if (!empty($pageValues['receipt_from_email'])) {
4121 CRM_Utils_Array
::value('receipt_from_name', $pageValues),
4122 $pageValues['receipt_from_email'],
4125 // If we are still empty fall back to the domain or logged in user information.
4126 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4130 * Load related memberships.
4134 * @return array $ids
4139 * Note that in theory it should be possible to retrieve these from the line_item table
4140 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4141 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4142 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4143 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4145 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4148 public function loadRelatedMembershipObjects($ids = []) {
4150 SELECT membership_id
4151 FROM civicrm_membership_payment
4152 WHERE contribution_id = %1 ";
4153 $params = [1 => [$this->id
, 'Integer']];
4154 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, []);
4156 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4157 while ($dao->fetch()) {
4158 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4159 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4163 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4164 foreach ($ids['membership'] as $id) {
4166 $membership = new CRM_Member_BAO_Membership();
4167 $membership->id
= $id;
4168 if (!$membership->find(TRUE)) {
4169 throw new Exception("Could not find membership record: $id");
4171 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4172 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4173 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4174 $this->_relatedObjects
['membership'][$membership->id
. '_' . $membership->membership_type_id
] = $membership;
4183 * Function use to store line item proportionally in in entity financial trxn table
4185 * @param array $trxnParams
4187 * @param int $trxnId
4189 * @param float $contributionTotalAmount
4191 * @throws \CiviCRM_API3_Exception
4193 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4194 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4195 if (!empty($lineItems)) {
4196 // get financial item
4197 [$ftIds, $taxItems] = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4199 'contribution_total_amount' => $contributionTotalAmount,
4200 'trxn_total_amount' => $trxnParams['total_amount'],
4201 'trxn_id' => $trxnId,
4203 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4208 * ContributionPage values were being imposed onto values.
4210 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4211 * REALLY didn't want superimposed. The rest are left there in their overkill out
4214 * The rationale for making this explicit is that it was a case of carefully set values being
4215 * seemingly randonly overwritten without much care. In general I think array randomly setting
4216 * variables en mass is risky.
4218 * @param array $values
4222 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4223 $contributionPageValues = [];
4224 CRM_Contribute_BAO_ContributionPage
::setValues(
4225 $this->contribution_page_id
,
4226 $contributionPageValues
4229 // These are the values that I believe to be useful.
4232 'pay_later_receipt',
4234 'receipt_from_email',
4235 'receipt_from_name',
4239 'honoree_profile_id',
4240 'onbehalf_profile_id',
4241 'honor_block_is_active',
4242 // Kinda might be - but would be on the contribution...
4245 // Included for 'fear of regression' but can't justify any use for these....
4247 'payment_processor',
4248 'financial_type_id',
4249 'amount_block_is_active',
4254 'default_amount_id',
4258 'initial_amount_help_text',
4259 'initial_amount_label',
4261 'is_allow_other_amount',
4262 'is_billing_required',
4263 'is_confirm_enabled',
4264 'is_credit_card_only',
4266 'is_partial_payment',
4267 'is_recur_installments',
4268 'is_recur_interval',
4272 'min_initial_amount',
4273 'recur_frequency_unit',
4280 foreach ($valuesToCopy as $valueToCopy) {
4281 if (isset($contributionPageValues[$valueToCopy])) {
4282 if ($valueToCopy === 'title') {
4283 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils
::getContributionPageTitle($this->contribution_page_id
);
4286 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4294 * Get values of CiviContribute Settings
4295 * and check if its enabled or not.
4296 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4297 * in serialized form. Usually this should be stored as flat settings for each form fields
4298 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4299 * settings we will live with an inconsistency because it's too hard to change for now.
4300 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4303 * @param string $name
4308 public static function checkContributeSettings($name) {
4309 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
4310 return $contributeSettings[$name] ??
NULL;
4314 * Get the contribution as it is in the database before being updated.
4316 * @param int $contributionID
4318 * @return \CRM_Contribute_BAO_Contribution|null
4320 private static function getOriginalContribution($contributionID) {
4321 return self
::getValues(['id' => $contributionID]);
4325 * Does this transaction reflect a payment instrument change.
4327 * @param array $params
4328 * @param array $pendingStatuses
4332 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
4333 $contributionStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id
);
4335 if (array_key_exists('payment_instrument_id', $params)) {
4336 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
4337 !CRM_Utils_System
::isNull($params['payment_instrument_id'])
4339 //check if status is changed from Pending to Completed
4340 // do not update payment instrument changes for Pending to Completed
4341 if (!($contributionStatus == 'Completed' &&
4342 in_array($params['prevContribution']->contribution_status_id
, $pendingStatuses))
4347 elseif ((!CRM_Utils_System
::isNull($params['payment_instrument_id']) &&
4348 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
4349 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
4353 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
4354 $params['contribution']->check_number
!= $params['prevContribution']->check_number
4356 // another special case when check number is changed, create new financial records
4357 // create financial trxn with negative amount
4365 * Update the memberships associated with a contribution if it has been completed.
4367 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
4368 * load them in this function. Code clean up would compensate for any minor performance implication.
4370 * @param int $contributionID
4371 * @param string $changeDate
4373 * @throws \CRM_Core_Exception
4374 * @throws \CiviCRM_API3_Exception
4376 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
4377 $memberships = self
::getRelatedMemberships((int) $contributionID);
4378 foreach ($memberships as $membership) {
4379 $membershipParams = [
4380 'id' => $membership['id'],
4381 'contact_id' => $membership['contact_id'],
4382 'is_test' => $membership['is_test'],
4383 'membership_type_id' => $membership['membership_type_id'],
4384 'membership_activity_status' => 'Completed',
4387 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4388 $membershipParams['membership_type_id'],
4389 $membershipParams['is_test'],
4390 $membershipParams['id']
4393 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4394 // this picks up membership type changes during renewals
4395 // @todo this is almost certainly an obsolete sql call, the pre-change
4396 // membership is accessible via $this->_relatedObjects
4398 SELECT membership_type_id
4399 FROM civicrm_membership_log
4400 WHERE membership_id={$membershipParams['id']}
4403 $dao = CRM_Core_DAO
::executeQuery($sql);
4404 if ($dao->fetch()) {
4405 if (!empty($dao->membership_type_id
)) {
4406 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4409 if (empty($membership['end_date']) ||
(int) $membership['status_id'] !== CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
4410 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
4411 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
4412 // 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.
4413 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
4414 // @todo once apiv4 ships with core switch to that & find sanity.
4415 $membershipParams['num_terms'] = self
::getNumTermsByContributionAndMembershipType(
4416 $membershipParams['membership_type_id'],
4420 // @todo remove all this stuff in favour of letting the api call further down handle in
4421 // (it is a duplication of what the api does).
4422 $dates = array_fill_keys([
4427 if ($currentMembership) {
4429 * Fixed FOR CRM-4433
4430 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4431 * when Contribution mode is notify and membership is for renewal )
4433 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
4435 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4437 // @todo - we should pass membership_type_id instead of null here but not
4438 // adding as not sure of testing
4439 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4440 $changeDate, NULL, $membershipParams['num_terms']
4442 $dates['join_date'] = $currentMembership['join_date'];
4444 if ('Pending' === CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id'])) {
4445 $membershipParams['skipStatusCal'] = '';
4448 //get the status for membership.
4449 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4451 $dates['join_date'],
4454 $membershipParams['membership_type_id'],
4458 unset($dates['end_date']);
4459 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4461 //we might be renewing membership,
4462 //so make status override false.
4463 $membershipParams['is_override'] = FALSE;
4464 $membershipParams['status_override_end_date'] = 'null';
4465 civicrm_api3('Membership', 'create', $membershipParams);
4470 * Get payment links as they relate to a contribution.
4472 * If a payment can be made then include a payment link & if a refund is appropriate
4473 * then a refund link.
4476 * @param float $balance
4477 * @param string $contributionStatus
4480 * $actionLinks Links array containing:
4484 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
4485 if ($contributionStatus === 'Failed' ||
!CRM_Core_Permission
::check('edit contributions')) {
4486 // In general the balance is the best way to determine if a payment can be added or not,
4487 // but not for Failed contributions, where we don't accept additional payments at the moment.
4488 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
4489 // do accept more payments agains them.
4494 'url' => CRM_Utils_System
::url('civicrm/payment', [
4500 'title' => ts('Record Payment'),
4503 if (CRM_Core_Config
::isEnabledBackOfficeCreditCardPayments()) {
4505 'url' => CRM_Utils_System
::url('civicrm/payment', [
4512 'title' => ts('Submit Credit Card payment'),
4516 'url' => CRM_Utils_System
::url('civicrm/payment', [
4522 'title' => ts('Record Refund'),
4524 return $actionLinks;
4528 * Get a query to determine the amount donated by the contact/s in the current financial year.
4530 * @param array $contactIDs
4534 public static function getAnnualQuery($contactIDs) {
4535 $contactIDs = implode(',', $contactIDs);
4536 $config = CRM_Core_Config
::singleton();
4537 $currentMonth = date('m');
4538 $currentDay = date('d');
4540 (int) $config->fiscalYearStart
['M'] > $currentMonth ||
4542 (int) $config->fiscalYearStart
['M'] == $currentMonth &&
4543 (int) $config->fiscalYearStart
['d'] > $currentDay
4546 $year = date('Y') - 1;
4551 $nextYear = $year +
1;
4553 if ($config->fiscalYearStart
) {
4554 $newFiscalYearStart = $config->fiscalYearStart
;
4555 if ($newFiscalYearStart['M'] < 10) {
4556 // This is just a clumsy way of adding padding.
4557 // @todo next round look for a nicer way.
4558 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
4560 if ($newFiscalYearStart['d'] < 10) {
4561 // This is just a clumsy way of adding padding.
4562 // @todo next round look for a nicer way.
4563 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
4565 $config->fiscalYearStart
= $newFiscalYearStart;
4566 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
4569 // First of January.
4572 $startDate = "$year$monthDay";
4573 $endDate = "$nextYear$monthDay";
4576 'contact_id' => 'IN (' . $contactIDs . ')',
4577 'is_test' => ' = 0',
4578 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
4580 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4581 CRM_Financial_BAO_FinancialType
::addACLClausesToWhereClauses($whereClauses);
4584 foreach ($whereClauses as $key => $clause) {
4585 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
4587 $whereClauseString = implode(' AND ', $clauses);
4589 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
4590 // this group by + having on contribution_status_id improves performance
4592 SELECT COUNT(*) as count,
4593 SUM(total_amount) as amount,
4594 AVG(total_amount) as average,
4596 FROM civicrm_contribution b
4597 WHERE " . $whereClauseString . "
4598 GROUP BY currency, contribution_status_id
4599 HAVING $havingClause
4605 * Assign Test Value.
4607 * @param string $fieldName
4608 * @param array $fieldDef
4609 * @param int $counter
4611 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
4612 if ($fieldName === 'tax_amount') {
4613 $this->{$fieldName} = "0.00";
4615 elseif ($fieldName === 'net_amount') {
4616 $this->{$fieldName} = '2.00';
4618 elseif ($fieldName === 'total_amount') {
4619 $this->{$fieldName} = "3.00";
4621 elseif ($fieldName === 'fee_amount') {
4622 $this->{$fieldName} = '1.00';
4625 parent
::assignTestValues($fieldName, $fieldDef, $counter);
4630 * Check if contribution has participant/membership payment.
4632 * @param int $contributionId
4637 public static function allowUpdateRevenueRecognitionDate($contributionId) {
4638 // get line item for contribution
4639 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
4640 // check if line item is for membership or participant
4641 foreach ($lineItems as $items) {
4642 if ($items['entity_table'] == 'civicrm_participant') {
4646 elseif ($items['entity_table'] == 'civicrm_membership') {
4658 * Create Accounts Receivable financial trxn entry for Completed Contribution.
4660 * @param array $trxnParams
4661 * Financial trxn params
4662 * @param array $contributionParams
4663 * Contribution Params
4667 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
4668 if (!Civi
::settings()->get('always_post_to_accounts_receivable')) {
4671 $statusId = $contributionParams['contribution']->contribution_status_id
;
4672 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4673 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
4674 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
4675 // Return if contribution status is not completed.
4676 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
4677 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
4678 && $contributionParams['prevContribution']->is_pay_later
== 0
4684 $params = $trxnParams;
4685 $financialTypeID = !empty($contributionParams['financial_type_id']) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
4686 $arAccountId = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
4687 $params['to_financial_account_id'] = $arAccountId;
4688 $params['status_id'] = array_search('Pending', $contributionStatuses);
4689 $params['is_payment'] = FALSE;
4690 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
4691 self
::$_trxnIDs[] = $trxn->id
;
4692 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
4696 * Calculate financial item amount when contribution is updated.
4698 * @param array $params
4699 * contribution params
4700 * @param array $amountParams
4702 * @param string $context
4706 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
4707 if (!empty($params['is_quick_config'])) {
4708 $amount = $amountParams['item_amount'];
4710 $amount = $params['total_amount'];
4711 if ($context === NULL) {
4712 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
4717 $amount = $amountParams['line_total'];
4718 if ($context == 'changedAmount') {
4719 $amount -= $amountParams['previous_line_total'];
4721 $amount *= $amountParams['diff'];
4727 * Retrieve Sales Tax Financial Accounts.
4733 public static function getSalesTaxFinancialAccounts() {
4734 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
4735 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
4736 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
4737 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4738 $queryParams = [1 => [$accountRel, 'Integer']];
4739 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
4740 $financialAccount = [];
4741 while ($dao->fetch()) {
4742 $financialAccount[(int) $dao->id
] = (int) $dao->id
;
4744 return $financialAccount;
4748 * Create tax entry in civicrm_entity_financial_trxn table.
4750 * @param array $entityParams
4752 * @param array $eftParams
4754 * @throws \CiviCRM_API3_Exception
4756 public static function createProportionalEntry($entityParams, $eftParams) {
4758 if ($entityParams['contribution_total_amount'] != 0) {
4759 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
4761 // Record Entity Financial Trxn; CRM-20145
4762 $eftParams['amount'] = $paid;
4763 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4767 * Create array of last financial item id's.
4769 * @param int $contributionId
4773 public static function getLastFinancialItemIds($contributionId) {
4774 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
4775 FROM civicrm_financial_item fi
4776 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4777 WHERE li.contribution_id = %1";
4778 $dao = CRM_Core_DAO
::executeQuery($sql, [
4784 $ftIds = $taxItems = [];
4785 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
4786 while ($dao->fetch()) {
4787 /* if sales tax item*/
4788 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
4789 $taxItems[$dao->price_field_value_id
] = [
4790 'financial_item_id' => $dao->id
,
4791 'amount' => $dao->tax_amount
,
4795 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4798 return [$ftIds, $taxItems];
4802 * Create proportional entries in civicrm_entity_financial_trxn.
4804 * @param array $entityParams
4806 * @param array $lineItems
4808 * @param array $ftIds
4810 * @param array $taxItems
4812 * @throws \CiviCRM_API3_Exception
4814 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
4816 'entity_table' => 'civicrm_financial_item',
4817 'financial_trxn_id' => $entityParams['trxn_id'],
4819 foreach ($lineItems as $key => $value) {
4820 if ($value['qty'] == 0) {
4823 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4824 $entityParams['line_item_amount'] = $value['line_total'];
4825 self
::createProportionalEntry($entityParams, $eftParams);
4826 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
4827 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
4828 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
4829 self
::createProportionalEntry($entityParams, $eftParams);
4835 * Load entities related to the contribution into $this->_relatedObjects.
4839 * @throws \CRM_Core_Exception
4841 protected function loadRelatedEntitiesByID($ids) {
4843 'contact' => 'CRM_Contact_BAO_Contact',
4844 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
4845 'contributionType' => 'CRM_Financial_BAO_FinancialType',
4846 'financialType' => 'CRM_Financial_BAO_FinancialType',
4847 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
4849 foreach ($entities as $entity => $bao) {
4850 if (!empty($ids[$entity])) {
4851 $this->_relatedObjects
[$entity] = new $bao();
4852 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
4853 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
4854 throw new CRM_Core_Exception($entity . ' could not be loaded');
4861 * Function to replace contribution tokens.
4863 * @param array $contributionIds
4865 * @param string $subject
4867 * @param array $subjectToken
4869 * @param string $text
4871 * @param string $html
4873 * @param array $messageToken
4875 * @param bool $escapeSmarty
4878 * @throws \CiviCRM_API3_Exception
4880 public static function replaceContributionTokens(
4889 if (empty($contributionIds)) {
4892 $contributionDetails = [];
4893 foreach ($contributionIds as $id) {
4894 $result = self
::getContributionTokenValues($id, $messageToken);
4895 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token
::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
4896 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token
::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
4897 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token
::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
4899 return $contributionDetails;
4903 * Get the contribution fields for $id and display labels where
4904 * appropriate (if the token is present).
4907 * @param array $messageToken
4910 * @throws \CRM_Core_Exception
4912 public static function getContributionTokenValues($id, $messageToken) {
4916 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
4917 if (!empty($messageToken['contribution'])) {
4918 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
4919 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
4920 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
4921 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField
::displayValue($result['values'][$id][$fieldName], $fieldName);
4924 $processor = new CRM_Contribute_Tokens();
4925 $pseudoFields = array_keys($processor->getPseudoTokens());
4926 foreach ($pseudoFields as $pseudoField) {
4927 $split = explode(':', $pseudoField);
4928 $result['values'][$id][$pseudoField] = $processor->getPseudoValue($split[0], $split[1], $result['values'][$id][$split[0]] ??
'');
4935 * Get invoice_number for contribution.
4937 * @param int $contributionID
4939 * @return string|null
4941 public static function getInvoiceNumber(int $contributionID): ?
string {
4942 $invoicePrefix = Civi
::settings()->get('invoice_prefix');
4943 return $invoicePrefix ?
$invoicePrefix . $contributionID : NULL;
4947 * Load the values needed for the event message.
4949 * @param int $eventID
4950 * @param int $participantID
4951 * @param int|null $contributionID
4954 * @throws \CRM_Core_Exception
4956 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
4961 $values = ['event' => []];
4963 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
4964 // add custom fields for event
4965 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', NULL, $eventID);
4967 $eventCustomGroup = [];
4968 foreach ($eventGroupTree as $key => $group) {
4969 if ($key === 'info') {
4973 foreach ($group['fields'] as $k => $customField) {
4974 $groupLabel = $group['title'];
4975 if (!empty($customField['customValue'])) {
4976 foreach ($customField['customValue'] as $customFieldValues) {
4977 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
4982 $values['event']['customGroup'] = $eventCustomGroup;
4984 //get participant details
4985 $participantParams = [
4986 'id' => $participantID,
4989 $values['participant'] = [];
4991 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
4992 // add custom fields for event
4993 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', NULL, $participantID);
4994 $participantCustomGroup = [];
4995 foreach ($participantGroupTree as $key => $group) {
4996 if ($key === 'info') {
5000 foreach ($group['fields'] as $k => $customField) {
5001 $groupLabel = $group['title'];
5002 if (!empty($customField['customValue'])) {
5003 foreach ($customField['customValue'] as $customFieldValues) {
5004 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ??
NULL;
5009 $values['participant']['customGroup'] = $participantCustomGroup;
5011 //get location details
5013 'entity_id' => $eventID,
5014 'entity_table' => 'civicrm_event',
5016 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
5019 'entity_table' => 'civicrm_event',
5020 'entity_id' => $eventID,
5021 'module' => 'CiviEvent',
5024 [$custom_pre_id, $custom_post_ids] = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
5026 $values['custom_pre_id'] = $custom_pre_id;
5027 $values['custom_post_id'] = $custom_post_ids;
5029 // set lineItem for event contribution
5030 if ($contributionID) {
5031 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($contributionID);
5032 if (!empty($participantIds)) {
5033 foreach ($participantIds as $pIDs) {
5034 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
5035 if (!CRM_Utils_System
::isNull($lineItem)) {
5036 $values['lineItem'][] = $lineItem;
5045 * Get the activity source and target contacts linked to a contribution
5047 * @param $activityId
5051 private static function getActivitySourceAndTarget($activityId): array {
5052 $activityContactQuery = ActivityContact
::get(FALSE)->setWhere([
5053 ['activity_id', '=', $activityId],
5054 ['record_type_id:name', 'IN', ['Activity Source', 'Activity Targets']],
5057 $sourceContactKey = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
5058 $targetContactKey = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Targets');
5060 $sourceContactId = NULL;
5061 $targetContactId = NULL;
5063 for ($i = 0; $i < $activityContactQuery->count(); $i++
) {
5064 $record = $activityContactQuery->itemAt($i);
5066 if ($record['record_type_id'] === $sourceContactKey) {
5067 $sourceContactId = $record['contact_id'];
5070 if ($record['record_type_id'] === $targetContactKey) {
5071 $targetContactId = $record['contact_id'];
5075 return [$sourceContactId, $targetContactId];