3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Static field to hold financial trxn id's.
54 static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
58 * @var array of objects (e.g membership object, participant object)
60 public $_relatedObjects = array();
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
68 * @var string component or event
70 public $_component = NULL;
73 * Possibly obsolete variable.
75 * If you use it please explain why it is set in the create function here.
79 public $trxn_result_code;
84 public function __construct() {
85 parent
::__construct();
89 * Takes an associative array and creates a contribution object.
91 * the function extract all the params it needs to initialize the create a
92 * contribution object. the params array could contain additional unused name/value
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
98 * The array that holds all the db ids.
100 * @return CRM_Contribute_BAO_Contribution|void
102 public static function add(&$params, $ids = array()) {
103 if (empty($params)) {
106 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
107 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
108 $duplicates = array();
109 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
110 $error = CRM_Core_Error
::singleton();
111 $d = implode(', ', $duplicates);
112 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
115 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
120 // first clean up all the money fields
121 $moneyFields = array(
125 'non_deductible_amount',
128 //if priceset is used, no need to cleanup money
129 if (!empty($params['skipCleanMoney'])) {
130 unset($moneyFields[0]);
133 foreach ($moneyFields as $field) {
134 if (isset($params[$field])) {
135 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
139 //set defaults in create mode
140 if (!$contributionID) {
141 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
144 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
145 //if contribution is created with cancelled or refunded status, add credit note id
146 if (!empty($params['contribution_status_id'])) {
147 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
148 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
149 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
151 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
152 $params['creditnote_id'] = self
::createCreditNoteId();
157 // Since the fee amount is expecting this (later on) ensure it is always set.
158 // It would only not be set for an update where it is unchanged.
159 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
163 && CRM_Utils_Array
::value('membership_id', $params)
164 && self
::checkContributeSettings('deferred_revenue_enabled')
166 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
167 if ($memberStartDate) {
168 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
171 self
::calculateMissingAmountParams($params, $contributionID);
173 if (!empty($params['payment_instrument_id'])) {
174 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
175 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
176 $params['check_number'] = 'null';
180 $setPrevContribution = TRUE;
181 // CRM-13964 partial payment
182 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
183 $partialAmtTotal = $params['partial_payment_total'];
184 $partialAmtPay = $params['partial_amount_pay'];
185 $params['total_amount'] = $partialAmtTotal;
186 if ($partialAmtPay < $partialAmtTotal) {
187 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
188 $params['is_pay_later'] = 0;
189 $setPrevContribution = FALSE;
192 if ($contributionID && $setPrevContribution) {
193 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
197 CRM_Financial_BAO_FinancialAccount
::checkFinancialTypeHasDeferred($params, $contributionID);
198 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
199 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
200 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
202 unset($params['revenue_recognition_date']);
205 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
206 isset($params['financial_type_id']))) {
207 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
210 if ($contributionID) {
211 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
214 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
216 $contribution = new CRM_Contribute_BAO_Contribution();
217 $contribution->copyValues($params);
219 $contribution->id
= $contributionID;
221 if (empty($contribution->id
)) {
222 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
223 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
224 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
228 $result = $contribution->save();
230 // Add financial_trxn details as part of fix for CRM-4724
231 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
232 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
234 //add Account details
235 $params['contribution'] = $contribution;
236 self
::recordFinancialAccounts($params);
238 if (self
::isUpdateToRecurringContribution($params)) {
239 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
240 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
241 $contributionStatus[$params['contribution_status_id']]
245 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
247 if ($contributionID) {
248 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
251 CRM_Utils_Hook
::post('create', '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.
288 public static function getDefaults() {
290 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
291 FALSE, FALSE, FALSE, 'AND is_default = 1')
293 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
298 * Fetch the object and store the values in the values array.
300 * @param array $params
301 * Input parameters to find object.
302 * @param array $values
303 * Output values of the object.
305 * The array that holds all the db ids.
307 * @return CRM_Contribute_BAO_Contribution|null
308 * The found object or null
310 public static function getValues($params, &$values, &$ids) {
311 if (empty($params)) {
314 $contribution = new CRM_Contribute_BAO_Contribution();
316 $contribution->copyValues($params);
318 if ($contribution->find(TRUE)) {
319 $ids['contribution'] = $contribution->id
;
321 CRM_Core_DAO
::storeValues($contribution, $values);
323 return $contribution;
325 $null = NULL; // return by reference
330 * Get the values and resolve the most common mappings.
332 * Since contribution status is resolved in almost every function that calls getValues it makes
333 * sense to have an extra function to resolve it rather than repeat the code.
335 * Think carefully before adding more mappings to be resolved as there could be performance implications
336 * if this function starts to be called from more iterative functions.
338 * @param array $params
339 * Input parameters to find object.
342 * Array of the found contribution.
343 * @throws CRM_Core_Exception
345 public static function getValuesWithMappings($params) {
346 $values = $ids = array();
347 $contribution = self
::getValues($params, $values, $ids);
348 if (is_null($contribution)) {
349 throw new CRM_Core_Exception('No contribution found');
351 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
356 * Calculate net_amount & fee_amount if they are not set.
358 * Net amount should be total - fee.
359 * This should only be called for new contributions.
361 * @param array $params
362 * Params for a new contribution before they are saved.
363 * @param int|null $contributionID
364 * Contribution ID if we are dealing with an update.
366 * @throws \CiviCRM_API3_Exception
368 public static function calculateMissingAmountParams(&$params, $contributionID) {
369 if (!$contributionID && !isset($params['fee_amount'])) {
370 if (isset($params['total_amount']) && isset($params['net_amount'])) {
371 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
374 $params['fee_amount'] = 0;
377 if (!isset($params['net_amount'])) {
378 if (!$contributionID) {
379 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
382 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
383 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
384 // net_amount may need adjusting.
385 $contribution = civicrm_api3('Contribution', 'getsingle', array(
386 'id' => $contributionID,
387 'return' => array('total_amount', 'net_amount'),
389 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
390 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
391 $params['net_amount'] = $totalAmount - $feeAmount;
399 * @param $billingLocationTypeID
403 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
404 $hasBillingField = FALSE;
405 $billingFields = array(
413 //build address array
414 $addressParams = array();
415 $addressParams['location_type_id'] = $billingLocationTypeID;
416 $addressParams['is_billing'] = 1;
418 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
419 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
420 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
421 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
423 foreach ($billingFields as $value) {
424 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
425 if (!empty($addressParams[$value])) {
426 $hasBillingField = TRUE;
429 return array($hasBillingField, $addressParams);
433 * Get address params ready to be passed to the payment processor.
435 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
436 * To create an address we need state_province_id.
438 * @param array $params
439 * @param int $billingLocationTypeID
443 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
444 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
445 foreach ($addressParams as $name => $field) {
446 if (substr($name, 0, 8) == 'billing_') {
447 $addressParams[substr($name, 9)] = $addressParams[$field];
450 return array($hasBillingField, $addressParams);
454 * Get the number of terms for this contribution for a given membership type
455 * based on querying the line item table and relevant price field values
456 * Note that any one contribution should only be able to have one line item relating to a particular membership
459 * @param int $membershipTypeID
461 * @param int $contributionID
465 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
466 $numTerms = CRM_Core_DAO
::singleValueQuery("
467 SELECT membership_num_terms FROM civicrm_line_item li
468 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
469 WHERE contribution_id = %1 AND membership_type_id = %2",
470 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
472 // default of 1 is precautionary
473 return empty($numTerms) ?
1 : $numTerms;
477 * Takes an associative array and creates a contribution object.
479 * @param array $params
480 * (reference ) an assoc array of name/value pairs.
482 * The array that holds all the db ids.
484 * @return CRM_Contribute_BAO_Contribution
486 public static function create(&$params, $ids = array()) {
487 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
488 foreach ($dateFields as $df) {
489 if (isset($params[$df])) {
490 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
494 //if contribution is created with cancelled or refunded status, add credit note id
495 if (!empty($params['contribution_status_id'])) {
496 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
498 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
499 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
501 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
502 $params['creditnote_id'] = self
::createCreditNoteId();
507 $transaction = new CRM_Core_Transaction();
509 $contribution = self
::add($params, $ids);
511 if (is_a($contribution, 'CRM_Core_Error')) {
512 $transaction->rollback();
513 return $contribution;
516 $params['contribution_id'] = $contribution->id
;
518 if (!empty($params['custom']) &&
519 is_array($params['custom'])
521 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
524 $session = CRM_Core_Session
::singleton();
526 if (!empty($params['note'])) {
528 'entity_table' => 'civicrm_contribution',
529 'note' => $params['note'],
530 'entity_id' => $contribution->id
,
531 'contact_id' => $session->get('userID'),
532 'modified_date' => date('Ymd'),
534 if (!$noteParams['contact_id']) {
535 $noteParams['contact_id'] = $params['contact_id'];
537 CRM_Core_BAO_Note
::add($noteParams);
540 // make entry in batch entity batch table
541 if (!empty($params['batch_id'])) {
542 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
543 $titleFields = array(
549 $retrieveRequired = 0;
550 foreach ($titleFields as $titleField) {
551 if (!isset($contribution->$titleField)) {
552 $retrieveRequired = 1;
556 if ($retrieveRequired == 1) {
557 $contribution->find(TRUE);
561 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
563 $transaction->commit();
565 // check if activity record exist for this contribution, if
567 $activity = new CRM_Activity_DAO_Activity();
568 $activity->source_record_id
= $contribution->id
;
569 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
574 //CRM-18406: Update activity when edit contribution.
575 if ($activity->find(TRUE)) {
576 // CRM-13237 : if activity record found, update it with campaign id of contribution
577 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
578 $contribution->activity_id
= $activity->id
;
580 if (empty($contribution->contact_id
)) {
581 $contribution->find(TRUE);
583 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
585 // do not add to recent items for import, CRM-4399
586 if (empty($params['skipRecentView'])) {
587 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
588 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
590 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
591 $titleFields = array(
597 $retrieveRequired = 0;
598 foreach ($titleFields as $titleField) {
599 if (!isset($contribution->$titleField)) {
600 $retrieveRequired = 1;
604 if ($retrieveRequired == 1) {
605 $contribution->find(TRUE);
607 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
608 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
610 $recentOther = array();
611 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
612 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
613 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
617 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
618 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
619 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
623 // add the recently created Contribution
624 CRM_Utils_Recent
::add($title,
628 $contribution->contact_id
,
634 return $contribution;
638 * Get the values for pseudoconstants for name->value and reverse.
640 * @param array $defaults
641 * (reference) the default values, some of which need to be resolved.
642 * @param bool $reverse
643 * True if we want to resolve the values in the reverse direction (value -> name).
645 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
646 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
647 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
648 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
649 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
653 * Convert associative array names to values and vice-versa.
655 * This function is used by both the web form layer and the api. Note that
656 * the api needs the name => value conversion, also the view layer typically
657 * requires value => name conversion
659 * @param array $defaults
660 * @param string $property
661 * @param array $lookup
662 * @param bool $reverse
666 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
667 $id = $property . '_id';
669 $src = $reverse ?
$property : $id;
670 $dst = $reverse ?
$id : $property;
672 if (!array_key_exists($src, $defaults)) {
676 $look = $reverse ?
array_flip($lookup) : $lookup;
678 if (is_array($look)) {
679 if (!array_key_exists($defaults[$src], $look)) {
683 $defaults[$dst] = $look[$defaults[$src]];
688 * Retrieve DB object based on input parameters.
690 * It also stores all the retrieved values in the default array.
692 * @param array $params
693 * (reference ) an assoc array of name/value pairs.
694 * @param array $defaults
695 * (reference ) an assoc array to hold the name / value pairs.
696 * in a hierarchical manner
698 * (reference) the array that holds all the db ids.
700 * @return CRM_Contribute_BAO_Contribution
702 public static function retrieve(&$params, &$defaults, &$ids) {
703 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
704 return $contribution;
708 * Combine all the importable fields from the lower levels object.
710 * The ordering is important, since currently we do not have a weight
711 * scheme. Adding weight is super important and should be done in the
712 * next week or so, before this can be called complete.
714 * @param string $contactType
715 * @param bool $status
718 * array of importable Fields
720 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
721 if (!self
::$_importableFields) {
722 if (!self
::$_importableFields) {
723 self
::$_importableFields = array();
727 $fields = array('' => array('title' => ts('- do not import -')));
730 $fields = array('' => array('title' => ts('- Contribution Fields -')));
733 $note = CRM_Core_DAO_Note
::import();
734 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
735 unset($tmpFields['option_value']);
736 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
737 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
739 // Using new Dedupe rule.
741 'contact_type' => $contactType,
742 'used' => 'Unsupervised',
744 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
745 $tmpContactField = array();
746 if (is_array($fieldsArray)) {
747 foreach ($fieldsArray as $value) {
748 //skip if there is no dupe rule
749 if ($value == 'none') {
752 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
757 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
758 $tmpContactField[trim($value)] = $contactFields[trim($value)];
760 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
763 $title = $tmpContactField[trim($value)]['title'];
765 $tmpContactField[trim($value)]['title'] = $title;
769 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
770 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
771 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
772 $fields = array_merge($fields, $tmpContactField);
773 $fields = array_merge($fields, $tmpFields);
774 $fields = array_merge($fields, $note);
775 $fields = array_merge($fields, $optionFields);
776 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
777 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
778 self
::$_importableFields = $fields;
780 return self
::$_importableFields;
784 * Combine all the exportable fields from the lower level objects.
786 * @param bool $checkPermission
789 * array of exportable Fields
791 public static function &exportableFields($checkPermission = TRUE) {
792 if (!self
::$_exportableFields) {
793 if (!self
::$_exportableFields) {
794 self
::$_exportableFields = array();
797 $impFields = CRM_Contribute_DAO_Contribution
::export();
798 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
799 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
800 $typeField = CRM_Financial_DAO_FinancialType
::export();
801 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
802 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
803 $contributionStatus = array(
804 'contribution_status' => array(
805 'title' => ts('Contribution Status'),
806 'name' => 'contribution_status',
807 'data_type' => CRM_Utils_Type
::T_STRING
,
811 $contributionPage = array(
812 'contribution_page' => array(
813 'title' => ts('Contribution Page'),
814 'name' => 'contribution_page',
815 'where' => 'civicrm_contribution_page.title',
816 'data_type' => CRM_Utils_Type
::T_STRING
,
820 $contributionNote = array(
821 'contribution_note' => array(
822 'title' => ts('Contribution Note'),
823 'name' => 'contribution_note',
824 'data_type' => CRM_Utils_Type
::T_TEXT
,
828 $extraFields = array(
829 'contribution_batch' => array(
830 'title' => ts('Batch Name'),
835 $campaignTitle = array(
836 'contribution_campaign_title' => array(
837 'title' => ts('Campaign Title'),
838 'name' => 'campaign_title',
839 'where' => 'civicrm_campaign.title',
840 'data_type' => CRM_Utils_Type
::T_STRING
,
843 $softCreditFields = array(
844 'contribution_soft_credit_name' => array(
845 'name' => 'contribution_soft_credit_name',
846 'title' => 'Soft Credit For',
847 'where' => 'civicrm_contact_d.display_name',
848 'data_type' => CRM_Utils_Type
::T_STRING
,
850 'contribution_soft_credit_amount' => array(
851 'name' => 'contribution_soft_credit_amount',
852 'title' => 'Soft Credit Amount',
853 'where' => 'civicrm_contribution_soft.amount',
854 'data_type' => CRM_Utils_Type
::T_MONEY
,
856 'contribution_soft_credit_type' => array(
857 'name' => 'contribution_soft_credit_type',
858 'title' => 'Soft Credit Type',
859 'where' => 'contribution_softcredit_type.label',
860 'data_type' => CRM_Utils_Type
::T_STRING
,
862 'contribution_soft_credit_contribution_id' => array(
863 'name' => 'contribution_soft_credit_contribution_id',
864 'title' => 'Soft Credit For Contribution ID',
865 'where' => 'civicrm_contribution_soft.contribution_id',
866 'data_type' => CRM_Utils_Type
::T_INT
,
868 'contribution_soft_credit_contact_id' => array(
869 'name' => 'contribution_soft_credit_contact_id',
870 'title' => 'Soft Credit For Contact ID',
871 'where' => 'civicrm_contact_d.id',
872 'data_type' => CRM_Utils_Type
::T_INT
,
876 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
878 'contribution_product_id' => array(
879 'title' => ts('Premium'),
880 'name' => 'contribution_product_id',
881 'where' => 'civicrm_product.id',
882 'data_type' => CRM_Utils_Type
::T_INT
,
886 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
887 $expFieldsContrib, $contributionNote, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
888 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
891 self
::$_exportableFields = $fields;
894 return self
::$_exportableFields;
898 * @param null $status
899 * @param null $startDate
900 * @param null $endDate
904 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
908 $where[] = 'contribution_status_id = 1';
912 $where[] = 'contribution_status_id = 3';
917 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
920 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
922 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
923 if ($financialTypes) {
924 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
925 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
928 $where[] = "c.financial_type_id IN (0)";
931 $whereCond = implode(' AND ', $where);
934 SELECT sum( total_amount ) as total_amount,
935 count( c.id ) as total_count,
937 FROM civicrm_contribution c
938 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
939 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
941 AND ( is_test = 0 OR is_test IS NULL )
942 AND contact.is_deleted = 0
946 $dao = CRM_Core_DAO
::executeQuery($query);
949 while ($dao->fetch()) {
950 $count +
= $dao->total_count
;
951 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
955 'amount' => implode(', ', $amount),
963 * Delete the indirect records associated with this contribution first.
968 * $results no of deleted Contribution on success, false otherwise
970 public static function deleteContribution($id) {
971 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
973 $transaction = new CRM_Core_Transaction();
976 //delete activity record
978 'source_record_id' => $id,
979 // activity type id for contribution
980 'activity_type_id' => 6,
983 CRM_Activity_BAO_Activity
::deleteActivity($params);
985 //delete billing address if exists for this contribution.
986 self
::deleteAddress($id);
988 //update pledge and pledge payment, CRM-3961
989 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
991 // remove entry from civicrm_price_set_entity, CRM-5095
992 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
993 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
995 // cleanup line items.
996 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
998 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
999 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1001 if ($participantId) {
1002 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1005 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1009 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1010 $noteId = key($note);
1012 CRM_Core_BAO_Note
::del($noteId, FALSE);
1015 $dao = new CRM_Contribute_DAO_Contribution();
1018 $results = $dao->delete();
1020 $transaction->commit();
1022 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1024 // delete the recently created Contribution
1025 $contributionRecent = array(
1027 'type' => 'Contribution',
1029 CRM_Utils_Recent
::del($contributionRecent);
1035 * React to a financial transaction (payment) failure.
1037 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1038 * payments is important for forensic and outreach reasons.
1040 * @param int $contributionID
1041 * @param int $contactID
1042 * @param string $message
1044 * @throws \CiviCRM_API3_Exception
1046 public static function failPayment($contributionID, $contactID, $message) {
1047 civicrm_api3('activity', 'create', array(
1048 'activity_type_id' => 'Failed Payment',
1049 'details' => $message,
1050 'subject' => ts('Payment failed at payment processor'),
1051 'source_record_id' => $contributionID,
1052 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1058 * Check if there is a contribution with the same trxn_id or invoice_id.
1060 * @param array $input
1061 * An assoc array of name/value pairs.
1062 * @param array $duplicates
1063 * (reference) store ids of duplicate contribs.
1067 * true if duplicate, false otherwise
1069 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1071 $id = CRM_Utils_Array
::value('id', $input);
1073 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1074 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1080 $clause[] = "trxn_id = %1";
1081 $input[1] = array($trxn_id, 'String');
1085 $clause[] = "invoice_id = %2";
1086 $input[2] = array($invoice_id, 'String');
1089 if (empty($clause)) {
1093 $clause = implode(' OR ', $clause);
1095 $clause = "( $clause ) AND id != %3";
1096 $input[3] = array($id, 'Integer');
1099 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1100 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1102 while ($dao->fetch()) {
1103 $duplicates[] = $dao->id
;
1110 * Takes an associative array and creates a contribution_product object.
1112 * the function extract all the params it needs to initialize the create a
1113 * contribution_product object. the params array could contain additional unused name/value
1116 * @param array $params
1117 * (reference) an assoc array of name/value pairs.
1119 * @return CRM_Contribute_DAO_ContributionProduct
1121 public static function addPremium(&$params) {
1122 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1123 $contributionProduct->copyValues($params);
1124 return $contributionProduct->save();
1128 * Get list of contribution fields for profile.
1129 * For now we only allow custom contribution fields to be in
1132 * @param bool $addExtraFields
1133 * True if special fields needs to be added.
1136 * the list of contribution fields
1138 public static function getContributionFields($addExtraFields = TRUE) {
1139 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1140 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1142 if ($addExtraFields) {
1143 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1146 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1148 foreach ($contributionFields as $key => $var) {
1149 if ($key == 'contribution_contact_id') {
1152 elseif ($key == 'contribution_campaign_id') {
1153 $var['title'] = ts('Campaign');
1155 $fields[$key] = $var;
1158 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1163 * Add extra fields specific to contribution.
1165 public static function getSpecialContributionFields() {
1166 $extraFields = array(
1167 'contribution_soft_credit_name' => array(
1168 'name' => 'contribution_soft_credit_name',
1169 'title' => 'Soft Credit Name',
1170 'headerPattern' => '/^soft_credit_name$/i',
1171 'where' => 'civicrm_contact_d.display_name',
1173 'contribution_soft_credit_email' => array(
1174 'name' => 'contribution_soft_credit_email',
1175 'title' => 'Soft Credit Email',
1176 'headerPattern' => '/^soft_credit_email$/i',
1177 'where' => 'soft_email.email',
1179 'contribution_soft_credit_phone' => array(
1180 'name' => 'contribution_soft_credit_phone',
1181 'title' => 'Soft Credit Phone',
1182 'headerPattern' => '/^soft_credit_phone$/i',
1183 'where' => 'soft_phone.phone',
1185 'contribution_soft_credit_contact_id' => array(
1186 'name' => 'contribution_soft_credit_contact_id',
1187 'title' => 'Soft Credit Contact ID',
1188 'headerPattern' => '/^soft_credit_contact_id$/i',
1189 'where' => 'civicrm_contribution_soft.contact_id',
1191 'contribution_pcp_title' => array(
1192 'name' => 'contribution_pcp_title',
1193 'title' => 'Personal Campaign Page Title',
1194 'headerPattern' => '/^contribution_pcp_title$/i',
1195 'where' => 'contribution_pcp.title',
1199 return $extraFields;
1203 * @param int $pageID
1207 public static function getCurrentandGoalAmount($pageID) {
1209 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1210 FROM civicrm_contribution_page p,
1211 civicrm_contribution c
1212 WHERE p.id = c.contribution_page_id
1214 AND c.cancel_date is null
1218 $config = CRM_Core_Config
::singleton();
1219 $params = array(1 => array($pageID, 'Integer'));
1220 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1222 if ($dao->fetch()) {
1223 return array($dao->goal
, $dao->total
);
1226 return array(NULL, NULL);
1231 * Get list of contributions which credit the passed in contact ID.
1233 * The returned array provides details about the original contribution & donor.
1235 * @todo - this is a confusing function called from one place. It has a test. It would be
1236 * nice to deprecate it.
1238 * @param int $honorId
1239 * In Honor of Contact ID.
1242 * list of contribution fields
1244 public static function getHonorContacts($honorId) {
1246 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1247 $honorDAO->contact_id
= $honorId;
1250 $type = CRM_Contribute_PseudoConstant
::financialType();
1252 while ($honorDAO->fetch()) {
1253 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1254 $contributionDAO->id
= $honorDAO->contribution_id
;
1256 if ($contributionDAO->find(TRUE)) {
1257 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1258 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1259 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1260 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1261 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1262 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1263 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1264 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1265 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1273 * Get the sort name of a contact for a particular contribution.
1276 * Id of the contribution.
1278 * @return null|string
1279 * sort name of the contact if found
1281 public static function sortName($id) {
1282 $id = CRM_Utils_Type
::escape($id, 'Integer');
1285 SELECT civicrm_contact.sort_name
1286 FROM civicrm_contribution, civicrm_contact
1287 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1288 AND civicrm_contribution.id = {$id}
1290 return CRM_Core_DAO
::singleValueQuery($query);
1294 * @param int $contactID
1298 public static function annual($contactID) {
1299 if (is_array($contactID)) {
1300 $contactIDs = implode(',', $contactID);
1303 $contactIDs = $contactID;
1306 $config = CRM_Core_Config
::singleton();
1307 $startDate = $endDate = NULL;
1309 $currentMonth = date('m');
1310 $currentDay = date('d');
1311 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1312 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1313 (int ) $config->fiscalYearStart
['d'] > $currentDay
1316 $year = date('Y') - 1;
1321 $nextYear = $year +
1;
1323 if ($config->fiscalYearStart
) {
1324 $newFiscalYearStart = $config->fiscalYearStart
;
1325 if ($newFiscalYearStart['M'] < 10) {
1326 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1328 if ($newFiscalYearStart['d'] < 10) {
1329 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1331 $config->fiscalYearStart
= $newFiscalYearStart;
1332 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1337 $startDate = "$year$monthDay";
1338 $endDate = "$nextYear$monthDay";
1339 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1340 $additionalWhere = " AND b.financial_type_id IN (0)";
1341 $liWhere = " AND i.financial_type_id IN (0)";
1342 if (!empty($financialTypes)) {
1343 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1344 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1347 SELECT count(*) as count,
1348 sum(total_amount) as amount,
1349 avg(total_amount) as average,
1351 FROM civicrm_contribution b
1352 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1353 WHERE b.contact_id IN ( $contactIDs )
1354 AND b.contribution_status_id = 1
1356 AND b.receive_date >= $startDate
1357 AND b.receive_date < $endDate
1361 $dao = CRM_Core_DAO
::executeQuery($query);
1363 $amount = $average = array();
1364 while ($dao->fetch()) {
1365 if ($dao->count
> 0 && $dao->amount
> 0) {
1366 $count +
= $dao->count
;
1367 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1368 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1374 implode(', ', $amount),
1375 implode(', ', $average),
1378 return array(0, 0, 0);
1382 * Check if there is a contribution with the params passed in.
1384 * Used for trxn_id,invoice_id and contribution_id
1386 * @param array $params
1387 * An assoc array of name/value pairs.
1390 * contribution id if success else NULL
1392 public static function checkDuplicateIds($params) {
1393 $dao = new CRM_Contribute_DAO_Contribution();
1397 foreach ($params as $k => $v) {
1399 $clause[] = "$k = '$v'";
1402 $clause = implode(' AND ', $clause);
1403 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1404 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1406 while ($dao->fetch()) {
1414 * Get the contribution details for component export.
1416 * @param int $exportMode
1418 * @param string $componentIds
1424 public static function getContributionDetails($exportMode, $componentIds) {
1425 $paymentDetails = array();
1426 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1428 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1429 $componentSelect = " civicrm_participant_payment.participant_id id";
1430 $additionalClause = "
1431 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1432 AND civicrm_participant_payment.participant_id {$componentClause} )
1435 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1436 $componentSelect = " civicrm_membership_payment.membership_id id";
1437 $additionalClause = "
1438 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1439 AND civicrm_membership_payment.membership_id {$componentClause} )
1442 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1443 $componentSelect = " civicrm_pledge_payment.id id";
1444 $additionalClause = "
1445 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1446 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1450 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1451 trxn_id, {$componentSelect}
1452 FROM civicrm_contribution
1453 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1454 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1455 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1456 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1457 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1458 AND option_group_contribution_status.id = contribution_status.option_group_id )
1462 $dao = CRM_Core_DAO
::executeQuery($query);
1464 while ($dao->fetch()) {
1465 $paymentDetails[$dao->id
] = array(
1466 'total_amount' => $dao->total_amount
,
1467 'contribution_status' => $dao->status
,
1468 'receive_date' => $dao->receive_date
,
1469 'pay_instru' => $dao->payment_instrument
,
1470 'trxn_id' => $dao->trxn_id
,
1474 return $paymentDetails;
1478 * Create address associated with contribution record.
1480 * As long as there is one or more billing field in the parameters we will create the address.
1482 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1485 * @param array $params
1486 * @param int $billingLocationTypeID
1491 public static function createAddress($params, $billingLocationTypeID) {
1492 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1493 if ($hasBillingField) {
1494 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1495 return $address->id
;
1502 * Delete billing address record related contribution.
1504 * @param int $contributionId
1505 * @param int $contactId
1507 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1509 $contactJoin = NULL;
1511 if ($contributionId) {
1512 $clauses[] = "cc.id = {$contributionId}";
1516 $clauses[] = "cco.id = {$contactId}";
1517 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1520 if (empty($clauses)) {
1521 CRM_Core_Error
::fatal();
1524 $condition = implode(' OR ', $clauses);
1528 FROM civicrm_address ca
1529 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1533 $dao = CRM_Core_DAO
::executeQuery($query);
1535 while ($dao->fetch()) {
1536 $params = array('id' => $dao->id
);
1537 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1542 * This function check online pending contribution associated w/
1543 * Online Event Registration or Online Membership signup.
1545 * @param int $componentId
1546 * Participant/membership id.
1547 * @param string $componentName
1551 * pending contribution id.
1553 public static function checkOnlinePendingContribution($componentId, $componentName) {
1554 $contributionId = NULL;
1555 if (!$componentId ||
1556 !in_array($componentName, array('Event', 'Membership'))
1558 return $contributionId;
1561 if ($componentName == 'Event') {
1562 $idName = 'participant_id';
1563 $componentTable = 'civicrm_participant';
1564 $paymentTable = 'civicrm_participant_payment';
1565 $source = ts('Online Event Registration');
1568 if ($componentName == 'Membership') {
1569 $idName = 'membership_id';
1570 $componentTable = 'civicrm_membership';
1571 $paymentTable = 'civicrm_membership_payment';
1572 $source = ts('Online Contribution');
1575 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1578 SELECT component.id as {$idName},
1579 componentPayment.contribution_id as contribution_id,
1580 contribution.source source,
1581 contribution.contribution_status_id as contribution_status_id,
1582 contribution.is_pay_later as is_pay_later
1583 FROM $componentTable component
1584 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1585 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1586 WHERE component.id = {$componentId}";
1588 $dao = CRM_Core_DAO
::executeQuery($query);
1590 while ($dao->fetch()) {
1591 if ($dao->contribution_id
&&
1592 $dao->is_pay_later
&&
1593 $dao->contribution_status_id
== $pendingStatusId &&
1594 strpos($dao->source
, $source) !== FALSE
1596 $contributionId = $dao->contribution_id
;
1601 return $contributionId;
1605 * Update contribution as well as related objects.
1607 * This function by-passes hooks - to address this - don't use this function.
1611 * Use api contribute.completetransaction
1612 * For failures use failPayment (preferably exposing by api in the process).
1614 * @param array $params
1615 * @param bool $processContributionObject
1618 * @throws \Exception
1620 public static function transitionComponents($params, $processContributionObject = FALSE) {
1621 // get minimum required values.
1622 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1623 $componentId = CRM_Utils_Array
::value('component_id', $params);
1624 $componentName = CRM_Utils_Array
::value('componentName', $params);
1625 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1626 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1628 // if we already processed contribution object pass previous status id.
1629 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1631 $updateResult = array();
1633 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1635 // we process only ( Completed, Cancelled, or Failed ) contributions.
1636 if (!$contributionId ||
1637 !in_array($contributionStatusId, array(
1638 array_search('Completed', $contributionStatuses),
1639 array_search('Cancelled', $contributionStatuses),
1640 array_search('Failed', $contributionStatuses),
1643 return $updateResult;
1646 if (!$componentName ||
!$componentId) {
1647 // get the related component details.
1648 $componentDetails = self
::getComponentDetails($contributionId);
1651 $componentDetails['contact_id'] = $contactId;
1652 $componentDetails['component'] = $componentName;
1654 if ($componentName == 'event') {
1655 $componentDetails['participant'] = $componentId;
1658 $componentDetails['membership'] = $componentId;
1662 if (!empty($componentDetails['contact_id'])) {
1663 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1669 // do check for required ids.
1670 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1671 return $updateResult;
1674 //now we are ready w/ required ids, start processing.
1676 $baseIPN = new CRM_Core_Payment_BaseIPN();
1678 $input = $ids = $objects = array();
1680 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1681 $ids['contribution'] = $contributionId;
1682 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1683 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1684 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1685 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1686 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1687 $ids['contributionRecur'] = NULL;
1688 $ids['contributionPage'] = NULL;
1690 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1691 CRM_Core_Error
::fatal();
1694 $memberships = &$objects['membership'];
1695 $participant = &$objects['participant'];
1696 $pledgePayment = &$objects['pledge_payment'];
1697 $contribution = &$objects['contribution'];
1699 if ($pledgePayment) {
1700 $pledgePaymentIDs = array();
1701 foreach ($pledgePayment as $key => $object) {
1702 $pledgePaymentIDs[] = $object->id
;
1704 $pledgeID = $pledgePayment[0]->pledge_id
;
1707 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1710 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1711 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1716 // we might want to process contribution object.
1717 $processContribution = FALSE;
1718 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1719 if (is_array($memberships)) {
1720 foreach ($memberships as $membership) {
1722 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1723 $membership->save();
1725 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1726 if ($processContributionObject) {
1727 $processContribution = TRUE;
1734 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1735 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1737 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1738 if ($processContributionObject) {
1739 $processContribution = TRUE;
1743 if ($pledgePayment) {
1744 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1746 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1747 if ($processContributionObject) {
1748 $processContribution = TRUE;
1752 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1753 if (is_array($memberships)) {
1754 foreach ($memberships as $membership) {
1756 $membership->status_id
= array_search('Expired', $membershipStatuses);
1757 $membership->save();
1759 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1760 if ($processContributionObject) {
1761 $processContribution = TRUE;
1767 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1768 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1770 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1771 if ($processContributionObject) {
1772 $processContribution = TRUE;
1776 if ($pledgePayment) {
1777 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1779 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1780 if ($processContributionObject) {
1781 $processContribution = TRUE;
1785 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1787 // only pending contribution related object processed.
1788 if ($previousContriStatusId &&
1789 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1791 // this is case when we already processed contribution object.
1792 return $updateResult;
1794 elseif (!$previousContriStatusId &&
1795 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1797 // this is case when we are going to process contribution object later.
1798 return $updateResult;
1801 if (is_array($memberships)) {
1802 foreach ($memberships as $membership) {
1807 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1808 $membership->membership_type_id
,
1809 $membership->is_test
, $membership->id
1812 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1813 // this picks up membership type changes during renewals
1815 SELECT membership_type_id
1816 FROM civicrm_membership_log
1817 WHERE membership_id=$membership->id
1820 $dao = new CRM_Core_DAO();
1822 if ($dao->fetch()) {
1823 if (!empty($dao->membership_type_id
)) {
1824 $membership->membership_type_id
= $dao->membership_type_id
;
1825 $membership->save();
1828 // else fall back to using current membership type
1831 // Figure out number of terms
1833 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
1834 foreach ($lineitems as $lineitem) {
1835 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1836 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1838 // in case membership_num_terms comes through as null or zero
1839 $numterms = $numterms >= 1 ?
$numterms : 1;
1844 // CRM-15735-to update the membership status as per the contribution receive date
1846 if (!empty($params['receive_date'])) {
1847 $joinDate = $params['receive_date'];
1848 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1849 $membership->end_date
,
1850 $membership->join_date
,
1851 $params['receive_date'],
1853 $membership->membership_type_id
,
1856 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1857 $membership->save();
1860 if ($currentMembership) {
1861 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1862 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1863 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1866 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1869 //get the status for membership.
1870 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1872 $dates['join_date'],
1875 $membership->membership_type_id
,
1879 $formattedParams = array(
1880 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1881 array_search('Current', $membershipStatuses)
1883 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1884 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1885 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1888 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1890 $membership->copyValues($formattedParams);
1891 $membership->save();
1893 //updating the membership log
1894 $membershipLog = array();
1895 $membershipLog = $formattedParams;
1896 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1897 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1899 $membershipLog['start_date'] = $logStartDate;
1900 $membershipLog['membership_id'] = $membership->id
;
1901 $membershipLog['modified_id'] = $membership->contact_id
;
1902 $membershipLog['modified_date'] = date('Ymd');
1903 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1905 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1907 //update related Memberships.
1908 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1910 //CRM-19678: No Membership Renewal Activity is created when a Pay Later is set to Completed
1911 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Renewal', $membership->contact_id
);
1913 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1916 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1917 if ($processContributionObject) {
1918 $processContribution = TRUE;
1921 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1927 $updatedStatusId = array_search('Registered', $participantStatuses);
1928 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1930 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1931 if ($processContributionObject) {
1932 $processContribution = TRUE;
1936 if ($pledgePayment) {
1937 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1939 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1940 if ($processContributionObject) {
1941 $processContribution = TRUE;
1946 // process contribution object.
1947 if ($processContribution) {
1948 $contributionParams = array();
1955 'payment_instrument_id',
1958 'financial_type_id',
1959 'contribution_status_id',
1960 'non_deductible_amount',
1964 foreach ($fields as $field) {
1965 if (empty($params[$field])) {
1968 $contributionParams[$field] = $params[$field];
1971 $ids = array('contribution' => $contributionId);
1972 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1975 return $updateResult;
1979 * Returns all contribution related object ids.
1981 * @param $contributionId
1985 public static function getComponentDetails($contributionId) {
1986 $componentDetails = $pledgePayment = array();
1987 if (!$contributionId) {
1988 return $componentDetails;
1992 SELECT c.id as contribution_id,
1993 c.contact_id as contact_id,
1994 c.contribution_recur_id,
1995 mp.membership_id as membership_id,
1996 m.membership_type_id as membership_type_id,
1997 pp.participant_id as participant_id,
1998 p.event_id as event_id,
1999 pgp.id as pledge_payment_id
2000 FROM civicrm_contribution c
2001 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2002 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2003 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2004 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2005 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2006 WHERE c.id = $contributionId";
2008 $dao = CRM_Core_DAO
::executeQuery($query);
2009 $componentDetails = array();
2011 while ($dao->fetch()) {
2012 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2013 $componentDetails['contact_id'] = $dao->contact_id
;
2014 if ($dao->event_id
) {
2015 $componentDetails['event'] = $dao->event_id
;
2017 if ($dao->participant_id
) {
2018 $componentDetails['participant'] = $dao->participant_id
;
2020 if ($dao->membership_id
) {
2021 if (!isset($componentDetails['membership'])) {
2022 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2024 $componentDetails['membership'][] = $dao->membership_id
;
2025 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2027 if ($dao->pledge_payment_id
) {
2028 $pledgePayment[] = $dao->pledge_payment_id
;
2030 if ($dao->contribution_recur_id
) {
2031 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2035 if ($pledgePayment) {
2036 $componentDetails['pledge_payment'] = $pledgePayment;
2039 return $componentDetails;
2043 * @param int $contactId
2044 * @param bool $includeSoftCredit
2046 * @return null|string
2048 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2052 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2053 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2054 $liWhere = " AND i.financial_type_id IN (0)";
2055 if (!empty($financialTypes)) {
2056 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2057 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2059 $contactContributionsSQL = "
2060 SELECT contribution.id AS id
2061 FROM civicrm_contribution contribution
2062 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2063 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2067 $contactSoftCreditContributionsSQL = "
2068 SELECT contribution.id
2069 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2070 ON ( contribution.id = softContribution.contribution_id )
2071 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2072 $query = "SELECT count( x.id ) count FROM ( ";
2073 $query .= $contactContributionsSQL;
2075 if ($includeSoftCredit) {
2076 $query .= " UNION ";
2077 $query .= $contactSoftCreditContributionsSQL;
2082 return CRM_Core_DAO
::singleValueQuery($query);
2086 * Repeat a transaction as part of a recurring series.
2088 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2089 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2090 * subsequent call to the contribution.completetransaction api.
2092 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2094 * @param CRM_Contribute_BAO_Contribution $contribution
2095 * @param array $input
2096 * @param array $contributionParams
2097 * @param int $paymentProcessorID
2100 * @throws CiviCRM_API3_Exception
2102 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2103 if (!empty($contribution->id
)) {
2106 if (empty($contribution->id
)) {
2107 // Unclear why this would only be set for repeats.
2108 if (!empty($input['amount'])) {
2109 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2112 if (!empty($contributionParams['contribution_recur_id'])) {
2113 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2114 'id' => $contributionParams['contribution_recur_id'],
2116 if (!empty($recurringContribution['campaign_id'])) {
2117 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2118 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2120 if (!empty($recurringContribution['financial_type_id'])) {
2121 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2122 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2125 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2126 $contributionParams['contribution_recur_id'],
2127 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2129 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2131 $contributionParams['status_id'] = 'Pending';
2132 if (isset($contributionParams['financial_type_id'])) {
2133 // Give precedence to passed in type.
2134 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2137 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2139 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2140 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2142 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2143 //do not create CC or BCC emails or profile notifications.
2144 //The if is just to be safe. Not sure if we can ever arrive with this unset
2145 // but per CRM-19478 it seems it can be 'null'
2146 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2147 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2150 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2151 $contribution->id
= $createContribution['id'];
2152 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2158 * Get individual id for onbehalf contribution.
2160 * @param int $contributionId
2162 * @param int $contributorId
2166 * containing organization id and individual id
2168 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2172 if (!$contributionId) {
2176 // fetch contributor id if null
2177 if (!$contributorId) {
2178 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2179 $contributionId, 'contact_id'
2183 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2184 $activityTypeId = array_search('Contribution', $activityTypeIds);
2186 if ($activityTypeId && $contributorId) {
2188 SELECT civicrm_activity_contact.contact_id
2189 FROM civicrm_activity_contact
2190 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2191 WHERE civicrm_activity.activity_type_id = %1
2192 AND civicrm_activity.source_record_id = %2
2193 AND civicrm_activity_contact.record_type_id = %3
2196 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2197 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2200 1 => array($activityTypeId, 'Integer'),
2201 2 => array($contributionId, 'Integer'),
2202 3 => array($sourceID, 'Integer'),
2205 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2207 // for on behalf contribution source is individual and contributor is organization
2208 if ($sourceContactId && $sourceContactId != $contributorId) {
2209 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2210 // get rel type id for employee of relation
2211 foreach ($relationshipTypeIds as $id => $typeVals) {
2212 if ($typeVals['name_a_b'] == 'Employee of') {
2213 $relationshipTypeId = $id;
2218 $rel = new CRM_Contact_DAO_Relationship();
2219 $rel->relationship_type_id
= $relationshipTypeId;
2220 $rel->contact_id_a
= $sourceContactId;
2221 $rel->contact_id_b
= $contributorId;
2222 if ($rel->find(TRUE)) {
2223 $ids['individual_id'] = $rel->contact_id_a
;
2224 $ids['organization_id'] = $rel->contact_id_b
;
2235 public static function getContributionDates() {
2236 $config = CRM_Core_Config
::singleton();
2237 $currentMonth = date('m');
2238 $currentDay = date('d');
2239 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2240 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2241 (int ) $config->fiscalYearStart
['d'] > $currentDay
2244 $year = date('Y') - 1;
2249 $year = array('Y' => $year);
2250 $yearDate = $config->fiscalYearStart
;
2251 $yearDate = array_merge($year, $yearDate);
2252 $yearDate = CRM_Utils_Date
::format($yearDate);
2254 $monthDate = date('Ym') . '01';
2260 'yearDate' => $yearDate,
2261 'monthDate' => $monthDate,
2266 * Load objects relations to contribution object.
2267 * Objects are stored in the $_relatedObjects property
2268 * In the first instance we are just moving functionality from BASEIpn -
2269 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2271 * Note that the unit test for the BaseIPN class tests this function
2273 * @param array $input
2274 * Input as delivered from Payment Processor.
2276 * Ids as Loaded by Payment Processor.
2277 * @param bool $loadAll
2278 * Load all related objects - even where id not passed in? (allows API to call this).
2283 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2285 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2286 if (empty($ids['contact']) && isset($this->contact_id
)) {
2287 $ids['contact'] = $this->contact_id
;
2290 if (empty($this->_component
)) {
2291 if (!empty($ids['event'])) {
2292 $this->_component
= 'event';
2295 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2299 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2300 // refactoring than anything else, and has unit test coverage.
2301 if (empty($this->financial_type_id
)) {
2305 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2310 if (!$paymentProcessorID && $this->contribution_page_id
) {
2311 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2312 $this->contribution_page_id
,
2315 if ($paymentProcessorID) {
2316 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2320 $ids['contributionType'] = $this->financial_type_id
;
2321 $ids['financialType'] = $this->financial_type_id
;
2324 'contact' => 'CRM_Contact_BAO_Contact',
2325 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2326 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2327 'financialType' => 'CRM_Financial_BAO_FinancialType',
2329 foreach ($entities as $entity => $bao) {
2330 if (!empty($ids[$entity])) {
2331 $this->_relatedObjects
[$entity] = new $bao();
2332 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2333 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2334 throw new CRM_Core_Exception($entity . ' could not be loaded');
2339 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2340 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2343 if (!empty($ids['pledge_payment'])) {
2344 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2345 if (empty($paymentID)) {
2348 $payment = new CRM_Pledge_BAO_PledgePayment();
2349 $payment->id
= $paymentID;
2350 if (!$payment->find(TRUE)) {
2351 throw new Exception("Could not find pledge payment record: " . $paymentID);
2353 $this->_relatedObjects
['pledge_payment'][] = $payment;
2357 $this->loadRelatedMembershipObjects($ids);
2359 if ($this->_component
!= 'contribute') {
2360 // we are in event mode
2361 // make sure event exists and is valid
2362 $event = new CRM_Event_BAO_Event();
2363 $event->id
= $ids['event'];
2364 if ($ids['event'] &&
2367 throw new Exception("Could not find event: " . $ids['event']);
2370 $this->_relatedObjects
['event'] = &$event;
2372 $participant = new CRM_Event_BAO_Participant();
2373 $participant->id
= $ids['participant'];
2374 if ($ids['participant'] &&
2375 !$participant->find(TRUE)
2377 throw new Exception("Could not find participant: " . $ids['participant']);
2379 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2381 $this->_relatedObjects
['participant'] = &$participant;
2383 // get the payment processor id from event - this is inaccurate see CRM-16923
2384 // in future we should look at throwing an exception here rather than an dubious guess.
2385 if (!$paymentProcessorID) {
2386 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2387 if ($paymentProcessorID) {
2388 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2393 if ($paymentProcessorID) {
2394 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2395 $this->is_test ?
'test' : 'live'
2397 $ids['paymentProcessor'] = $paymentProcessorID;
2398 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2404 * Create array of message information - ie. return html version, txt version, to field
2406 * @param array $input
2407 * Incoming information.
2408 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2409 * just check presence of recur object but maintaining legacy approach
2412 * IDs of related objects.
2413 * @param array $values
2414 * Any values that may have already been compiled by calling process.
2415 * This is augmented by values 'gathered' by gatherMessageValues
2416 * @param bool $recur
2417 * @param bool $returnMessageText
2418 * Distinguishes between whether to send message or return.
2419 * message text. We are working towards this function ALWAYS returning message text & calling
2420 * function doing emails / pdfs with it
2426 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2427 $this->loadRelatedObjects($input, $ids);
2429 if (empty($this->_component
)) {
2430 $this->_component
= CRM_Utils_Array
::value('component', $input);
2433 //not really sure what params might be passed in but lets merge em into values
2434 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2435 if (!empty($input['receipt_date'])) {
2436 $values['receipt_date'] = $input['receipt_date'];
2439 $template = CRM_Core_Smarty
::singleton();
2440 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2441 //what does recur 'mean here - to do with payment processor return functionality but
2442 // what is the importance
2443 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2444 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2446 $entityID = $entity = NULL;
2447 if (isset($ids['contribution'])) {
2448 $entity = 'contribution';
2449 $entityID = $ids['contribution'];
2451 if (!empty($ids['membership'])) {
2452 //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
2453 // 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
2454 // line having loaded an array
2455 $ids['membership'] = (array) $ids['membership'];
2456 $entity = 'membership';
2457 $entityID = $ids['membership'][0];
2460 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2461 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2462 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2464 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2465 //direct mode showing billing block, so use directIPN for temporary
2466 $template->assign('contributeMode', 'directIPN');
2469 // todo remove strtolower - check consistency
2470 if (strtolower($this->_component
) == 'event') {
2471 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2472 $values['event'] = array();
2474 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2476 //get location details
2477 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2478 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2480 $ufJoinParams = array(
2481 'entity_table' => 'civicrm_event',
2482 'entity_id' => $ids['event'],
2483 'module' => 'CiviEvent',
2486 list($custom_pre_id,
2488 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2490 $values['custom_pre_id'] = $custom_pre_id;
2491 $values['custom_post_id'] = $custom_post_ids;
2492 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2493 //and cases involving status updation through ipn
2494 // whatever that means!
2495 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2496 // perhaps we should throw an e-notice if amount is set & force total_amount?
2497 if (!empty($input['amount'])) {
2498 $values['totalAmount'] = $input['amount'];
2501 if ($values['event']['is_email_confirm']) {
2502 $values['is_email_receipt'] = 1;
2505 if (!empty($ids['contribution'])) {
2506 $values['contributionId'] = $ids['contribution'];
2509 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2510 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2514 $values['contribution_id'] = $this->id
;
2515 if (!empty($ids['related_contact'])) {
2516 $values['related_contact'] = $ids['related_contact'];
2517 if (isset($ids['onbehalf_dupe_alert'])) {
2518 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2520 $entityBlock = array(
2521 'contact_id' => $ids['contact'],
2522 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2523 'Home', 'id', 'name'
2526 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2527 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2530 if ($this->is_test
) {
2533 if (!empty($this->_relatedObjects
['membership'])) {
2534 foreach ($this->_relatedObjects
['membership'] as $membership) {
2535 if ($membership->id
) {
2536 $values['isMembership'] = TRUE;
2537 $values['membership_assign'] = TRUE;
2539 // need to set the membership values here
2540 $template->assign('membership_name',
2541 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2543 $template->assign('mem_start_date', $membership->start_date
);
2544 $template->assign('mem_join_date', $membership->join_date
);
2545 $template->assign('mem_end_date', $membership->end_date
);
2546 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2547 $template->assign('mem_status', $membership_status);
2548 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2549 $values['is_pay_later'] = 1;
2552 if ($recur && $paymentObject) {
2553 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2554 $template->assign('cancelSubscriptionUrl', $url);
2555 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2556 $template->assign('updateSubscriptionBillingUrl', $url);
2557 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2558 $template->assign('updateSubscriptionUrl', $url);
2561 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2564 // otherwise if its about sending emails, continue sending without return, as we
2565 // don't want to exit the loop.
2570 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2576 * Gather values for contribution mail - this function has been created
2577 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2578 * Values related to the contribution in question are gathered
2580 * @param array $input
2581 * Input into function (probably from payment processor).
2582 * @param array $values
2584 * The set of ids related to the input.
2588 public function _gatherMessageValues($input, &$values, $ids = array()) {
2589 // set display address of contributor
2590 if ($this->address_id
) {
2591 $addressParams = array('id' => $this->address_id
);
2592 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2593 $addressDetails = array_values($addressDetails);
2595 // Else we assign the billing address of the contribution contact.
2597 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2598 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2599 $addressDetails = array_values($addressDetails);
2602 if (!empty($addressDetails[0]['display'])) {
2603 $values['address'] = $addressDetails[0]['display'];
2606 if ($this->_component
== 'contribute') {
2607 //get soft contributions
2608 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2609 if (!empty($softContributions)) {
2610 $values['softContributions'] = $softContributions['soft_credit'];
2612 if (isset($this->contribution_page_id
)) {
2613 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2614 if ($this->contribution_page_id
) {
2615 // CRM-8254 - override default currency if applicable
2616 $config = CRM_Core_Config
::singleton();
2617 $config->defaultCurrency
= CRM_Utils_Array
::value(
2620 $config->defaultCurrency
2624 // no contribution page -probably back office
2626 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2627 $values['is_email_receipt'] = 1;
2628 $values['title'] = 'Contribution';
2630 // set lineItem for contribution
2632 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2633 if (!empty($lineItems)) {
2634 $firstLineItem = reset($lineItems);
2635 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2636 $values['priceSetID'] = $priceSet['id'];
2637 foreach ($lineItems as &$eachItem) {
2638 if (isset($this->_relatedObjects
['membership'])
2639 && is_array($this->_relatedObjects
['membership'])
2640 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2641 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2642 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2643 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2645 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2646 // However, that does create upgrade pain so would be better to be phased in.
2647 $values['useForMember'] = !$priceSet['is_quick_config'];
2649 $values['lineItem'][0] = $lineItems;
2653 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2657 // if this is onbehalf of contribution then set related contact
2658 if (!empty($relatedContact['individual_id'])) {
2659 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2664 $eventParams = array(
2665 'id' => $this->_relatedObjects
['event']->id
,
2667 $values['event'] = array();
2669 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2670 // add custom fields for event
2671 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2673 $eventCustomGroup = array();
2674 foreach ($eventGroupTree as $key => $group) {
2675 if ($key === 'info') {
2679 foreach ($group['fields'] as $k => $customField) {
2680 $groupLabel = $group['title'];
2681 if (!empty($customField['customValue'])) {
2682 foreach ($customField['customValue'] as $customFieldValues) {
2683 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2688 $values['event']['customGroup'] = $eventCustomGroup;
2690 //get participant details
2691 $participantParams = array(
2692 'id' => $this->_relatedObjects
['participant']->id
,
2695 $values['participant'] = array();
2697 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2698 // add custom fields for event
2699 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2700 $participantCustomGroup = array();
2701 foreach ($participantGroupTree as $key => $group) {
2702 if ($key === 'info') {
2706 foreach ($group['fields'] as $k => $customField) {
2707 $groupLabel = $group['title'];
2708 if (!empty($customField['customValue'])) {
2709 foreach ($customField['customValue'] as $customFieldValues) {
2710 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2715 $values['participant']['customGroup'] = $participantCustomGroup;
2717 //get location details
2718 $locationParams = array(
2719 'entity_id' => $this->_relatedObjects
['event']->id
,
2720 'entity_table' => 'civicrm_event',
2722 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2724 $ufJoinParams = array(
2725 'entity_table' => 'civicrm_event',
2726 'entity_id' => $ids['event'],
2727 'module' => 'CiviEvent',
2730 list($custom_pre_id,
2732 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2734 $values['custom_pre_id'] = $custom_pre_id;
2735 $values['custom_post_id'] = $custom_post_ids;
2737 // set lineItem for event contribution
2739 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2740 if (!empty($participantIds)) {
2741 foreach ($participantIds as $pIDs) {
2742 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2743 if (!CRM_Utils_System
::isNull($lineItem)) {
2744 $values['lineItem'][] = $lineItem;
2751 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2753 $customGroup = array();
2754 foreach ($groupTree as $key => $group) {
2755 if ($key === 'info') {
2759 foreach ($group['fields'] as $k => $customField) {
2760 $groupLabel = $group['title'];
2761 if (!empty($customField['customValue'])) {
2762 foreach ($customField['customValue'] as $customFieldValues) {
2763 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2768 $values['customGroup'] = $customGroup;
2774 * Assign message variables to template but try to break the habit.
2776 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2777 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2778 * multiple recurring payments for processors like IATS that use tokens.
2780 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2781 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2782 * Note we send directly from this function in some cases because it is only partly refactored.
2784 * Don't call this function directly as the signature will change.
2788 * @param CRM_Core_SMARTY $template
2789 * @param bool $recur
2790 * @param bool $returnMessageText
2794 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2795 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2796 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2797 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2799 // For some unit tests contribution cannot contain paymentProcessor information
2800 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
2801 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
2803 //assign honor information to receipt message
2804 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2806 if (isset($softRecord['soft_credit'])) {
2807 //if id of contribution page is present
2808 if (!empty($values['id'])) {
2809 $values['honor'] = array(
2810 'honor_profile_values' => array(),
2811 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2812 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2815 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2816 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2819 //offline contribution
2820 $softCreditTypes = $softCredits = array();
2821 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2822 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2823 $softCredits[$key] = array(
2824 'Name' => $softCredit['contact_name'],
2825 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2828 $template->assign('softCreditTypes', $softCreditTypes);
2829 $template->assign('softCredits', $softCredits);
2833 $dao = new CRM_Contribute_DAO_ContributionProduct();
2834 $dao->contribution_id
= $this->id
;
2835 if ($dao->find(TRUE)) {
2836 $premiumId = $dao->product_id
;
2837 $template->assign('option', $dao->product_option
);
2839 $productDAO = new CRM_Contribute_DAO_Product();
2840 $productDAO->id
= $premiumId;
2841 $productDAO->find(TRUE);
2842 $template->assign('selectPremium', TRUE);
2843 $template->assign('product_name', $productDAO->name
);
2844 $template->assign('price', $productDAO->price
);
2845 $template->assign('sku', $productDAO->sku
);
2847 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2848 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2849 if (!$values['amount'] && isset($this->total_amount
)) {
2850 $values['amount'] = $this->total_amount
;
2853 // add the new contribution values
2854 if (strtolower($this->_component
) == 'contribute') {
2856 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2857 $softDAO->contribution_id
= $this->id
;
2858 if ($softDAO->find(TRUE)) {
2859 $template->assign('pcpBlock', TRUE);
2860 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2861 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2862 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2864 //assign the pcp page title for email subject
2865 $pcpDAO = new CRM_PCP_DAO_PCP();
2866 $pcpDAO->id
= $softDAO->pcp_id
;
2867 if ($pcpDAO->find(TRUE)) {
2868 $template->assign('title', $pcpDAO->title
);
2873 if ($this->financial_type_id
) {
2874 $values['financial_type_id'] = $this->financial_type_id
;
2877 $template->assign('trxn_id', $this->trxn_id
);
2878 $template->assign('receive_date',
2879 CRM_Utils_Date
::processDate($this->receive_date
)
2881 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2882 $template->assign('action', $this->is_test ?
1024 : 1);
2883 $template->assign('receipt_text',
2884 CRM_Utils_Array
::value('receipt_text',
2888 $template->assign('is_monetary', 1);
2889 $template->assign('is_recur', (bool) $recur);
2890 $template->assign('currency', $this->currency
);
2891 $template->assign('address', CRM_Utils_Address
::format($input));
2892 if (!empty($values['customGroup'])) {
2893 $template->assign('customGroup', $values['customGroup']);
2895 if (!empty($values['softContributions'])) {
2896 $template->assign('softContributions', $values['softContributions']);
2898 if ($this->_component
== 'event') {
2899 $template->assign('title', $values['event']['title']);
2900 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2901 $viewRoles = array();
2902 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2903 $viewRoles[] = $participantRoles[$v];
2905 $values['event']['participant_role'] = implode(', ', $viewRoles);
2906 $template->assign('event', $values['event']);
2907 $template->assign('participant', $values['participant']);
2908 $template->assign('location', $values['location']);
2909 $template->assign('customPre', $values['custom_pre_id']);
2910 $template->assign('customPost', $values['custom_post_id']);
2913 if ($this->_relatedObjects
['participant']->is_test
) {
2917 $values['params'] = array();
2918 //to get email of primary participant.
2919 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2920 $primaryAmount[] = array(
2921 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2922 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2924 //build an array of cId/pId of participants
2925 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2926 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2927 //send receipt to additional participant if exists
2928 if (count($additionalIDs)) {
2929 $template->assign('isPrimary', 0);
2930 $template->assign('customProfile', NULL);
2931 //set additionalParticipant true
2932 $values['params']['additionalParticipant'] = TRUE;
2933 foreach ($additionalIDs as $pId => $cId) {
2935 //to change the status pending to completed
2936 $additional = new CRM_Event_DAO_Participant();
2937 $additional->id
= $pId;
2938 $additional->contact_id
= $cId;
2939 $additional->find(TRUE);
2940 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2941 $additional->status_id
= 1;
2942 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2943 //if additional participant dont have email
2945 if (!$additionalParticipantInfo) {
2946 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2948 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2949 $primaryAmount[] = array(
2950 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2951 'amount' => $additional->fee_amount
,
2953 $additional->save();
2954 $additional->free();
2955 $template->assign('amount', $amount);
2956 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2960 //build an array of custom profile and assigning it to template
2961 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2963 if (count($customProfile)) {
2964 $template->assign('customProfile', $customProfile);
2967 // for primary contact
2968 $values['params']['additionalParticipant'] = FALSE;
2969 $template->assign('isPrimary', 1);
2970 $template->assign('amount', $primaryAmount);
2971 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2972 if ($this->payment_instrument_id
) {
2973 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2974 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2976 // carry paylater, since we did not created billing,
2977 // so need to pull email from primary location, CRM-4395
2978 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2984 * Check whether payment processor supports
2985 * cancellation of contribution subscription
2987 * @param int $contributionId
2990 * @param bool $isNotCancelled
2994 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2995 $cacheKeyString = "$contributionId";
2996 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2998 static $supportsCancel = array();
3000 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3001 $supportsCancel[$cacheKeyString] = FALSE;
3002 $isCancelled = FALSE;
3004 if ($isNotCancelled) {
3005 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3008 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3009 if (!empty($paymentObject)) {
3010 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3013 return $supportsCancel[$cacheKeyString];
3017 * Check whether subscription is already cancelled.
3019 * @param int $contributionId
3023 * contribution status
3025 public static function isSubscriptionCancelled($contributionId) {
3027 SELECT cr.contribution_status_id
3028 FROM civicrm_contribution_recur cr
3029 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3030 WHERE con.id = %1 LIMIT 1";
3031 $params = array(1 => array($contributionId, 'Integer'));
3032 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3033 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3034 if ($status == 'Cancelled') {
3041 * Create all financial accounts entry.
3043 * @param array $params
3044 * Contribution object, line item array and params for trxn.
3047 * @param array $financialTrxnValues
3049 * @return null|object
3051 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3052 $skipRecords = $update = $return = $isRelatedId = FALSE;
3054 $additionalParticipantId = array();
3055 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3056 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3058 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3059 $entityId = $params['participant_id'];
3060 $entityTable = 'civicrm_participant';
3061 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3063 elseif (!empty($params['membership_id'])) {
3064 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3065 // are created off one contribution should be handled elsewhere
3066 $entityId = $params['membership_id'];
3067 $entityTable = 'civicrm_membership';
3070 $entityId = $params['contribution']->id
;
3071 $entityTable = 'civicrm_contribution';
3074 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3075 $isRelatedId = TRUE;
3078 $entityID[] = $entityId;
3079 if (!empty($additionalParticipantId)) {
3080 $entityID +
= $additionalParticipantId;
3082 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3083 if (empty($params['prevContribution'])) {
3090 $statusId = $params['contribution']->contribution_status_id
;
3091 // CRM-13964 partial payment
3092 if ($contributionStatus == 'Partially paid'
3093 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3095 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_pay']);
3096 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3098 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3099 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3100 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3101 $params['total_amount'] = $partialAmtPay;
3103 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3104 if (empty($balanceTrxnInfo['trxn_id'])) {
3105 // create new balance transaction record
3106 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3107 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3109 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3110 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3111 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3112 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3113 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3114 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3115 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3116 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3117 $balanceTrxnParams['status_id'] = $statusId;
3118 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3119 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3120 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3121 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3123 $balanceTrxnParams['is_payment'] = 1;
3125 if (!empty($params['payment_processor'])) {
3126 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3128 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3132 // build line item array if its not set in $params
3133 if (empty($params['line_item']) ||
$additionalParticipantId) {
3134 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3137 if ($contributionStatus != 'Failed' &&
3138 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3140 $skipRecords = TRUE;
3141 $pendingStatus = array(
3145 if (in_array($contributionStatus, $pendingStatus)) {
3146 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3147 $params['financial_type_id'],
3148 'Accounts Receivable Account is'
3151 elseif (!empty($params['payment_processor'])) {
3152 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3153 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3154 'id' => $params['payment_processor'],
3155 'return' => 'payment_instrument_id',
3158 elseif (!empty($params['payment_instrument_id'])) {
3159 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3162 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3163 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3164 $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);
3167 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3168 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3169 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3171 //build financial transaction params
3172 $trxnParams = array(
3173 'contribution_id' => $params['contribution']->id
,
3174 'to_financial_account_id' => $params['to_financial_account_id'],
3175 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3176 'total_amount' => $totalAmount,
3177 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3178 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3179 'currency' => $params['contribution']->currency
,
3180 'trxn_id' => $params['contribution']->trxn_id
,
3181 'status_id' => $statusId,
3182 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3183 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3185 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3186 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3187 if (isset($params['refund_trxn_id'])) {
3188 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3189 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3192 //CRM-16259, set is_payment flag for non pending status
3193 if (!in_array($contributionStatus, $pendingStatus)) {
3194 $trxnParams['is_payment'] = 1;
3196 if (!empty($params['payment_processor'])) {
3197 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3200 if (isset($fromFinancialAccountId)) {
3201 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3204 // consider external values passed for recording transaction entry
3205 if (!empty($financialTrxnValues)) {
3206 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3209 $params['trxnParams'] = $trxnParams;
3211 if (!empty($params['prevContribution'])) {
3213 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3214 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3215 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3216 if (!isset($params['trxnParams']['trxn_id'])) {
3217 // Actually I have no idea why we are overwriting any values from the previous contribution.
3218 // (filling makes sense to me). However, only protecting this value as I really really know we
3219 // don't want this one overwritten.
3221 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3223 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3225 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3226 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3227 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3229 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3230 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3233 //if financial type is changed
3234 if (!empty($params['financial_type_id']) &&
3235 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3237 $accountRelationship = 'Income Account is';
3238 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3239 $accountRelationship = 'Deferred Revenue Account is';
3241 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' "));
3242 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3243 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3244 if ($oldFinancialAccount != $newFinancialAccount) {
3245 $params['total_amount'] = 0;
3246 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3247 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3248 $params['prevContribution']->financial_type_id
, $relationTypeId);
3251 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3252 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3253 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3256 self
::updateFinancialAccounts($params, 'changeFinancialType');
3257 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3258 $params['financial_account_id'] = $newFinancialAccount;
3259 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3260 self
::updateFinancialAccounts($params);
3261 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3263 $params['deferred_financial_account_id'] = $newFinancialAccount;
3267 //Update contribution status
3268 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3269 if (!isset($params['refund_trxn_id'])) {
3270 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3271 // gets preference over another so I am only 'protecting' a very specific tested flow
3272 // and letting natural justice take care of the rest.
3273 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3275 if (!empty($params['contribution_status_id']) &&
3276 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3278 //Update Financial Records
3279 self
::updateFinancialAccounts($params, 'changedStatus');
3283 // change Payment Instrument for a Completed contribution
3284 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3285 // instrument is null and now new payment instrument is added along with the payment
3286 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3287 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3288 if (array_key_exists('payment_instrument_id', $params)) {
3289 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3290 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3291 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3293 //check if status is changed from Pending to Completed
3294 // do not update payment instrument changes for Pending to Completed
3295 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3296 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3298 // for all other statuses create new financial records
3299 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3300 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3301 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3305 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3306 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3307 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3309 // for any other payment instrument changes create new financial records
3310 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3311 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3312 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3315 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3316 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3318 // another special case when check number is changed, create new financial records
3319 // create financial trxn with negative amount
3320 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3321 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3322 // create financial trxn with positive amount
3323 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3324 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3325 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3330 //if Change contribution amount
3331 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3332 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3333 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3334 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3335 if (isset($totalAmount) &&
3336 $totalAmount != $params['prevContribution']->total_amount
3338 //Update Financial Records
3339 $params['trxnParams']['from_financial_account_id'] = NULL;
3340 self
::updateFinancialAccounts($params, 'changedAmount');
3345 // Looks like we might have a data correction update.
3346 // This would be a case where a transaction id has been entered but it is incorrect &
3347 // the person goes back in & fixes it, as opposed to a new transaction.
3348 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3349 // the data fix scenario.
3351 if (isset($params['refund_trxn_id'])) {
3352 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3353 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3354 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3361 // records finanical trxn and entity financial trxn
3362 // also make it available as return value
3363 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3364 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3365 $params['entity_id'] = $financialTxn->id
;
3366 if (empty($params['partial_payment_total']) && empty($params['partial_amount_pay'])) {
3367 self
::$_trxnIDs[] = $financialTxn->id
;
3371 // record line items and financial items
3372 if (empty($params['skipLineItem'])) {
3373 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3376 // create batch entry if batch_id is passed and
3377 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3378 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3379 $entityParams = array(
3380 'batch_id' => $params['batch_id'],
3381 'entity_table' => 'civicrm_financial_trxn',
3382 'entity_id' => $financialTxn->id
,
3384 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3387 // when a fee is charged
3388 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3389 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3392 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3393 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3395 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3396 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3397 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3399 unset($params['line_item']);
3400 self
::$_trxnIDs = NULL;
3405 * Update all financial accounts entry.
3407 * @param array $params
3408 * Contribution object, line item array and params for trxn.
3410 * @param string $context
3413 * @param null $skipTrxn
3416 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3417 $itemAmount = $trxnID = NULL;
3418 //get all the statuses
3419 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3420 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3421 if (($previousContributionStatus == 'Pending'
3422 ||
$previousContributionStatus == 'In Progress')
3423 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3424 && $context == 'changePaymentInstrument'
3428 if ((($previousContributionStatus == 'Partially paid'
3429 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3430 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3431 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3432 && $context == 'changedStatus'
3436 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3437 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3439 if ($context == 'changedStatus') {
3440 //get all the statuses
3441 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3442 $cancelledTaxAmount = 0;
3443 if ($previousContributionStatus == 'Completed'
3444 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3446 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3447 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3448 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3449 $creditNoteId = self
::createCreditNoteId();
3450 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3453 elseif (($previousContributionStatus == 'Pending'
3454 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3456 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3457 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3458 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3460 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3461 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3462 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3463 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3464 $creditNoteId = self
::createCreditNoteId();
3465 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3469 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3472 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3474 elseif ($context == 'changePaymentInstrument') {
3475 $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount'];
3476 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $params);
3477 if (empty($deferredFinancialAccount)) {
3478 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
3479 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3481 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3482 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3483 if ($params['total_amount'] != $params['trxnParams']['total_amount']) {
3484 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3485 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3488 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3489 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3494 if ($context == 'changedStatus') {
3495 if (($previousContributionStatus == 'Pending'
3496 ||
$previousContributionStatus == 'In Progress')
3497 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3499 if (empty($params['line_item'])) {
3501 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3502 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3503 // & this can be removed
3506 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3507 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3508 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3509 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3510 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3512 $entityParams = array(
3513 'entity_table' => 'civicrm_financial_item',
3515 foreach ($params['line_item'] as $fieldId => $fields) {
3516 foreach ($fields as $fieldValueId => $fieldValues) {
3518 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3519 2 => array($fieldValues['id'], 'Integer'),
3521 CRM_Core_DAO
::executeQuery($query, $fparams);
3523 1 => array($fieldValues['id'], 'Integer'),
3525 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3526 while ($financialItem->fetch()) {
3527 $entityParams['entity_id'] = $financialItem->id
;
3528 $entityParams['amount'] = $financialItem->amount
;
3529 foreach (self
::$_trxnIDs as $tID) {
3530 $entityParams['financial_trxn_id'] = $tID;
3531 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3539 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3540 $params['entity_id'] = $trxn->id
;
3541 if ($context != 'changePaymentInstrument') {
3542 $itemParams['entity_table'] = 'civicrm_line_item';
3543 $trxnIds['id'] = $params['entity_id'];
3544 foreach ($params['line_item'] as $fieldId => $fields) {
3545 foreach ($fields as $fieldValueId => $fieldValues) {
3546 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3547 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3548 if ($params['contribution']->receive_date
) {
3549 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3552 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3554 $currency = $params['prevContribution']->currency
;
3555 if ($params['contribution']->currency
) {
3556 $currency = $params['contribution']->currency
;
3559 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3562 if (!empty($params['is_quick_config'])) {
3563 $amount = $itemAmount;
3565 $amount = $params['total_amount'];
3569 $amount = $diff * $fieldValues['line_total'];
3572 $itemParams = array(
3573 'transaction_date' => $receiveDate,
3574 'contact_id' => $params['prevContribution']->contact_id
,
3575 'currency' => $currency,
3576 'amount' => $amount,
3577 'description' => $prevFinancialItem->description
,
3578 'status_id' => $prevFinancialItem->status_id
,
3579 'financial_account_id' => $financialAccount,
3580 'entity_table' => 'civicrm_line_item',
3581 'entity_id' => $fieldValues['id'],
3583 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3584 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3585 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3587 if ($fieldValues['tax_amount']) {
3588 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3589 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3590 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3591 $itemParams['description'] = $taxTerm;
3592 if ($fieldValues['financial_type_id']) {
3593 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3595 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3600 if ($context == 'changeFinancialType') {
3601 $params['skipLineItem'] = FALSE;
3602 foreach ($params['line_item'] as &$lineItems) {
3603 foreach ($lineItems as &$line) {
3604 $line['financial_type_id'] = $params['financial_type_id'];
3608 if ($context == 'changePaymentInstrument') {
3609 // store financial item Proportionaly.
3610 $trxnParams = array(
3611 'total_amount' => $trxn->total_amount
,
3612 'contribution_id' => $params['contribution']->id
,
3614 self
::assignProportionalLineItems($trxnParams, $trxn->id
, $params['prevContribution']->total_amount
);
3616 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3620 * Is this contribution status a reversal.
3622 * If so we would expect to record a negative value in the financial_trxn table.
3624 * @param int $status_id
3628 public static function isContributionStatusNegative($status_id) {
3629 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3630 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3634 * Check status validation on update of a contribution.
3636 * @param array $values
3637 * Previous form values before submit.
3639 * @param array $fields
3640 * The input form values.
3642 * @param array $errors
3647 public static function checkStatusValidation($values, &$fields, &$errors) {
3648 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3649 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3650 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3654 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3655 $checkStatus = array(
3656 'Cancelled' => array('Completed', 'Refunded'),
3657 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3658 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3659 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3660 'Refunded' => array('Cancelled', 'Completed'),
3661 'Partially paid' => array('Completed'),
3664 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3665 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3667 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3668 1 => $contributionStatuses[$values['contribution_status_id']],
3669 2 => $contributionStatuses[$fields['contribution_status_id']],
3675 * Delete contribution of contact.
3679 * @param int $contactId
3683 public static function deleteContactContribution($contactId) {
3684 $contribution = new CRM_Contribute_DAO_Contribution();
3685 $contribution->contact_id
= $contactId;
3686 $contribution->find();
3687 while ($contribution->fetch()) {
3688 self
::deleteContribution($contribution->id
);
3693 * Get options for a given contribution field.
3694 * @see CRM_Core_DAO::buildOptions
3696 * @param string $fieldName
3697 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3698 * @param array $props whatever is known about this dao object.
3700 * @return array|bool
3702 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3703 $className = __CLASS__
;
3705 switch ($fieldName) {
3706 // This field is not part of this object but the api supports it
3707 case 'payment_processor':
3708 $className = 'CRM_Contribute_BAO_ContributionPage';
3709 // Filter results by contribution page
3710 if (!empty($props['contribution_page_id'])) {
3711 $page = civicrm_api('contribution_page', 'getsingle', array(
3713 'id' => ($props['contribution_page_id']),
3715 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3716 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3720 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3721 case 'honor_type_id':
3722 $className = 'CRM_Contribute_BAO_ContributionSoft';
3723 $fieldName = 'soft_credit_type_id';
3724 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3727 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3731 * Validate financial type.
3735 * @param int $financialTypeId
3736 * Financial Type id.
3738 * @param string $relationName
3740 * @return array|bool
3742 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3743 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3744 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3746 if (!$financialAccount) {
3747 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3754 * Function to record additional payment for partial and refund contributions.
3756 * @param int $contributionId
3757 * is the invoice contribution id (got created after processing participant payment).
3758 * @param array $trxnsData
3759 * to take user provided input of transaction details.
3760 * @param string $paymentType
3761 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3762 * @param int $participantId
3763 * @param bool $updateStatus
3765 * @return null|object
3767 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3768 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3769 $getInfoOf['id'] = $contributionId;
3770 $defaults = array();
3771 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3772 if (!$participantId) {
3773 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
3776 if ($paymentType == 'owed') {
3777 // build params for recording financial trxn entry
3778 $params['contribution'] = $contributionDAO;
3779 $params = array_merge($defaults, $params);
3780 $params['skipLineItem'] = TRUE;
3781 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3782 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3783 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3784 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3787 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3788 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3789 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3791 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3792 if (!empty($trxnId)) {
3793 $trxnId = $trxnId['trxn_id'];
3795 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3796 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3799 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3800 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3801 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3805 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3806 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3807 FROM civicrm_financial_trxn ft
3808 LEFT JOIN civicrm_entity_financial_trxn eft
3809 ON (ft.id = eft.financial_trxn_id)
3810 WHERE eft.entity_table = 'civicrm_contribution'
3811 AND eft.entity_id = {$contributionId}
3812 AND ft.to_financial_account_id != {$toFinancialAccount}
3813 AND ft.status_id = {$statusId}
3815 $query = CRM_Core_DAO
::executeQuery($sql);
3817 $sumOfPayments = $query->sum_of_payments
;
3820 if ($contributionDAO->total_amount
== $sumOfPayments) {
3821 // update contribution status and
3822 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3823 $contributionDAO->contribution_status_id
= $statusId;
3824 $contributionDAO->cancel_date
= 'null';
3825 $contributionDAO->cancel_reason
= NULL;
3826 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3827 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3828 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3829 $contributionDAO->save();
3831 //Change status of financial record too
3832 $financialTrxn->status_id
= $statusId;
3833 $financialTrxn->save();
3835 // note : not using the self::add method,
3836 // the reason because it performs 'status change' related code execution for financial records
3837 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3838 // are coded below i.e. just updating financial_item status to 'Paid'
3840 if ($participantId) {
3841 // update participant status
3842 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3843 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3844 foreach ($ids as $val) {
3845 $participantUpdate['id'] = $val;
3846 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3847 CRM_Event_BAO_Participant
::add($participantUpdate);
3851 // update financial item statuses
3852 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3853 $paidStatus = array_search('Paid', $financialItemStatus);
3855 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3856 $sqlFinancialItemUpdate = "
3857 UPDATE civicrm_financial_item fi
3858 LEFT JOIN civicrm_entity_financial_trxn eft
3859 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3860 SET status_id = {$paidStatus}
3861 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3863 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3866 elseif ($paymentType == 'refund') {
3867 // build params for recording financial trxn entry
3868 $params['contribution'] = $contributionDAO;
3869 $params = array_merge($defaults, $params);
3870 $params['skipLineItem'] = TRUE;
3871 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3872 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3874 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3875 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3876 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3878 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3880 // note : not using the self::add method,
3881 // the reason because it performs 'status change' related code execution for financial records
3882 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3883 // are coded below i.e. just updating financial_item status to 'Paid'
3884 if ($updateStatus) {
3885 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3887 // add financial item entry
3888 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3889 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3890 if (!empty($lineItems)) {
3891 foreach ($lineItems as $lineItemId => $lineItemValue) {
3892 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3893 $addFinancialEntry = array(
3894 'transaction_date' => $financialTrxn->trxn_date
,
3895 'contact_id' => $contributionDAO->contact_id
,
3896 'amount' => round($paid, 2),
3897 'status_id' => array_search('Paid', $financialItemStatus),
3898 'entity_id' => $lineItemId,
3899 'entity_table' => 'civicrm_line_item',
3901 $trxnIds['id'] = $financialTrxn->id
;
3902 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3905 if ($participantId) {
3906 // update participant status
3907 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3908 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3909 foreach ($ids as $val) {
3910 $participantUpdate['id'] = $val;
3911 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3912 CRM_Event_BAO_Participant
::add($participantUpdate);
3917 // activity creation
3918 if (!empty($financialTrxn)) {
3919 if ($participantId) {
3920 $inputParams['id'] = $participantId;
3923 $component = 'event';
3924 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3925 $entityObj = $entityObj[$participantId];
3928 $entityObj = $contributionDAO;
3929 $component = 'contribution';
3931 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3933 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3935 return $financialTrxn;
3941 * @param $activityType
3943 * @param int $contributionId
3945 * @throws CRM_Core_Exception
3947 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3948 if ($component == 'event') {
3949 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3952 $title = ts('Contribution');
3954 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3955 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3956 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3957 $targetCid = $entityObj->contact_id
;
3958 // source record id would be the contribution id
3959 $srcRecId = $contributionId;
3962 $activityParams = array(
3963 'source_contact_id' => $targetCid,
3964 'source_record_id' => $srcRecId,
3965 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3969 'subject' => $subject,
3970 'activity_date_time' => $date,
3971 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3975 'skipRecentView' => TRUE,
3978 // create activity with target contacts
3979 $session = CRM_Core_Session
::singleton();
3980 $id = $session->get('userID');
3982 $activityParams['source_contact_id'] = $id;
3983 $activityParams['target_contact_id'][] = $targetCid;
3985 CRM_Activity_BAO_Activity
::create($activityParams);
3989 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3993 * @param bool $getTrxnInfo
3994 * @param bool $usingLineTotal
3998 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3999 if ($component == 'event') {
4000 $entity = 'participant';
4001 $entityTable = 'civicrm_participant';
4002 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4004 if (!$contributionId) {
4005 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4006 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4007 $id = $primaryParticipantId;
4009 if (!$contributionId) {
4015 $contributionId = $id;
4016 $entity = 'contribution';
4017 $entityTable = 'civicrm_contribution';
4020 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4021 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4023 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4024 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4026 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4027 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4030 $baseTrxnId = $total['trxn_id'];
4031 $total = $total['total_amount'];
4034 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4035 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4037 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
4038 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4039 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
4041 if ($paymentBalance == 0 && $contributionIsPayLater) {
4042 $paymentBalance = $total;
4045 $info['total'] = $total;
4046 $info['paid'] = $total - $paymentBalance;
4047 $info['balance'] = $paymentBalance;
4049 $info['component'] = $component;
4050 $info['payLater'] = $contributionIsPayLater;
4052 if ($getTrxnInfo && $baseTrxnId) {
4053 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4055 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4057 ft.payment_instrument_id,
4058 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4060 FROM civicrm_contribution con
4061 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4062 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4063 AND ft.to_financial_account_id != %2
4064 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4065 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4066 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4068 WHERE con.id = %1 AND ft.is_payment = 1
4070 $queryParams = array(
4071 1 => array($contributionId, 'Integer'),
4072 2 => array($feeFinancialAccount, 'Integer'),
4074 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4075 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4077 while ($resultDAO->fetch()) {
4078 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4079 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4081 'total_amount' => $resultDAO->total_amount
,
4082 'financial_type' => $resultDAO->financial_account
,
4083 'payment_instrument' => $paidByLabel,
4084 'receive_date' => $resultDAO->trxn_date
,
4085 'trxn_id' => $resultDAO->trxn_id
,
4086 'status' => $statuses[$resultDAO->status_id
],
4087 'currency' => $resultDAO->currency
,
4089 if ($paidByName == 'Check') {
4090 $val['check_number'] = $resultDAO->check_number
;
4094 $info['transaction'] = $rows;
4100 * Get financial account id has 'Sales Tax Account is' account relationship with financial type.
4102 * @param int $financialTypeId
4105 * Financial Account Id
4107 public static function getFinancialAccountId($financialTypeId) {
4108 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4109 $searchParams = array(
4110 'entity_table' => 'civicrm_financial_type',
4111 'entity_id' => $financialTypeId,
4112 'account_relationship' => $accountRel,
4115 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4117 return CRM_Utils_Array
::value('financial_account_id', $result);
4121 * Get the tax amount (misnamed function).
4123 * @param array $params
4124 * @param bool $isLineItem
4128 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4129 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4131 // Update contribution.
4132 if (!empty($params['id'])) {
4133 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4134 // there are no tax implications - early return.
4135 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4138 if (empty($params['prevContribution'])) {
4139 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4142 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4143 if (!isset($params[$field])) {
4144 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4145 // Tax amount gets added back on later....
4146 $params['total_amount'] = $params['prevContribution']->total_amount
-
4147 $params['prevContribution']->tax_amount
;
4150 $params[$field] = $params['prevContribution']->$field;
4151 if ($params[$field] != $params['prevContribution']->$field) {
4157 self
::calculateMissingAmountParams($params, $params['id']);
4158 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4159 // Assign tax Amount on update of contribution
4160 if (!empty($params['prevContribution']->tax_amount
)) {
4161 $params['tax_amount'] = 'null';
4162 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4163 foreach ($params['line_item'] as $setID => $priceField) {
4164 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4165 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4172 // New Contribution and update of contribution with tax rate financial type
4173 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4174 empty($params['skipLineItem']) && !$isLineItem
4176 $taxRateParams = $taxRates[$params['financial_type_id']];
4177 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4178 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4180 // Get Line Item on update of contribution
4181 if (isset($params['id'])) {
4182 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4185 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4187 foreach ($params['line_item'] as $setID => $priceField) {
4188 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4189 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4192 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4194 elseif (isset($params['api.line_item.create'])) {
4195 // Update total amount of contribution using lineItem
4196 $taxAmountArray = array();
4197 foreach ($params['api.line_item.create'] as $key => $value) {
4198 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4199 $taxRate = $taxRates[$value['financial_type_id']];
4200 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4201 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4204 $params['tax_amount'] = array_sum($taxAmountArray);
4205 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4208 // update line item of contrbution
4209 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4210 $taxRate = $taxRates[$params['financial_type_id']];
4211 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4212 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4219 * Check financial type validation on update of a contribution.
4221 * @param Integer $financialTypeId
4222 * Value of latest Financial Type.
4224 * @param Integer $contributionId
4227 * @param array $errors
4232 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4233 if (!empty($financialTypeId)) {
4234 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4235 if ($oldFinancialTypeId == $financialTypeId) {
4239 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4241 '1' => array($contributionId, 'Integer'),
4243 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4244 if ($result->N
> 1) {
4245 $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.');
4250 * Update related pledge payment payments.
4252 * This function has been refactored out of the back office contribution form and may
4253 * still overlap with other functions.
4255 * @param string $action
4256 * @param int $pledgePaymentID
4257 * @param int $contributionID
4258 * @param bool $adjustTotalAmount
4259 * @param float $total_amount
4260 * @param float $original_total_amount
4261 * @param int $contribution_status_id
4262 * @param int $original_contribution_status_id
4264 public static function updateRelatedPledge(
4270 $original_total_amount,
4271 $contribution_status_id,
4272 $original_contribution_status_id
4274 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4278 if ($pledgePaymentID) {
4279 //store contribution id in payment record.
4280 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4283 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4290 if (!$pledgePaymentID) {
4293 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4299 $updatePledgePaymentStatus = FALSE;
4301 // If either the status or the amount has changed we update the pledge status.
4302 if ($action & CRM_Core_Action
::ADD
) {
4303 $updatePledgePaymentStatus = TRUE;
4305 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4306 ($original_total_amount != $total_amount))
4308 $updatePledgePaymentStatus = TRUE;
4311 if ($updatePledgePaymentStatus) {
4312 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4313 array($pledgePaymentID),
4314 $contribution_status_id,
4323 * Compute the stats values
4325 * @param string $stat either 'mode' or 'median'
4326 * @param string $sql
4327 * @param string $alias of civicrm_contribution
4329 * @return array|null
4331 public static function computeStats($stat, $sql, $alias = NULL) {
4332 $mode = $median = array();
4335 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4336 while ($modeDAO->fetch()) {
4337 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4338 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4347 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4348 foreach ($currencies as $currency => $val) {
4350 $where = "AND {$alias}.currency = '{$currency}'";
4351 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4355 $medianRow = floor($rowCount / 2);
4356 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4362 $medianValue = "SELECT {$alias}.total_amount as median
4364 ORDER BY median LIMIT {$medianRow},{$offset}";
4365 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4366 while ($medianValDAO->fetch()) {
4368 $midValue = $midValue +
$medianValDAO->median
;
4371 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4375 $midValue = $midValue / 2;
4376 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4387 * Is there only one line item attached to the contribution.
4393 * @throws \CiviCRM_API3_Exception
4395 public static function isSingleLineItem($id) {
4396 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4397 return ($lineItemCount == 1);
4401 * Complete an order.
4403 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4405 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4407 * Moving it out of the BaseIPN class is just the first step.
4409 * @param array $input
4411 * @param array $objects
4412 * @param CRM_Core_Transaction $transaction
4414 * @param CRM_Contribute_BAO_Contribution $contribution
4415 * @param bool $isRecurring
4416 * Duplication of param needs review. Only used by AuthorizeNetIPN
4417 * @param int $isFirstOrLastRecurringPayment
4418 * Deprecated param only used by AuthorizeNetIPN.
4422 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4423 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4424 // The previous details are used when calculating line items so keep it before any code that 'does something'
4425 if (!empty($contribution->id
)) {
4426 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4427 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4429 $inputContributionWhiteList = array(
4434 'payment_instrument_id',
4439 'contribution_status_id',
4441 if (self
::isSingleLineItem($primaryContributionID)) {
4442 $inputContributionWhiteList[] = 'financial_type_id';
4445 $participant = CRM_Utils_Array
::value('participant', $objects);
4446 $memberships = CRM_Utils_Array
::value('membership', $objects);
4447 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4448 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4449 $event = CRM_Utils_Array
::value('event', $objects);
4451 $paymentProcessorId = '';
4452 if (isset($objects['paymentProcessor'])) {
4453 if (is_array($objects['paymentProcessor'])) {
4454 $paymentProcessorId = $objects['paymentProcessor']['id'];
4457 $paymentProcessorId = $objects['paymentProcessor']->id
;
4461 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4463 $contributionParams = array_merge(array(
4464 'contribution_status_id' => $completedContributionStatusID,
4465 'source' => self
::getRecurringContributionDescription($contribution, $event),
4466 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4468 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4470 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4471 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4472 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4473 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4476 if ($recurringContributionID) {
4477 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4479 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4481 if (empty($contributionParams['receive_date']) && $changeDate) {
4482 $contributionParams['receive_date'] = $changeDate;
4485 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4486 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4488 if (is_numeric($memberships)) {
4489 $memberships = array($objects['membership']);
4493 if (isset($input['is_email_receipt'])) {
4494 $values['is_email_receipt'] = $input['is_email_receipt'];
4497 if ($input['component'] == 'contribute') {
4498 if ($contribution->contribution_page_id
) {
4499 // Figure out what we gain from this.
4500 // Note that we may have overwritten the is_email_receipt input, fix that below.
4501 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4503 elseif ($recurContrib && $recurringContributionID) {
4504 $values['amount'] = $recurContrib->amount
;
4505 $values['financial_type_id'] = $objects['contributionType']->id
;
4506 $values['title'] = $source = ts('Offline Recurring Contribution');
4509 if (isset($input['is_email_receipt'])) {
4510 // CRM-19601 - we may have overwritten this above.
4511 $values['is_email_receipt'] = $input['is_email_receipt'];
4513 elseif ($recurContrib && $recurringContributionID) {
4514 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4515 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4516 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4519 if (!empty($memberships)) {
4520 foreach ($memberships as $membershipTypeIdKey => $membership) {
4522 $membershipParams = array(
4523 'id' => $membership->id
,
4524 'contact_id' => $membership->contact_id
,
4525 'is_test' => $membership->is_test
,
4526 'membership_type_id' => $membership->membership_type_id
,
4529 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4530 $membershipParams['membership_type_id'],
4531 $membershipParams['is_test'],
4532 $membershipParams['id']
4535 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4536 // this picks up membership type changes during renewals
4538 SELECT membership_type_id
4539 FROM civicrm_membership_log
4540 WHERE membership_id={$membershipParams['id']}
4543 $dao = CRM_Core_DAO
::executeQuery($sql);
4544 if ($dao->fetch()) {
4545 if (!empty($dao->membership_type_id
)) {
4546 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4551 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4552 $membershipParams['membership_type_id'],
4553 $primaryContributionID
4555 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4556 if ($currentMembership) {
4558 * Fixed FOR CRM-4433
4559 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4560 * when Contribution mode is notify and membership is for renewal )
4562 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4564 // @todo - we should pass membership_type_id instead of null here but not
4565 // adding as not sure of testing
4566 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4567 $changeDate, NULL, $membershipParams['num_terms']
4570 $dates['join_date'] = $currentMembership['join_date'];
4573 //get the status for membership.
4574 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4576 $dates['join_date'],
4579 $membershipParams['membership_type_id'],
4583 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4584 //we might be renewing membership,
4585 //so make status override false.
4586 $membershipParams['is_override'] = FALSE;
4587 //CRM-17723 - reset static $relatedContactIds array()
4589 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4590 civicrm_api3('Membership', 'create', $membershipParams);
4591 //CRM-19600: Add Membership Renewal activity
4592 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Renewal', $membership->contact_id
);
4598 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4599 if ($event->is_email_confirm
) {
4600 // @todo this should be set by the function that sends the mail after sending.
4601 $contributionParams['receipt_date'] = $changeDate;
4603 $participantParams['id'] = $participant->id
;
4604 $participantParams['status_id'] = 'Registered';
4605 civicrm_api3('Participant', 'create', $participantParams);
4609 $contributionParams['id'] = $contribution->id
;
4611 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4612 // unsetting it here does NOT cause any other contribution test to fail!
4613 unset($contributionParams['financial_type_id']);
4614 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4616 // Add new soft credit against current $contribution.
4617 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4618 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4621 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4622 'labelColumn' => 'name',
4625 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4626 $input['payment_processor'] = $paymentProcessorId;
4629 if (!empty($contribution->_relatedObjects
['participant'])) {
4630 $input['contribution_mode'] = 'participant';
4631 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4633 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4634 $input['contribution_mode'] = 'membership';
4635 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4636 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4637 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4640 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4641 $transaction->commit();
4643 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4644 $contributionParams['contribution_status_id'], $input['amount']);
4646 // create an activity record
4647 if ($input['component'] == 'contribute') {
4649 $targetContactID = NULL;
4650 if (!empty($ids['related_contact'])) {
4651 $targetContactID = $contribution->contact_id
;
4652 $contribution->contact_id
= $ids['related_contact'];
4654 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4658 CRM_Activity_BAO_Activity
::addActivity($participant);
4661 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4662 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4663 if (!array_key_exists('is_email_receipt', $values) ||
4664 $values['is_email_receipt'] == 1
4666 civicrm_api3('Contribution', 'sendconfirmation', array(
4667 'id' => $contribution->id
,
4668 'payment_processor_id' => $paymentProcessorId,
4670 CRM_Core_Error
::debug_log_message("Receipt sent");
4673 CRM_Core_Error
::debug_log_message("Success: Database updated");
4675 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4676 $isFirstOrLastRecurringPayment);
4678 return $contributionResult;
4682 * Send receipt from contribution.
4684 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4686 * Note that the compose message part has been moved to contribution
4687 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4689 * @param array $input
4690 * Incoming data from Payment processor.
4692 * Related object IDs.
4693 * @param int $contributionID
4694 * @param array $values
4695 * Values related to objects that have already been loaded.
4696 * @param bool $recur
4697 * Is it part of a recurring contribution.
4698 * @param bool $returnMessageText
4699 * Should text be returned instead of sent. This.
4700 * is because the function is also used to generate pdfs
4703 * @throws \CRM_Core_Exception
4704 * @throws \CiviCRM_API3_Exception
4706 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4707 $returnMessageText = FALSE) {
4708 $input['is_recur'] = $recur;
4710 $contribution = new CRM_Contribute_BAO_Contribution();
4711 $contribution->id
= $contributionID;
4712 if (!$contribution->find(TRUE)) {
4713 throw new CRM_Core_Exception('Contribution does not exist');
4715 $contribution->loadRelatedObjects($input, $ids, TRUE);
4716 // set receipt from e-mail and name in value
4717 if (!$returnMessageText) {
4718 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4720 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4721 // Contribution ID should really always be set. But ?
4722 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4723 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4729 * Generate From email and from name in an array values
4731 public static function generateFromEmailAndName($input, $contribution) {
4732 // Use input valuse if supplied.
4733 if (!empty($input['receipt_from_email'])) {
4734 return array(CRM_Utils_array
::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4736 // if we are still empty see if we can use anything from a contribution page.
4737 $pageValues = array();
4738 if (!empty($contribution->contribution_page_id
)) {
4739 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id
));
4741 // if we are still empty see if we can use anything from a contribution page.
4742 if (!empty($pageValues['receipt_from_email'])) {
4743 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4745 // If we are still empty fall back to the domain.
4746 $domain = civicrm_api3('domain', 'getsingle', array('id' => CRM_Core_Config
::domainID()));
4747 if (!empty($domain['from_email'])) {
4748 return array($domain['from_name'], $domain['from_email']);
4750 if (!empty($domain['domain_email'])) {
4751 return array($domain['name'], $domain['domain_email']);
4753 $userID = CRM_Core_Session
::singleton()->getLoggedInContactID();
4756 if (!empty($userID)) {
4757 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4759 // If still empty fall back to the logged in user details.
4760 // return empty values no matter what.
4761 return array($userName, $userEmail);
4765 * Generate credit note id with next avaible number
4770 public static function createCreditNoteId() {
4771 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4773 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4774 $creditNoteId = NULL;
4778 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4779 $result = civicrm_api3('Contribution', 'getcount', array(
4781 'creditnote_id' => $creditNoteId,
4783 } while ($result > 0);
4785 return $creditNoteId;
4789 * Load related memberships.
4791 * Note that in theory it should be possible to retrieve these from the line_item table
4792 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4793 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4794 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4795 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4797 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4803 public function loadRelatedMembershipObjects(&$ids) {
4805 SELECT membership_id
4806 FROM civicrm_membership_payment
4807 WHERE contribution_id = %1 ";
4808 $params = array(1 => array($this->id
, 'Integer'));
4809 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, array());
4811 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4812 while ($dao->fetch()) {
4813 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4814 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4818 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4819 foreach ($ids['membership'] as $id) {
4821 $membership = new CRM_Member_BAO_Membership();
4822 $membership->id
= $id;
4823 if (!$membership->find(TRUE)) {
4824 throw new Exception("Could not find membership record: $id");
4826 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4827 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4828 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4829 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4830 $membership->free();
4837 * This function is used to record partial payments for contribution
4839 * @param array $contribution
4841 * @param array $params
4845 public static function recordPartialPayment($contribution, $params) {
4846 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4847 $pendingStatus = array(
4848 array_search('Pending', $contributionStatuses),
4849 array_search('In Progress', $contributionStatuses),
4851 $statusId = array_search('Completed', $contributionStatuses);
4852 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4853 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4854 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4856 elseif (!empty($params['payment_processor'])) {
4857 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4859 elseif (!empty($params['payment_instrument_id'])) {
4860 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4863 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4864 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4865 $balanceTrxnParams['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);
4867 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4868 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4869 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4870 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4871 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4872 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4873 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4874 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4875 $balanceTrxnParams['currency'] = $contribution['currency'];
4876 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4877 $balanceTrxnParams['status_id'] = $statusId;
4878 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4879 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4880 if ($fromFinancialAccountId != NULL &&
4881 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4883 $balanceTrxnParams['is_payment'] = 1;
4885 if (!empty($params['payment_processor'])) {
4886 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4888 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4892 * Get the description (source field) for the recurring contribution.
4894 * @param CRM_Contribute_BAO_Contribution $contribution
4895 * @param CRM_Event_DAO_Event|null $event
4898 * @throws \CiviCRM_API3_Exception
4900 protected static function getRecurringContributionDescription($contribution, $event) {
4901 if (!empty($contribution->source
)) {
4902 return $contribution->source
;
4904 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4905 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4906 'id' => $contribution->contribution_page_id
,
4907 'return' => 'title',
4909 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4912 return ts('Online Event Registration') . ': ' . $event->title
;
4914 elseif (!empty($contribution->contribution_recur_id
)) {
4915 return 'recurring contribution';
4921 * Function to add payments for contribution
4922 * for Partially Paid status
4924 * @param array $contributions
4925 * @param array $contributionStatusId
4928 public static function addPayments($contributions, $contributionStatusId = NULL) {
4929 // get financial trxn which is a payment
4930 $ftSql = "SELECT ft.id, ft.total_amount
4931 FROM civicrm_financial_trxn ft
4932 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4933 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4934 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4935 'labelColumn' => 'name',
4937 foreach ($contributions as $k => $contribution) {
4938 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4939 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4943 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4946 // store financial item Proportionaly.
4947 $trxnParams = array(
4948 'total_amount' => $ftDao->total_amount
,
4949 'contribution_id' => $contribution->id
,
4951 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4956 * Function use to store line item proportionaly in
4957 * in entity financial trxn table
4959 * @param array $trxnParams
4961 * @param Integer $trxnId
4963 * @param float $contributionTotalAmount
4966 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4967 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4968 if (!empty($lineItems)) {
4969 // get financial item
4970 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4971 $entityParams = array(
4972 'contribution_total_amount' => $contributionTotalAmount,
4973 'trxn_total_amount' => $trxnParams['total_amount'],
4974 'trxn_id' => $trxnId,
4976 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4981 * Function to check line items.
4983 * @param array $params
4984 * array of order params.
4986 * @throws \API_Exception
4988 public static function checkLineItems(&$params) {
4989 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4990 $lineItemAmount = 0;
4991 foreach ($params['line_items'] as &$lineItems) {
4992 foreach ($lineItems['line_item'] as &$item) {
4993 if (empty($item['financial_type_id'])) {
4994 $item['financial_type_id'] = $params['financial_type_id'];
4996 $lineItemAmount +
= $item['line_total'];
4999 if (!isset($totalAmount)) {
5000 $params['total_amount'] = $lineItemAmount;
5002 elseif ($totalAmount != $lineItemAmount) {
5003 throw new API_Exception("Line item total doesn't match with total amount.");
5008 * Get the financial account for the item associated with the new transaction.
5010 * @param array $params
5011 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
5015 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
5017 if (!empty($params['financial_account_id'])) {
5018 return $params['financial_account_id'];
5020 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5021 $preferredAccountsRelationships = array(
5022 'Refunded' => 'Credit/Contra Revenue Account is',
5023 'Chargeback' => 'Chargeback Account is',
5025 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5026 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5027 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5029 $preferredAccountsRelationships[$contributionStatus]
5032 return $prevFinancialItem->financial_account_id
;
5036 * ContributionPage values were being imposed onto values.
5038 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5039 * REALLY didn't want superimposed. The rest are left there in their overkill out
5042 * The rationale for making this explicit is that it was a case of carefully set values being
5043 * seemingly randonly overwritten without much care. In general I think array randomly setting
5044 * variables en mass is risky.
5046 * @param array $values
5050 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5051 $contributionPageValues = array();
5052 CRM_Contribute_BAO_ContributionPage
::setValues(
5053 $this->contribution_page_id
,
5054 $contributionPageValues
5056 $valuesToCopy = array(
5057 // These are the values that I believe to be useful.
5061 'pay_later_receipt',
5063 'receipt_from_email',
5064 'receipt_from_name',
5068 'honoree_profile_id',
5069 'onbehalf_profile_id',
5070 'honor_block_is_active',
5071 // Kinda might be - but would be on the contribution...
5074 // Included for 'fear of regression' but can't justify any use for these....
5076 'payment_processor',
5077 'financial_type_id',
5078 'amount_block_is_active',
5083 'default_amount_id',
5087 'initial_amount_help_text',
5088 'initial_amount_label',
5090 'is_allow_other_amount',
5091 'is_billing_required',
5092 'is_confirm_enabled',
5093 'is_credit_card_only',
5095 'is_partial_payment',
5096 'is_recur_installments',
5097 'is_recur_interval',
5101 'min_initial_amount',
5102 'recur_frequency_unit',
5109 foreach ($valuesToCopy as $valueToCopy) {
5110 if (isset($contributionPageValues[$valueToCopy])) {
5111 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5118 * Get values of CiviContribute Settings
5119 * and check if its enabled or not.
5120 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5121 * in serialized form. Usually this should be stored as flat settings for each form fields
5122 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5123 * settings we will live with an inconsistency because it's too hard to change for now.
5124 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5127 * @param string $name
5131 public static function checkContributeSettings($name = NULL) {
5132 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5135 return CRM_Utils_Array
::value($name, $contributeSettings);
5137 return $contributeSettings;
5141 * This function process contribution related objects.
5143 * @param int $contributionId
5144 * @param int $statusId
5145 * @param int|null $previousStatusId
5147 * @param string $receiveDate
5149 * @return null|string
5151 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5153 if (!$contributionId ||
!$statusId) {
5158 'contribution_id' => $contributionId,
5159 'contribution_status_id' => $statusId,
5160 'previous_contribution_status_id' => $previousStatusId,
5161 'receive_date' => $receiveDate,
5164 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5166 if (!is_array($updateResult) ||
5167 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5168 !is_array($updatedComponents) ||
5169 empty($updatedComponents)
5174 // get the user display name.
5176 SELECT display_name as displayName
5177 FROM civicrm_contact
5178 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5179 WHERE civicrm_contribution.id = {$contributionId}";
5180 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5182 // get the status message for user.
5183 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5185 if ($componentName == 'CiviMember') {
5186 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5187 CRM_Member_PseudoConstant
::membershipStatus()
5189 if ($updatedStatusName == 'Cancelled') {
5190 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5192 elseif ($updatedStatusName == 'Expired') {
5193 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5196 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5198 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5200 1 => $userDisplayName,
5208 if ($componentName == 'CiviEvent') {
5209 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5210 CRM_Event_PseudoConstant
::participantStatus()
5212 if ($updatedStatusName == 'Cancelled') {
5213 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5215 elseif ($updatedStatusName == 'Registered') {
5216 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5220 if ($componentName == 'CiviPledge') {
5221 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5222 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5224 if ($updatedStatusName == 'Cancelled') {
5225 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5227 elseif ($updatedStatusName == 'Failed') {
5228 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5230 elseif ($updatedStatusName == 'Completed') {
5231 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5240 * Get the contribution as it is in the database before being updated.
5242 * @param int $contributionID
5246 private static function getOriginalContribution($contributionID) {
5247 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5251 * Assign Test Value.
5253 * @param string $fieldName
5254 * @param array $fieldDef
5255 * @param int $counter
5257 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5258 if ($fieldName == 'tax_amount') {
5259 $this->{$fieldName} = "0.00";
5261 elseif ($fieldName == 'net_amount') {
5262 $this->{$fieldName} = "2.00";
5264 elseif ($fieldName == 'total_amount') {
5265 $this->{$fieldName} = "3.00";
5267 elseif ($fieldName == 'fee_amount') {
5268 $this->{$fieldName} = "1.00";
5271 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5276 * Check if contribution has participant/membership payment.
5278 * @param int $contributionId
5283 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5284 // get line item for contribution
5285 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5286 // check if line item is for membership or participant
5287 foreach ($lineItems as $items) {
5288 if ($items['entity_table'] == 'civicrm_participant') {
5292 elseif ($items['entity_table'] == 'civicrm_membership') {
5304 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5306 * @param array $trxnParams
5307 * Financial trxn params
5308 * @param string $contributionParams
5309 * Contribution Params
5313 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5314 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5317 $statusId = $contributionParams['contribution']->contribution_status_id
;
5318 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5319 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5320 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5321 // Return if contribution status is not completed.
5322 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5323 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5324 && $contributionParams['prevContribution']->is_pay_later
== 0
5330 $params = $trxnParams;
5331 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5332 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
5333 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
5334 $params['to_financial_account_id'] = $arAccountId;
5335 $params['status_id'] = array_search('Pending', $contributionStatuses);
5336 $params['is_payment'] = FALSE;
5337 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5338 self
::$_trxnIDs[] = $trxn->id
;
5339 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5343 * Calculate financial item amount when contribution is updated.
5345 * @param array $params
5346 * contribution params
5347 * @param array $amountParams
5349 * @param string $context
5353 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5354 if (!empty($params['is_quick_config'])) {
5355 $amount = $amountParams['item_amount'];
5357 $amount = $params['total_amount'];
5358 if ($context === NULL) {
5359 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5364 $amount = $amountParams['line_total'];
5365 if ($context == 'changedAmount') {
5366 $amount -= $amountParams['previous_line_total'];
5368 $amount *= $amountParams['diff'];
5374 * Calculate net amount.
5376 * @param array $netAmount
5378 * @param float $taxAmount
5382 public static function calculateNetAmount($netAmount, $taxAmount) {
5384 $netAmount -= $taxAmount;
5386 return CRM_Utils_Money
::format($netAmount, NULL, '%a');
5390 * Retrieve Sales Tax Financial Accounts.
5396 public static function getSalesTaxFinancialAccounts() {
5397 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5398 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5399 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5400 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5401 $queryParams = array(1 => array($accountRel, 'Integer'));
5402 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5403 $financialAccount = array();
5404 while ($dao->fetch()) {
5405 $financialAccount[$dao->id
] = $dao->id
;
5407 return $financialAccount;
5411 * Create tax entry in civicrm_entity_financial_trxn table.
5413 * @param array $entityParams
5415 * @param array $eftParams
5418 public static function createProportionalEntry($entityParams, $eftParams) {
5419 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5420 // Record Entity Financial Trxn; CRM-20145
5421 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5422 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5426 * Create array of last financial item id's.
5428 * @param int $contributionId
5432 public static function getLastFinancialItemIds($contributionId) {
5433 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5434 FROM civicrm_financial_item fi
5435 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5436 WHERE li.contribution_id = %1";
5437 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5438 $ftIds = $taxItems = array();
5439 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5440 while ($dao->fetch()) {
5441 /* if sales tax item*/
5442 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5443 $taxItems[$dao->price_field_value_id
] = array(
5444 'financial_item_id' => $dao->id
,
5445 'amount' => $dao->tax_amount
,
5449 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5452 return array($ftIds, $taxItems);
5456 * Create proportional entries in civicrm_entity_financial_trxn.
5458 * @param array $entityParams
5460 * @param array $lineItems
5462 * @param array $ftIds
5464 * @param array $taxItems
5467 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5469 'entity_table' => 'civicrm_financial_item',
5470 'financial_trxn_id' => $entityParams['trxn_id'],
5472 foreach ($lineItems as $key => $value) {
5473 if ($value['qty'] == 0) {
5476 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5477 $entityParams['line_item_amount'] = $value['line_total'];
5478 self
::createProportionalEntry($entityParams, $eftParams);
5479 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5480 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5481 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5482 self
::createProportionalEntry($entityParams, $eftParams);