3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 $contributionRecurId = array(
829 'contribution_recur_id' => array(
830 'title' => ts('Recurring Contributions ID'),
831 'name' => 'contribution_recur_id',
832 'where' => 'civicrm_contribution.contribution_recur_id',
833 'data_type' => CRM_Utils_Type
::T_INT
,
837 $extraFields = array(
838 'contribution_batch' => array(
839 'title' => ts('Batch Name'),
844 $campaignTitle = array(
845 'contribution_campaign_title' => array(
846 'title' => ts('Campaign Title'),
847 'name' => 'campaign_title',
848 'where' => 'civicrm_campaign.title',
849 'data_type' => CRM_Utils_Type
::T_STRING
,
852 $softCreditFields = array(
853 'contribution_soft_credit_name' => array(
854 'name' => 'contribution_soft_credit_name',
855 'title' => 'Soft Credit For',
856 'where' => 'civicrm_contact_d.display_name',
857 'data_type' => CRM_Utils_Type
::T_STRING
,
859 'contribution_soft_credit_amount' => array(
860 'name' => 'contribution_soft_credit_amount',
861 'title' => 'Soft Credit Amount',
862 'where' => 'civicrm_contribution_soft.amount',
863 'data_type' => CRM_Utils_Type
::T_MONEY
,
865 'contribution_soft_credit_type' => array(
866 'name' => 'contribution_soft_credit_type',
867 'title' => 'Soft Credit Type',
868 'where' => 'contribution_softcredit_type.label',
869 'data_type' => CRM_Utils_Type
::T_STRING
,
871 'contribution_soft_credit_contribution_id' => array(
872 'name' => 'contribution_soft_credit_contribution_id',
873 'title' => 'Soft Credit For Contribution ID',
874 'where' => 'civicrm_contribution_soft.contribution_id',
875 'data_type' => CRM_Utils_Type
::T_INT
,
877 'contribution_soft_credit_contact_id' => array(
878 'name' => 'contribution_soft_credit_contact_id',
879 'title' => 'Soft Credit For Contact ID',
880 'where' => 'civicrm_contact_d.id',
881 'data_type' => CRM_Utils_Type
::T_INT
,
885 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
887 'contribution_product_id' => array(
888 'title' => ts('Premium'),
889 'name' => 'contribution_product_id',
890 'where' => 'civicrm_product.id',
891 'data_type' => CRM_Utils_Type
::T_INT
,
895 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
896 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
897 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
900 self
::$_exportableFields = $fields;
903 return self
::$_exportableFields;
907 * @param null $status
908 * @param null $startDate
909 * @param null $endDate
913 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
917 $where[] = 'contribution_status_id = 1';
921 $where[] = 'contribution_status_id = 3';
926 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
929 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
931 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
932 if ($financialTypes) {
933 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
934 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
937 $where[] = "c.financial_type_id IN (0)";
940 $whereCond = implode(' AND ', $where);
943 SELECT sum( total_amount ) as total_amount,
944 count( c.id ) as total_count,
946 FROM civicrm_contribution c
947 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
948 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
950 AND ( is_test = 0 OR is_test IS NULL )
951 AND contact.is_deleted = 0
955 $dao = CRM_Core_DAO
::executeQuery($query);
958 while ($dao->fetch()) {
959 $count +
= $dao->total_count
;
960 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
964 'amount' => implode(', ', $amount),
972 * Delete the indirect records associated with this contribution first.
977 * $results no of deleted Contribution on success, false otherwise
979 public static function deleteContribution($id) {
980 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
982 $transaction = new CRM_Core_Transaction();
985 //delete activity record
987 'source_record_id' => $id,
988 // activity type id for contribution
989 'activity_type_id' => 6,
992 CRM_Activity_BAO_Activity
::deleteActivity($params);
994 //delete billing address if exists for this contribution.
995 self
::deleteAddress($id);
997 //update pledge and pledge payment, CRM-3961
998 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
1000 // remove entry from civicrm_price_set_entity, CRM-5095
1001 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
1002 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
1004 // cleanup line items.
1005 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
1007 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
1008 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1010 if ($participantId) {
1011 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1014 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1018 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1019 $noteId = key($note);
1021 CRM_Core_BAO_Note
::del($noteId, FALSE);
1024 $dao = new CRM_Contribute_DAO_Contribution();
1027 $results = $dao->delete();
1029 $transaction->commit();
1031 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1033 // delete the recently created Contribution
1034 $contributionRecent = array(
1036 'type' => 'Contribution',
1038 CRM_Utils_Recent
::del($contributionRecent);
1044 * React to a financial transaction (payment) failure.
1046 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1047 * payments is important for forensic and outreach reasons.
1049 * @param int $contributionID
1050 * @param int $contactID
1051 * @param string $message
1053 * @throws \CiviCRM_API3_Exception
1055 public static function failPayment($contributionID, $contactID, $message) {
1056 civicrm_api3('activity', 'create', array(
1057 'activity_type_id' => 'Failed Payment',
1058 'details' => $message,
1059 'subject' => ts('Payment failed at payment processor'),
1060 'source_record_id' => $contributionID,
1061 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1067 * Check if there is a contribution with the same trxn_id or invoice_id.
1069 * @param array $input
1070 * An assoc array of name/value pairs.
1071 * @param array $duplicates
1072 * (reference) store ids of duplicate contribs.
1076 * true if duplicate, false otherwise
1078 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1080 $id = CRM_Utils_Array
::value('id', $input);
1082 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1083 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1089 $clause[] = "trxn_id = %1";
1090 $input[1] = array($trxn_id, 'String');
1094 $clause[] = "invoice_id = %2";
1095 $input[2] = array($invoice_id, 'String');
1098 if (empty($clause)) {
1102 $clause = implode(' OR ', $clause);
1104 $clause = "( $clause ) AND id != %3";
1105 $input[3] = array($id, 'Integer');
1108 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1109 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1111 while ($dao->fetch()) {
1112 $duplicates[] = $dao->id
;
1119 * Takes an associative array and creates a contribution_product object.
1121 * the function extract all the params it needs to initialize the create a
1122 * contribution_product object. the params array could contain additional unused name/value
1125 * @param array $params
1126 * (reference) an assoc array of name/value pairs.
1128 * @return CRM_Contribute_DAO_ContributionProduct
1130 public static function addPremium(&$params) {
1131 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1132 $contributionProduct->copyValues($params);
1133 return $contributionProduct->save();
1137 * Get list of contribution fields for profile.
1138 * For now we only allow custom contribution fields to be in
1141 * @param bool $addExtraFields
1142 * True if special fields needs to be added.
1145 * the list of contribution fields
1147 public static function getContributionFields($addExtraFields = TRUE) {
1148 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1149 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1151 if ($addExtraFields) {
1152 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1155 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1157 foreach ($contributionFields as $key => $var) {
1158 if ($key == 'contribution_contact_id') {
1161 elseif ($key == 'contribution_campaign_id') {
1162 $var['title'] = ts('Campaign');
1164 $fields[$key] = $var;
1167 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1172 * Add extra fields specific to contribution.
1174 public static function getSpecialContributionFields() {
1175 $extraFields = array(
1176 'contribution_soft_credit_name' => array(
1177 'name' => 'contribution_soft_credit_name',
1178 'title' => 'Soft Credit Name',
1179 'headerPattern' => '/^soft_credit_name$/i',
1180 'where' => 'civicrm_contact_d.display_name',
1182 'contribution_soft_credit_email' => array(
1183 'name' => 'contribution_soft_credit_email',
1184 'title' => 'Soft Credit Email',
1185 'headerPattern' => '/^soft_credit_email$/i',
1186 'where' => 'soft_email.email',
1188 'contribution_soft_credit_phone' => array(
1189 'name' => 'contribution_soft_credit_phone',
1190 'title' => 'Soft Credit Phone',
1191 'headerPattern' => '/^soft_credit_phone$/i',
1192 'where' => 'soft_phone.phone',
1194 'contribution_soft_credit_contact_id' => array(
1195 'name' => 'contribution_soft_credit_contact_id',
1196 'title' => 'Soft Credit Contact ID',
1197 'headerPattern' => '/^soft_credit_contact_id$/i',
1198 'where' => 'civicrm_contribution_soft.contact_id',
1200 'contribution_pcp_title' => array(
1201 'name' => 'contribution_pcp_title',
1202 'title' => 'Personal Campaign Page Title',
1203 'headerPattern' => '/^contribution_pcp_title$/i',
1204 'where' => 'contribution_pcp.title',
1208 return $extraFields;
1212 * @param int $pageID
1216 public static function getCurrentandGoalAmount($pageID) {
1218 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1219 FROM civicrm_contribution_page p,
1220 civicrm_contribution c
1221 WHERE p.id = c.contribution_page_id
1223 AND c.cancel_date is null
1227 $config = CRM_Core_Config
::singleton();
1228 $params = array(1 => array($pageID, 'Integer'));
1229 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1231 if ($dao->fetch()) {
1232 return array($dao->goal
, $dao->total
);
1235 return array(NULL, NULL);
1240 * Get list of contributions which credit the passed in contact ID.
1242 * The returned array provides details about the original contribution & donor.
1244 * @todo - this is a confusing function called from one place. It has a test. It would be
1245 * nice to deprecate it.
1247 * @param int $honorId
1248 * In Honor of Contact ID.
1251 * list of contribution fields
1253 public static function getHonorContacts($honorId) {
1255 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1256 $honorDAO->contact_id
= $honorId;
1259 $type = CRM_Contribute_PseudoConstant
::financialType();
1261 while ($honorDAO->fetch()) {
1262 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1263 $contributionDAO->id
= $honorDAO->contribution_id
;
1265 if ($contributionDAO->find(TRUE)) {
1266 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1267 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1268 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1269 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1270 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1271 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1272 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1273 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1274 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1282 * Get the sort name of a contact for a particular contribution.
1285 * Id of the contribution.
1287 * @return null|string
1288 * sort name of the contact if found
1290 public static function sortName($id) {
1291 $id = CRM_Utils_Type
::escape($id, 'Integer');
1294 SELECT civicrm_contact.sort_name
1295 FROM civicrm_contribution, civicrm_contact
1296 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1297 AND civicrm_contribution.id = {$id}
1299 return CRM_Core_DAO
::singleValueQuery($query);
1303 * @param int $contactID
1307 public static function annual($contactID) {
1308 if (is_array($contactID)) {
1309 $contactIDs = implode(',', $contactID);
1312 $contactIDs = $contactID;
1315 $config = CRM_Core_Config
::singleton();
1316 $startDate = $endDate = NULL;
1318 $currentMonth = date('m');
1319 $currentDay = date('d');
1320 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1321 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1322 (int ) $config->fiscalYearStart
['d'] > $currentDay
1325 $year = date('Y') - 1;
1330 $nextYear = $year +
1;
1332 if ($config->fiscalYearStart
) {
1333 $newFiscalYearStart = $config->fiscalYearStart
;
1334 if ($newFiscalYearStart['M'] < 10) {
1335 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1337 if ($newFiscalYearStart['d'] < 10) {
1338 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1340 $config->fiscalYearStart
= $newFiscalYearStart;
1341 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1346 $startDate = "$year$monthDay";
1347 $endDate = "$nextYear$monthDay";
1348 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1349 $additionalWhere = " AND b.financial_type_id IN (0)";
1350 $liWhere = " AND i.financial_type_id IN (0)";
1351 if (!empty($financialTypes)) {
1352 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1353 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1356 SELECT count(*) as count,
1357 sum(total_amount) as amount,
1358 avg(total_amount) as average,
1360 FROM civicrm_contribution b
1361 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1362 WHERE b.contact_id IN ( $contactIDs )
1363 AND b.contribution_status_id = 1
1365 AND b.receive_date >= $startDate
1366 AND b.receive_date < $endDate
1370 $dao = CRM_Core_DAO
::executeQuery($query);
1372 $amount = $average = array();
1373 while ($dao->fetch()) {
1374 if ($dao->count
> 0 && $dao->amount
> 0) {
1375 $count +
= $dao->count
;
1376 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1377 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1383 implode(', ', $amount),
1384 implode(', ', $average),
1387 return array(0, 0, 0);
1391 * Check if there is a contribution with the params passed in.
1393 * Used for trxn_id,invoice_id and contribution_id
1395 * @param array $params
1396 * An assoc array of name/value pairs.
1399 * contribution id if success else NULL
1401 public static function checkDuplicateIds($params) {
1402 $dao = new CRM_Contribute_DAO_Contribution();
1406 foreach ($params as $k => $v) {
1408 $clause[] = "$k = '$v'";
1411 $clause = implode(' AND ', $clause);
1412 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1413 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1415 while ($dao->fetch()) {
1423 * Get the contribution details for component export.
1425 * @param int $exportMode
1427 * @param string $componentIds
1433 public static function getContributionDetails($exportMode, $componentIds) {
1434 $paymentDetails = array();
1435 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1437 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1438 $componentSelect = " civicrm_participant_payment.participant_id id";
1439 $additionalClause = "
1440 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1441 AND civicrm_participant_payment.participant_id {$componentClause} )
1444 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1445 $componentSelect = " civicrm_membership_payment.membership_id id";
1446 $additionalClause = "
1447 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1448 AND civicrm_membership_payment.membership_id {$componentClause} )
1451 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1452 $componentSelect = " civicrm_pledge_payment.id id";
1453 $additionalClause = "
1454 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1455 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1459 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1460 trxn_id, {$componentSelect}
1461 FROM civicrm_contribution
1462 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1463 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1464 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1465 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1466 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1467 AND option_group_contribution_status.id = contribution_status.option_group_id )
1471 $dao = CRM_Core_DAO
::executeQuery($query);
1473 while ($dao->fetch()) {
1474 $paymentDetails[$dao->id
] = array(
1475 'total_amount' => $dao->total_amount
,
1476 'contribution_status' => $dao->status
,
1477 'receive_date' => $dao->receive_date
,
1478 'pay_instru' => $dao->payment_instrument
,
1479 'trxn_id' => $dao->trxn_id
,
1483 return $paymentDetails;
1487 * Create address associated with contribution record.
1489 * As long as there is one or more billing field in the parameters we will create the address.
1491 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1494 * @param array $params
1495 * @param int $billingLocationTypeID
1500 public static function createAddress($params, $billingLocationTypeID) {
1501 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1502 if ($hasBillingField) {
1503 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1504 return $address->id
;
1511 * Delete billing address record related contribution.
1513 * @param int $contributionId
1514 * @param int $contactId
1516 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1518 $contactJoin = NULL;
1520 if ($contributionId) {
1521 $clauses[] = "cc.id = {$contributionId}";
1525 $clauses[] = "cco.id = {$contactId}";
1526 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1529 if (empty($clauses)) {
1530 CRM_Core_Error
::fatal();
1533 $condition = implode(' OR ', $clauses);
1537 FROM civicrm_address ca
1538 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1542 $dao = CRM_Core_DAO
::executeQuery($query);
1544 while ($dao->fetch()) {
1545 $params = array('id' => $dao->id
);
1546 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1551 * This function check online pending contribution associated w/
1552 * Online Event Registration or Online Membership signup.
1554 * @param int $componentId
1555 * Participant/membership id.
1556 * @param string $componentName
1560 * pending contribution id.
1562 public static function checkOnlinePendingContribution($componentId, $componentName) {
1563 $contributionId = NULL;
1564 if (!$componentId ||
1565 !in_array($componentName, array('Event', 'Membership'))
1567 return $contributionId;
1570 if ($componentName == 'Event') {
1571 $idName = 'participant_id';
1572 $componentTable = 'civicrm_participant';
1573 $paymentTable = 'civicrm_participant_payment';
1574 $source = ts('Online Event Registration');
1577 if ($componentName == 'Membership') {
1578 $idName = 'membership_id';
1579 $componentTable = 'civicrm_membership';
1580 $paymentTable = 'civicrm_membership_payment';
1581 $source = ts('Online Contribution');
1584 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1587 SELECT component.id as {$idName},
1588 componentPayment.contribution_id as contribution_id,
1589 contribution.source source,
1590 contribution.contribution_status_id as contribution_status_id,
1591 contribution.is_pay_later as is_pay_later
1592 FROM $componentTable component
1593 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1594 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1595 WHERE component.id = {$componentId}";
1597 $dao = CRM_Core_DAO
::executeQuery($query);
1599 while ($dao->fetch()) {
1600 if ($dao->contribution_id
&&
1601 $dao->is_pay_later
&&
1602 $dao->contribution_status_id
== $pendingStatusId &&
1603 strpos($dao->source
, $source) !== FALSE
1605 $contributionId = $dao->contribution_id
;
1610 return $contributionId;
1614 * Update contribution as well as related objects.
1616 * This function by-passes hooks - to address this - don't use this function.
1620 * Use api contribute.completetransaction
1621 * For failures use failPayment (preferably exposing by api in the process).
1623 * @param array $params
1624 * @param bool $processContributionObject
1627 * @throws \Exception
1629 public static function transitionComponents($params, $processContributionObject = FALSE) {
1630 // get minimum required values.
1631 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1632 $componentId = CRM_Utils_Array
::value('component_id', $params);
1633 $componentName = CRM_Utils_Array
::value('componentName', $params);
1634 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1635 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1637 // if we already processed contribution object pass previous status id.
1638 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1640 $updateResult = array();
1642 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1644 // we process only ( Completed, Cancelled, or Failed ) contributions.
1645 if (!$contributionId ||
1646 !in_array($contributionStatusId, array(
1647 array_search('Completed', $contributionStatuses),
1648 array_search('Cancelled', $contributionStatuses),
1649 array_search('Failed', $contributionStatuses),
1652 return $updateResult;
1655 if (!$componentName ||
!$componentId) {
1656 // get the related component details.
1657 $componentDetails = self
::getComponentDetails($contributionId);
1660 $componentDetails['contact_id'] = $contactId;
1661 $componentDetails['component'] = $componentName;
1663 if ($componentName == 'event') {
1664 $componentDetails['participant'] = $componentId;
1667 $componentDetails['membership'] = $componentId;
1671 if (!empty($componentDetails['contact_id'])) {
1672 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1678 // do check for required ids.
1679 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1680 return $updateResult;
1683 //now we are ready w/ required ids, start processing.
1685 $baseIPN = new CRM_Core_Payment_BaseIPN();
1687 $input = $ids = $objects = array();
1689 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1690 $ids['contribution'] = $contributionId;
1691 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1692 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1693 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1694 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1695 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1696 $ids['contributionRecur'] = NULL;
1697 $ids['contributionPage'] = NULL;
1699 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1700 CRM_Core_Error
::fatal();
1703 $memberships = &$objects['membership'];
1704 $participant = &$objects['participant'];
1705 $pledgePayment = &$objects['pledge_payment'];
1706 $contribution = &$objects['contribution'];
1708 if ($pledgePayment) {
1709 $pledgePaymentIDs = array();
1710 foreach ($pledgePayment as $key => $object) {
1711 $pledgePaymentIDs[] = $object->id
;
1713 $pledgeID = $pledgePayment[0]->pledge_id
;
1716 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1719 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1720 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1725 // we might want to process contribution object.
1726 $processContribution = FALSE;
1727 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1728 if (is_array($memberships)) {
1729 foreach ($memberships as $membership) {
1731 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1732 $membership->save();
1734 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1735 if ($processContributionObject) {
1736 $processContribution = TRUE;
1743 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1744 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1746 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1747 if ($processContributionObject) {
1748 $processContribution = TRUE;
1752 if ($pledgePayment) {
1753 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1755 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1756 if ($processContributionObject) {
1757 $processContribution = TRUE;
1761 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1762 if (is_array($memberships)) {
1763 foreach ($memberships as $membership) {
1765 $membership->status_id
= array_search('Expired', $membershipStatuses);
1766 $membership->save();
1768 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1769 if ($processContributionObject) {
1770 $processContribution = TRUE;
1776 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1777 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1779 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1780 if ($processContributionObject) {
1781 $processContribution = TRUE;
1785 if ($pledgePayment) {
1786 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1788 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1789 if ($processContributionObject) {
1790 $processContribution = TRUE;
1794 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1796 // only pending contribution related object processed.
1797 if ($previousContriStatusId &&
1798 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1800 // this is case when we already processed contribution object.
1801 return $updateResult;
1803 elseif (!$previousContriStatusId &&
1804 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1806 // this is case when we are going to process contribution object later.
1807 return $updateResult;
1810 if (is_array($memberships)) {
1811 foreach ($memberships as $membership) {
1816 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1817 $membership->membership_type_id
,
1818 $membership->is_test
, $membership->id
1821 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1822 // this picks up membership type changes during renewals
1824 SELECT membership_type_id
1825 FROM civicrm_membership_log
1826 WHERE membership_id=$membership->id
1829 $dao = new CRM_Core_DAO();
1831 if ($dao->fetch()) {
1832 if (!empty($dao->membership_type_id
)) {
1833 $membership->membership_type_id
= $dao->membership_type_id
;
1834 $membership->save();
1837 // else fall back to using current membership type
1840 // Figure out number of terms
1842 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1843 foreach ($lineitems as $lineitem) {
1844 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1845 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1847 // in case membership_num_terms comes through as null or zero
1848 $numterms = $numterms >= 1 ?
$numterms : 1;
1853 // CRM-15735-to update the membership status as per the contribution receive date
1855 if (!empty($params['receive_date'])) {
1856 $joinDate = $params['receive_date'];
1857 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1858 $membership->end_date
,
1859 $membership->join_date
,
1860 $params['receive_date'],
1862 $membership->membership_type_id
,
1865 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1866 $membership->save();
1869 if ($currentMembership) {
1870 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1871 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1872 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1875 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1878 //get the status for membership.
1879 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1881 $dates['join_date'],
1884 $membership->membership_type_id
,
1888 $formattedParams = array(
1889 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1890 array_search('Current', $membershipStatuses)
1892 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1893 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1894 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1897 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1899 $membership->copyValues($formattedParams);
1900 $membership->save();
1902 //updating the membership log
1903 $membershipLog = array();
1904 $membershipLog = $formattedParams;
1905 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1906 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1908 $membershipLog['start_date'] = $logStartDate;
1909 $membershipLog['membership_id'] = $membership->id
;
1910 $membershipLog['modified_id'] = $membership->contact_id
;
1911 $membershipLog['modified_date'] = date('Ymd');
1912 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1914 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1916 //update related Memberships.
1917 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1919 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1922 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1923 if ($processContributionObject) {
1924 $processContribution = TRUE;
1927 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1933 $updatedStatusId = array_search('Registered', $participantStatuses);
1934 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1936 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1937 if ($processContributionObject) {
1938 $processContribution = TRUE;
1942 if ($pledgePayment) {
1943 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1945 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1946 if ($processContributionObject) {
1947 $processContribution = TRUE;
1952 // process contribution object.
1953 if ($processContribution) {
1954 $contributionParams = array();
1961 'payment_instrument_id',
1964 'financial_type_id',
1965 'contribution_status_id',
1966 'non_deductible_amount',
1970 foreach ($fields as $field) {
1971 if (empty($params[$field])) {
1974 $contributionParams[$field] = $params[$field];
1977 $ids = array('contribution' => $contributionId);
1978 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1981 return $updateResult;
1985 * Returns all contribution related object ids.
1987 * @param $contributionId
1991 public static function getComponentDetails($contributionId) {
1992 $componentDetails = $pledgePayment = array();
1993 if (!$contributionId) {
1994 return $componentDetails;
1998 SELECT c.id as contribution_id,
1999 c.contact_id as contact_id,
2000 c.contribution_recur_id,
2001 mp.membership_id as membership_id,
2002 m.membership_type_id as membership_type_id,
2003 pp.participant_id as participant_id,
2004 p.event_id as event_id,
2005 pgp.id as pledge_payment_id
2006 FROM civicrm_contribution c
2007 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2008 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2009 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2010 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2011 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2012 WHERE c.id = $contributionId";
2014 $dao = CRM_Core_DAO
::executeQuery($query);
2015 $componentDetails = array();
2017 while ($dao->fetch()) {
2018 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2019 $componentDetails['contact_id'] = $dao->contact_id
;
2020 if ($dao->event_id
) {
2021 $componentDetails['event'] = $dao->event_id
;
2023 if ($dao->participant_id
) {
2024 $componentDetails['participant'] = $dao->participant_id
;
2026 if ($dao->membership_id
) {
2027 if (!isset($componentDetails['membership'])) {
2028 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2030 $componentDetails['membership'][] = $dao->membership_id
;
2031 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2033 if ($dao->pledge_payment_id
) {
2034 $pledgePayment[] = $dao->pledge_payment_id
;
2036 if ($dao->contribution_recur_id
) {
2037 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2041 if ($pledgePayment) {
2042 $componentDetails['pledge_payment'] = $pledgePayment;
2045 return $componentDetails;
2049 * @param int $contactId
2050 * @param bool $includeSoftCredit
2052 * @return null|string
2054 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2058 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2059 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2060 $liWhere = " AND i.financial_type_id IN (0)";
2061 if (!empty($financialTypes)) {
2062 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2063 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2065 $contactContributionsSQL = "
2066 SELECT contribution.id AS id
2067 FROM civicrm_contribution contribution
2068 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2069 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2073 $contactSoftCreditContributionsSQL = "
2074 SELECT contribution.id
2075 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2076 ON ( contribution.id = softContribution.contribution_id )
2077 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2078 $query = "SELECT count( x.id ) count FROM ( ";
2079 $query .= $contactContributionsSQL;
2081 if ($includeSoftCredit) {
2082 $query .= " UNION ";
2083 $query .= $contactSoftCreditContributionsSQL;
2088 return CRM_Core_DAO
::singleValueQuery($query);
2092 * Repeat a transaction as part of a recurring series.
2094 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2095 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2096 * subsequent call to the contribution.completetransaction api.
2098 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2100 * @param CRM_Contribute_BAO_Contribution $contribution
2101 * @param array $input
2102 * @param array $contributionParams
2103 * @param int $paymentProcessorID
2106 * @throws CiviCRM_API3_Exception
2108 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2109 if (!empty($contribution->id
)) {
2112 if (empty($contribution->id
)) {
2113 // Unclear why this would only be set for repeats.
2114 if (!empty($input['amount'])) {
2115 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2118 if (!empty($contributionParams['contribution_recur_id'])) {
2119 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2120 'id' => $contributionParams['contribution_recur_id'],
2122 if (!empty($recurringContribution['campaign_id'])) {
2123 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2124 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2126 if (!empty($recurringContribution['financial_type_id'])) {
2127 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2128 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2131 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2132 $contributionParams['contribution_recur_id'],
2133 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2135 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2137 $contributionParams['status_id'] = 'Pending';
2138 if (isset($contributionParams['financial_type_id'])) {
2139 // Give precedence to passed in type.
2140 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2143 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2145 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2146 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2148 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2149 //do not create CC or BCC emails or profile notifications.
2150 //The if is just to be safe. Not sure if we can ever arrive with this unset
2151 if (isset($contribution->contribution_page_id
)) {
2152 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2155 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2156 $contribution->id
= $createContribution['id'];
2157 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2163 * Get individual id for onbehalf contribution.
2165 * @param int $contributionId
2167 * @param int $contributorId
2171 * containing organization id and individual id
2173 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2177 if (!$contributionId) {
2181 // fetch contributor id if null
2182 if (!$contributorId) {
2183 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2184 $contributionId, 'contact_id'
2188 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2189 $activityTypeId = array_search('Contribution', $activityTypeIds);
2191 if ($activityTypeId && $contributorId) {
2193 SELECT civicrm_activity_contact.contact_id
2194 FROM civicrm_activity_contact
2195 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2196 WHERE civicrm_activity.activity_type_id = %1
2197 AND civicrm_activity.source_record_id = %2
2198 AND civicrm_activity_contact.record_type_id = %3
2201 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2202 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2205 1 => array($activityTypeId, 'Integer'),
2206 2 => array($contributionId, 'Integer'),
2207 3 => array($sourceID, 'Integer'),
2210 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2212 // for on behalf contribution source is individual and contributor is organization
2213 if ($sourceContactId && $sourceContactId != $contributorId) {
2214 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2215 // get rel type id for employee of relation
2216 foreach ($relationshipTypeIds as $id => $typeVals) {
2217 if ($typeVals['name_a_b'] == 'Employee of') {
2218 $relationshipTypeId = $id;
2223 $rel = new CRM_Contact_DAO_Relationship();
2224 $rel->relationship_type_id
= $relationshipTypeId;
2225 $rel->contact_id_a
= $sourceContactId;
2226 $rel->contact_id_b
= $contributorId;
2227 if ($rel->find(TRUE)) {
2228 $ids['individual_id'] = $rel->contact_id_a
;
2229 $ids['organization_id'] = $rel->contact_id_b
;
2240 public static function getContributionDates() {
2241 $config = CRM_Core_Config
::singleton();
2242 $currentMonth = date('m');
2243 $currentDay = date('d');
2244 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2245 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2246 (int ) $config->fiscalYearStart
['d'] > $currentDay
2249 $year = date('Y') - 1;
2254 $year = array('Y' => $year);
2255 $yearDate = $config->fiscalYearStart
;
2256 $yearDate = array_merge($year, $yearDate);
2257 $yearDate = CRM_Utils_Date
::format($yearDate);
2259 $monthDate = date('Ym') . '01';
2265 'yearDate' => $yearDate,
2266 'monthDate' => $monthDate,
2271 * Load objects relations to contribution object.
2272 * Objects are stored in the $_relatedObjects property
2273 * In the first instance we are just moving functionality from BASEIpn -
2274 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2276 * Note that the unit test for the BaseIPN class tests this function
2278 * @param array $input
2279 * Input as delivered from Payment Processor.
2281 * Ids as Loaded by Payment Processor.
2282 * @param bool $loadAll
2283 * Load all related objects - even where id not passed in? (allows API to call this).
2288 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2290 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2291 if (empty($ids['contact']) && isset($this->contact_id
)) {
2292 $ids['contact'] = $this->contact_id
;
2295 if (empty($this->_component
)) {
2296 if (!empty($ids['event'])) {
2297 $this->_component
= 'event';
2300 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2304 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2305 // refactoring than anything else, and has unit test coverage.
2306 if (empty($this->financial_type_id
)) {
2310 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2315 if (!$paymentProcessorID && $this->contribution_page_id
) {
2316 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2317 $this->contribution_page_id
,
2320 if ($paymentProcessorID) {
2321 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2325 $ids['contributionType'] = $this->financial_type_id
;
2326 $ids['financialType'] = $this->financial_type_id
;
2329 'contact' => 'CRM_Contact_BAO_Contact',
2330 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2331 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2332 'financialType' => 'CRM_Financial_BAO_FinancialType',
2334 foreach ($entities as $entity => $bao) {
2335 if (!empty($ids[$entity])) {
2336 $this->_relatedObjects
[$entity] = new $bao();
2337 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2338 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2339 throw new CRM_Core_Exception($entity . ' could not be loaded');
2344 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2345 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2348 if (!empty($ids['pledge_payment'])) {
2349 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2350 if (empty($paymentID)) {
2353 $payment = new CRM_Pledge_BAO_PledgePayment();
2354 $payment->id
= $paymentID;
2355 if (!$payment->find(TRUE)) {
2356 throw new Exception("Could not find pledge payment record: " . $paymentID);
2358 $this->_relatedObjects
['pledge_payment'][] = $payment;
2362 $this->loadRelatedMembershipObjects($ids);
2364 if ($this->_component
!= 'contribute') {
2365 // we are in event mode
2366 // make sure event exists and is valid
2367 $event = new CRM_Event_BAO_Event();
2368 $event->id
= $ids['event'];
2369 if ($ids['event'] &&
2372 throw new Exception("Could not find event: " . $ids['event']);
2375 $this->_relatedObjects
['event'] = &$event;
2377 $participant = new CRM_Event_BAO_Participant();
2378 $participant->id
= $ids['participant'];
2379 if ($ids['participant'] &&
2380 !$participant->find(TRUE)
2382 throw new Exception("Could not find participant: " . $ids['participant']);
2384 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2386 $this->_relatedObjects
['participant'] = &$participant;
2388 // get the payment processor id from event - this is inaccurate see CRM-16923
2389 // in future we should look at throwing an exception here rather than an dubious guess.
2390 if (!$paymentProcessorID) {
2391 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2392 if ($paymentProcessorID) {
2393 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2398 if ($paymentProcessorID) {
2399 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2400 $this->is_test ?
'test' : 'live'
2402 $ids['paymentProcessor'] = $paymentProcessorID;
2403 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2409 * Create array of message information - ie. return html version, txt version, to field
2411 * @param array $input
2412 * Incoming information.
2413 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2414 * just check presence of recur object but maintaining legacy approach
2417 * IDs of related objects.
2418 * @param array $values
2419 * Any values that may have already been compiled by calling process.
2420 * This is augmented by values 'gathered' by gatherMessageValues
2421 * @param bool $recur
2422 * @param bool $returnMessageText
2423 * Distinguishes between whether to send message or return.
2424 * message text. We are working towards this function ALWAYS returning message text & calling
2425 * function doing emails / pdfs with it
2431 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2432 $this->loadRelatedObjects($input, $ids);
2434 if (empty($this->_component
)) {
2435 $this->_component
= CRM_Utils_Array
::value('component', $input);
2438 //not really sure what params might be passed in but lets merge em into values
2439 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2440 if (!empty($input['receipt_date'])) {
2441 $values['receipt_date'] = $input['receipt_date'];
2444 $template = CRM_Core_Smarty
::singleton();
2445 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2446 //what does recur 'mean here - to do with payment processor return functionality but
2447 // what is the importance
2448 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2449 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2451 $entityID = $entity = NULL;
2452 if (isset($ids['contribution'])) {
2453 $entity = 'contribution';
2454 $entityID = $ids['contribution'];
2456 if (!empty($ids['membership'])) {
2457 //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
2458 // 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
2459 // line having loaded an array
2460 $ids['membership'] = (array) $ids['membership'];
2461 $entity = 'membership';
2462 $entityID = $ids['membership'][0];
2465 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2466 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2467 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2469 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2470 //direct mode showing billing block, so use directIPN for temporary
2471 $template->assign('contributeMode', 'directIPN');
2474 // todo remove strtolower - check consistency
2475 if (strtolower($this->_component
) == 'event') {
2476 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2477 $values['event'] = array();
2479 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2481 //get location details
2482 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2483 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2485 $ufJoinParams = array(
2486 'entity_table' => 'civicrm_event',
2487 'entity_id' => $ids['event'],
2488 'module' => 'CiviEvent',
2491 list($custom_pre_id,
2493 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2495 $values['custom_pre_id'] = $custom_pre_id;
2496 $values['custom_post_id'] = $custom_post_ids;
2497 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2498 //and cases involving status updation through ipn
2499 // whatever that means!
2500 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2501 // perhaps we should throw an e-notice if amount is set & force total_amount?
2502 if (!empty($input['amount'])) {
2503 $values['totalAmount'] = $input['amount'];
2506 if ($values['event']['is_email_confirm']) {
2507 $values['is_email_receipt'] = 1;
2510 if (!empty($ids['contribution'])) {
2511 $values['contributionId'] = $ids['contribution'];
2514 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2515 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2519 $values['contribution_id'] = $this->id
;
2520 if (!empty($ids['related_contact'])) {
2521 $values['related_contact'] = $ids['related_contact'];
2522 if (isset($ids['onbehalf_dupe_alert'])) {
2523 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2525 $entityBlock = array(
2526 'contact_id' => $ids['contact'],
2527 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2528 'Home', 'id', 'name'
2531 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2532 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2535 if ($this->is_test
) {
2538 if (!empty($this->_relatedObjects
['membership'])) {
2539 foreach ($this->_relatedObjects
['membership'] as $membership) {
2540 if ($membership->id
) {
2541 $values['isMembership'] = TRUE;
2542 $values['membership_assign'] = TRUE;
2544 // need to set the membership values here
2545 $template->assign('membership_name',
2546 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2548 $template->assign('mem_start_date', $membership->start_date
);
2549 $template->assign('mem_join_date', $membership->join_date
);
2550 $template->assign('mem_end_date', $membership->end_date
);
2551 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2552 $template->assign('mem_status', $membership_status);
2553 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2554 $values['is_pay_later'] = 1;
2557 // if separate payment there are two contributions recorded and the
2558 // admin will need to send a receipt for each of them separately.
2559 // we dont link the two in the db (but can potentially infer it if needed)
2560 $template->assign('is_separate_payment', 0);
2562 if ($recur && $paymentObject) {
2563 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2564 $template->assign('cancelSubscriptionUrl', $url);
2565 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2566 $template->assign('updateSubscriptionBillingUrl', $url);
2567 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2568 $template->assign('updateSubscriptionUrl', $url);
2571 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2574 // otherwise if its about sending emails, continue sending without return, as we
2575 // don't want to exit the loop.
2580 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2586 * Gather values for contribution mail - this function has been created
2587 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2588 * Values related to the contribution in question are gathered
2590 * @param array $input
2591 * Input into function (probably from payment processor).
2592 * @param array $values
2594 * The set of ids related to the input.
2598 public function _gatherMessageValues($input, &$values, $ids = array()) {
2599 // set display address of contributor
2600 if ($this->address_id
) {
2601 $addressParams = array('id' => $this->address_id
);
2602 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2603 $addressDetails = array_values($addressDetails);
2605 // Else we assign the billing address of the contribution contact.
2607 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2608 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2609 $addressDetails = array_values($addressDetails);
2612 if (!empty($addressDetails[0]['display'])) {
2613 $values['address'] = $addressDetails[0]['display'];
2616 if ($this->_component
== 'contribute') {
2617 //get soft contributions
2618 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2619 if (!empty($softContributions)) {
2620 $values['softContributions'] = $softContributions['soft_credit'];
2622 if (isset($this->contribution_page_id
)) {
2623 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2624 if ($this->contribution_page_id
) {
2625 // CRM-8254 - override default currency if applicable
2626 $config = CRM_Core_Config
::singleton();
2627 $config->defaultCurrency
= CRM_Utils_Array
::value(
2630 $config->defaultCurrency
2634 // no contribution page -probably back office
2636 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2637 $values['is_email_receipt'] = 1;
2638 $values['title'] = 'Contribution';
2640 // set lineItem for contribution
2642 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2643 if (!empty($lineItem)) {
2644 $itemId = key($lineItem);
2645 foreach ($lineItem as &$eachItem) {
2646 if (isset($this->_relatedObjects
['membership'])
2647 && is_array($this->_relatedObjects
['membership'])
2648 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2649 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2650 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2651 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2654 $values['lineItem'][0] = $lineItem;
2655 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2659 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2663 // if this is onbehalf of contribution then set related contact
2664 if (!empty($relatedContact['individual_id'])) {
2665 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2670 $eventParams = array(
2671 'id' => $this->_relatedObjects
['event']->id
,
2673 $values['event'] = array();
2675 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2676 // add custom fields for event
2677 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2679 $eventCustomGroup = array();
2680 foreach ($eventGroupTree as $key => $group) {
2681 if ($key === 'info') {
2685 foreach ($group['fields'] as $k => $customField) {
2686 $groupLabel = $group['title'];
2687 if (!empty($customField['customValue'])) {
2688 foreach ($customField['customValue'] as $customFieldValues) {
2689 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2694 $values['event']['customGroup'] = $eventCustomGroup;
2696 //get participant details
2697 $participantParams = array(
2698 'id' => $this->_relatedObjects
['participant']->id
,
2701 $values['participant'] = array();
2703 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2704 // add custom fields for event
2705 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2706 $participantCustomGroup = array();
2707 foreach ($participantGroupTree as $key => $group) {
2708 if ($key === 'info') {
2712 foreach ($group['fields'] as $k => $customField) {
2713 $groupLabel = $group['title'];
2714 if (!empty($customField['customValue'])) {
2715 foreach ($customField['customValue'] as $customFieldValues) {
2716 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2721 $values['participant']['customGroup'] = $participantCustomGroup;
2723 //get location details
2724 $locationParams = array(
2725 'entity_id' => $this->_relatedObjects
['event']->id
,
2726 'entity_table' => 'civicrm_event',
2728 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2730 $ufJoinParams = array(
2731 'entity_table' => 'civicrm_event',
2732 'entity_id' => $ids['event'],
2733 'module' => 'CiviEvent',
2736 list($custom_pre_id,
2738 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2740 $values['custom_pre_id'] = $custom_pre_id;
2741 $values['custom_post_id'] = $custom_post_ids;
2743 // set lineItem for event contribution
2745 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2746 if (!empty($participantIds)) {
2747 foreach ($participantIds as $pIDs) {
2748 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2749 if (!CRM_Utils_System
::isNull($lineItem)) {
2750 $values['lineItem'][] = $lineItem;
2757 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2759 $customGroup = array();
2760 foreach ($groupTree as $key => $group) {
2761 if ($key === 'info') {
2765 foreach ($group['fields'] as $k => $customField) {
2766 $groupLabel = $group['title'];
2767 if (!empty($customField['customValue'])) {
2768 foreach ($customField['customValue'] as $customFieldValues) {
2769 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2774 $values['customGroup'] = $customGroup;
2780 * Assign message variables to template but try to break the habit.
2782 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2783 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2784 * multiple recurring payments for processors like IATS that use tokens.
2786 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2787 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2788 * Note we send directly from this function in some cases because it is only partly refactored.
2790 * Don't call this function directly as the signature will change.
2794 * @param CRM_Core_SMARTY $template
2795 * @param bool $recur
2796 * @param bool $returnMessageText
2800 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2801 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2802 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2803 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2804 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2805 $values['useForMember'] = TRUE;
2807 //assign honor information to receipt message
2808 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2810 if (isset($softRecord['soft_credit'])) {
2811 //if id of contribution page is present
2812 if (!empty($values['id'])) {
2813 $values['honor'] = array(
2814 'honor_profile_values' => array(),
2815 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2816 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2818 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2820 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2821 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2824 //offline contribution
2825 $softCreditTypes = $softCredits = array();
2826 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2827 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2828 $softCredits[$key] = array(
2829 'Name' => $softCredit['contact_name'],
2830 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2833 $template->assign('softCreditTypes', $softCreditTypes);
2834 $template->assign('softCredits', $softCredits);
2838 $dao = new CRM_Contribute_DAO_ContributionProduct();
2839 $dao->contribution_id
= $this->id
;
2840 if ($dao->find(TRUE)) {
2841 $premiumId = $dao->product_id
;
2842 $template->assign('option', $dao->product_option
);
2844 $productDAO = new CRM_Contribute_DAO_Product();
2845 $productDAO->id
= $premiumId;
2846 $productDAO->find(TRUE);
2847 $template->assign('selectPremium', TRUE);
2848 $template->assign('product_name', $productDAO->name
);
2849 $template->assign('price', $productDAO->price
);
2850 $template->assign('sku', $productDAO->sku
);
2852 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2853 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2854 if (!$values['amount'] && isset($this->total_amount
)) {
2855 $values['amount'] = $this->total_amount
;
2858 // add the new contribution values
2859 if (strtolower($this->_component
) == 'contribute') {
2861 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2862 $softDAO->contribution_id
= $this->id
;
2863 if ($softDAO->find(TRUE)) {
2864 $template->assign('pcpBlock', TRUE);
2865 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2866 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2867 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2869 //assign the pcp page title for email subject
2870 $pcpDAO = new CRM_PCP_DAO_PCP();
2871 $pcpDAO->id
= $softDAO->pcp_id
;
2872 if ($pcpDAO->find(TRUE)) {
2873 $template->assign('title', $pcpDAO->title
);
2878 if ($this->financial_type_id
) {
2879 $values['financial_type_id'] = $this->financial_type_id
;
2882 $template->assign('trxn_id', $this->trxn_id
);
2883 $template->assign('receive_date',
2884 CRM_Utils_Date
::processDate($this->receive_date
)
2886 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2887 $template->assign('contributeMode', 'notify');
2888 $template->assign('action', $this->is_test ?
1024 : 1);
2889 $template->assign('receipt_text',
2890 CRM_Utils_Array
::value('receipt_text',
2894 $template->assign('is_monetary', 1);
2895 $template->assign('is_recur', (bool) $recur);
2896 $template->assign('currency', $this->currency
);
2897 $template->assign('address', CRM_Utils_Address
::format($input));
2898 if (!empty($values['customGroup'])) {
2899 $template->assign('customGroup', $values['customGroup']);
2901 if (!empty($values['softContributions'])) {
2902 $template->assign('softContributions', $values['softContributions']);
2904 if ($this->_component
== 'event') {
2905 $template->assign('title', $values['event']['title']);
2906 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2907 $viewRoles = array();
2908 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2909 $viewRoles[] = $participantRoles[$v];
2911 $values['event']['participant_role'] = implode(', ', $viewRoles);
2912 $template->assign('event', $values['event']);
2913 $template->assign('participant', $values['participant']);
2914 $template->assign('location', $values['location']);
2915 $template->assign('customPre', $values['custom_pre_id']);
2916 $template->assign('customPost', $values['custom_post_id']);
2919 if ($this->_relatedObjects
['participant']->is_test
) {
2923 $values['params'] = array();
2924 //to get email of primary participant.
2925 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2926 $primaryAmount[] = array(
2927 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2928 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2930 //build an array of cId/pId of participants
2931 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2932 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2933 //send receipt to additional participant if exists
2934 if (count($additionalIDs)) {
2935 $template->assign('isPrimary', 0);
2936 $template->assign('customProfile', NULL);
2937 //set additionalParticipant true
2938 $values['params']['additionalParticipant'] = TRUE;
2939 foreach ($additionalIDs as $pId => $cId) {
2941 //to change the status pending to completed
2942 $additional = new CRM_Event_DAO_Participant();
2943 $additional->id
= $pId;
2944 $additional->contact_id
= $cId;
2945 $additional->find(TRUE);
2946 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2947 $additional->status_id
= 1;
2948 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2949 //if additional participant dont have email
2951 if (!$additionalParticipantInfo) {
2952 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2954 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2955 $primaryAmount[] = array(
2956 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2957 'amount' => $additional->fee_amount
,
2959 $additional->save();
2960 $additional->free();
2961 $template->assign('amount', $amount);
2962 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2966 //build an array of custom profile and assigning it to template
2967 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2969 if (count($customProfile)) {
2970 $template->assign('customProfile', $customProfile);
2973 // for primary contact
2974 $values['params']['additionalParticipant'] = FALSE;
2975 $template->assign('isPrimary', 1);
2976 $template->assign('amount', $primaryAmount);
2977 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2978 if ($this->payment_instrument_id
) {
2979 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2980 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2982 // carry paylater, since we did not created billing,
2983 // so need to pull email from primary location, CRM-4395
2984 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2990 * Check whether payment processor supports
2991 * cancellation of contribution subscription
2993 * @param int $contributionId
2996 * @param bool $isNotCancelled
3000 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3001 $cacheKeyString = "$contributionId";
3002 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3004 static $supportsCancel = array();
3006 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3007 $supportsCancel[$cacheKeyString] = FALSE;
3008 $isCancelled = FALSE;
3010 if ($isNotCancelled) {
3011 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3014 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3015 if (!empty($paymentObject)) {
3016 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3019 return $supportsCancel[$cacheKeyString];
3023 * Check whether subscription is already cancelled.
3025 * @param int $contributionId
3029 * contribution status
3031 public static function isSubscriptionCancelled($contributionId) {
3033 SELECT cr.contribution_status_id
3034 FROM civicrm_contribution_recur cr
3035 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3036 WHERE con.id = %1 LIMIT 1";
3037 $params = array(1 => array($contributionId, 'Integer'));
3038 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3039 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3040 if ($status == 'Cancelled') {
3047 * Create all financial accounts entry.
3049 * @param array $params
3050 * Contribution object, line item array and params for trxn.
3053 * @param array $financialTrxnValues
3055 * @return null|object
3057 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3058 $skipRecords = $update = $return = $isRelatedId = FALSE;
3060 $additionalParticipantId = array();
3061 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3062 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3064 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3065 $entityId = $params['participant_id'];
3066 $entityTable = 'civicrm_participant';
3067 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3069 elseif (!empty($params['membership_id'])) {
3070 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3071 // are created off one contribution should be handled elsewhere
3072 $entityId = $params['membership_id'];
3073 $entityTable = 'civicrm_membership';
3076 $entityId = $params['contribution']->id
;
3077 $entityTable = 'civicrm_contribution';
3080 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3081 $isRelatedId = TRUE;
3084 $entityID[] = $entityId;
3085 if (!empty($additionalParticipantId)) {
3086 $entityID +
= $additionalParticipantId;
3088 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3089 if (empty($params['prevContribution'])) {
3096 $statusId = $params['contribution']->contribution_status_id
;
3097 // CRM-13964 partial payment
3098 if ($contributionStatus == 'Partially paid'
3099 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3101 $partialAmtPay = $params['partial_amount_pay'];
3102 $partialAmtTotal = $params['partial_payment_total'];
3104 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3105 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3106 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3107 $params['total_amount'] = $partialAmtPay;
3109 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3110 if (empty($balanceTrxnInfo['trxn_id'])) {
3111 // create new balance transaction record
3112 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3113 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3115 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3116 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3117 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3118 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3119 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3120 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3121 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3122 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3123 $balanceTrxnParams['status_id'] = $statusId;
3124 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3125 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3126 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3127 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3129 $balanceTrxnParams['is_payment'] = 1;
3131 if (!empty($params['payment_processor'])) {
3132 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3134 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3138 // build line item array if its not set in $params
3139 if (empty($params['line_item']) ||
$additionalParticipantId) {
3140 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3143 if ($contributionStatus != 'Failed' &&
3144 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3146 $skipRecords = TRUE;
3147 $pendingStatus = array(
3151 if (in_array($contributionStatus, $pendingStatus)) {
3152 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3153 $params['financial_type_id'],
3154 'Accounts Receivable Account is'
3157 elseif (!empty($params['payment_processor'])) {
3158 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3159 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3160 'id' => $params['payment_processor'],
3161 'return' => 'payment_instrument_id',
3164 elseif (!empty($params['payment_instrument_id'])) {
3165 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3168 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3169 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3170 $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);
3173 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3174 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3175 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3177 //build financial transaction params
3178 $trxnParams = array(
3179 'contribution_id' => $params['contribution']->id
,
3180 'to_financial_account_id' => $params['to_financial_account_id'],
3181 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3182 'total_amount' => $totalAmount,
3183 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3184 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3185 'currency' => $params['contribution']->currency
,
3186 'trxn_id' => $params['contribution']->trxn_id
,
3187 'status_id' => $statusId,
3188 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3189 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3191 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3192 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3193 if (isset($params['refund_trxn_id'])) {
3194 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3195 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3198 //CRM-16259, set is_payment flag for non pending status
3199 if (!in_array($contributionStatus, $pendingStatus)) {
3200 $trxnParams['is_payment'] = 1;
3202 if (!empty($params['payment_processor'])) {
3203 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3206 if (isset($fromFinancialAccountId)) {
3207 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3210 // consider external values passed for recording transaction entry
3211 if (!empty($financialTrxnValues)) {
3212 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3215 $params['trxnParams'] = $trxnParams;
3217 if (!empty($params['prevContribution'])) {
3219 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3220 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3221 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3222 if (!isset($params['trxnParams']['trxn_id'])) {
3223 // Actually I have no idea why we are overwriting any values from the previous contribution.
3224 // (filling makes sense to me). However, only protecting this value as I really really know we
3225 // don't want this one overwritten.
3227 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3229 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3231 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3232 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3233 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3235 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3236 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3239 //if financial type is changed
3240 if (!empty($params['financial_type_id']) &&
3241 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3243 $accountRelationship = 'Income Account is';
3244 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3245 $accountRelationship = 'Deferred Revenue Account is';
3247 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' "));
3248 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3249 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3250 if ($oldFinancialAccount != $newFinancialAccount) {
3251 $params['total_amount'] = 0;
3252 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3253 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3254 $params['prevContribution']->financial_type_id
, $relationTypeId);
3257 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3258 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3259 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3262 self
::updateFinancialAccounts($params, 'changeFinancialType');
3263 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3264 $params['financial_account_id'] = $newFinancialAccount;
3265 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3266 self
::updateFinancialAccounts($params);
3267 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3269 $params['deferred_financial_account_id'] = $newFinancialAccount;
3273 //Update contribution status
3274 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3275 if (!isset($params['refund_trxn_id'])) {
3276 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3277 // gets preference over another so I am only 'protecting' a very specific tested flow
3278 // and letting natural justice take care of the rest.
3279 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3281 if (!empty($params['contribution_status_id']) &&
3282 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3284 //Update Financial Records
3285 self
::updateFinancialAccounts($params, 'changedStatus');
3289 // change Payment Instrument for a Completed contribution
3290 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3291 // instrument is null and now new payment instrument is added along with the payment
3292 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3293 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3294 if (array_key_exists('payment_instrument_id', $params)) {
3295 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3296 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3297 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3299 //check if status is changed from Pending to Completed
3300 // do not update payment instrument changes for Pending to Completed
3301 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3302 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3304 // for all other statuses create new financial records
3305 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3306 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3307 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3311 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3312 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3313 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3315 // for any other payment instrument changes create new financial records
3316 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3317 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3318 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3321 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3322 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3324 // another special case when check number is changed, create new financial records
3325 // create financial trxn with negative amount
3326 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3327 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3328 // create financial trxn with positive amount
3329 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3330 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3331 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3336 //if Change contribution amount
3337 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3338 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3339 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3340 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3341 if (isset($totalAmount) &&
3342 $totalAmount != $params['prevContribution']->total_amount
3344 //Update Financial Records
3345 $params['trxnParams']['from_financial_account_id'] = NULL;
3346 self
::updateFinancialAccounts($params, 'changedAmount');
3351 // Looks like we might have a data correction update.
3352 // This would be a case where a transaction id has been entered but it is incorrect &
3353 // the person goes back in & fixes it, as opposed to a new transaction.
3354 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3355 // the data fix scenario.
3357 if (isset($params['refund_trxn_id'])) {
3358 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3359 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3360 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3367 // records finanical trxn and entity financial trxn
3368 // also make it available as return value
3369 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3370 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3371 $params['entity_id'] = $financialTxn->id
;
3372 if (empty($params['partial_payment_total']) && empty($params['partial_amount_pay'])) {
3373 self
::$_trxnIDs[] = $financialTxn->id
;
3377 // record line items and financial items
3378 if (empty($params['skipLineItem'])) {
3379 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3382 // create batch entry if batch_id is passed and
3383 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3384 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3385 $entityParams = array(
3386 'batch_id' => $params['batch_id'],
3387 'entity_table' => 'civicrm_financial_trxn',
3388 'entity_id' => $financialTxn->id
,
3390 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3393 // when a fee is charged
3394 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3395 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3398 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3399 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3401 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3402 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3403 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3405 unset($params['line_item']);
3406 self
::$_trxnIDs = NULL;
3411 * Update all financial accounts entry.
3413 * @param array $params
3414 * Contribution object, line item array and params for trxn.
3416 * @param string $context
3419 * @param null $skipTrxn
3422 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3423 $itemAmount = $trxnID = NULL;
3424 //get all the statuses
3425 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3426 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3427 if (($previousContributionStatus == 'Pending'
3428 ||
$previousContributionStatus == 'In Progress')
3429 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3430 && $context == 'changePaymentInstrument'
3434 if ((($previousContributionStatus == 'Partially paid'
3435 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3436 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3437 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3438 && $context == 'changedStatus'
3442 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3443 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3445 if ($context == 'changedStatus') {
3446 //get all the statuses
3447 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3448 $cancelledTaxAmount = 0;
3449 if ($previousContributionStatus == 'Completed'
3450 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3452 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3453 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3454 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3455 $creditNoteId = self
::createCreditNoteId();
3456 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3459 elseif (($previousContributionStatus == 'Pending'
3460 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3462 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3463 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3464 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3466 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3467 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3468 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3469 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3470 $creditNoteId = self
::createCreditNoteId();
3471 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3475 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3478 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3480 elseif ($context == 'changePaymentInstrument') {
3481 $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount'];
3482 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $params);
3483 if (empty($deferredFinancialAccount)) {
3484 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
3485 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3487 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3488 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3489 if ($params['total_amount'] != $params['trxnParams']['total_amount']) {
3490 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3491 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3494 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3495 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3500 if ($context == 'changedStatus') {
3501 if (($previousContributionStatus == 'Pending'
3502 ||
$previousContributionStatus == 'In Progress')
3503 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3505 if (empty($params['line_item'])) {
3507 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3508 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3509 // & this can be removed
3512 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3513 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3514 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3515 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3516 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3518 $entityParams = array(
3519 'entity_table' => 'civicrm_financial_item',
3521 foreach ($params['line_item'] as $fieldId => $fields) {
3522 foreach ($fields as $fieldValueId => $fieldValues) {
3524 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3525 2 => array($fieldValues['id'], 'Integer'),
3527 CRM_Core_DAO
::executeQuery($query, $fparams);
3529 1 => array($fieldValues['id'], 'Integer'),
3531 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3532 while ($financialItem->fetch()) {
3533 $entityParams['entity_id'] = $financialItem->id
;
3534 $entityParams['amount'] = $financialItem->amount
;
3535 foreach (self
::$_trxnIDs as $tID) {
3536 $entityParams['financial_trxn_id'] = $tID;
3537 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3545 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3546 $params['entity_id'] = $trxn->id
;
3547 if ($context != 'changePaymentInstrument') {
3548 $itemParams['entity_table'] = 'civicrm_line_item';
3549 $trxnIds['id'] = $params['entity_id'];
3550 foreach ($params['line_item'] as $fieldId => $fields) {
3551 foreach ($fields as $fieldValueId => $fieldValues) {
3552 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3553 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3554 if ($params['contribution']->receive_date
) {
3555 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3558 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3560 $currency = $params['prevContribution']->currency
;
3561 if ($params['contribution']->currency
) {
3562 $currency = $params['contribution']->currency
;
3565 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3568 if (!empty($params['is_quick_config'])) {
3569 $amount = $itemAmount;
3571 $amount = $params['total_amount'];
3575 $amount = $diff * $fieldValues['line_total'];
3578 $itemParams = array(
3579 'transaction_date' => $receiveDate,
3580 'contact_id' => $params['prevContribution']->contact_id
,
3581 'currency' => $currency,
3582 'amount' => $amount,
3583 'description' => $prevFinancialItem->description
,
3584 'status_id' => $prevFinancialItem->status_id
,
3585 'financial_account_id' => $financialAccount,
3586 'entity_table' => 'civicrm_line_item',
3587 'entity_id' => $fieldValues['id'],
3589 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3590 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3591 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3593 if ($fieldValues['tax_amount']) {
3594 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3595 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3596 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3597 $itemParams['description'] = $taxTerm;
3598 if ($fieldValues['financial_type_id']) {
3599 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3601 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3606 if ($context == 'changeFinancialType') {
3607 $params['skipLineItem'] = FALSE;
3608 foreach ($params['line_item'] as &$lineItems) {
3609 foreach ($lineItems as &$line) {
3610 $line['financial_type_id'] = $params['financial_type_id'];
3614 if ($context == 'changePaymentInstrument') {
3615 foreach ($params['line_item'] as $lineitems) {
3616 foreach ($lineitems as $fieldValueId => $fieldValues) {
3617 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3618 // save to entity_financial_trxn table
3619 $entityFinancialTrxnParams = array(
3620 'entity_table' => "civicrm_financial_item",
3621 'entity_id' => $prevFinancialItem->id
,
3622 'financial_trxn_id' => $trxn->id
,
3623 'amount' => $trxn->total_amount
,
3625 civicrm_api3('entityFinancialTrxn', 'create', $entityFinancialTrxnParams);
3629 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3633 * Is this contribution status a reversal.
3635 * If so we would expect to record a negative value in the financial_trxn table.
3637 * @param int $status_id
3641 public static function isContributionStatusNegative($status_id) {
3642 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3643 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3647 * Check status validation on update of a contribution.
3649 * @param array $values
3650 * Previous form values before submit.
3652 * @param array $fields
3653 * The input form values.
3655 * @param array $errors
3660 public static function checkStatusValidation($values, &$fields, &$errors) {
3661 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3662 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3663 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3667 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3668 $checkStatus = array(
3669 'Cancelled' => array('Completed', 'Refunded'),
3670 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3671 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3672 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3673 'Refunded' => array('Cancelled', 'Completed'),
3674 'Partially paid' => array('Completed'),
3677 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3678 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3680 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3681 1 => $contributionStatuses[$values['contribution_status_id']],
3682 2 => $contributionStatuses[$fields['contribution_status_id']],
3688 * Delete contribution of contact.
3692 * @param int $contactId
3696 public static function deleteContactContribution($contactId) {
3697 $contribution = new CRM_Contribute_DAO_Contribution();
3698 $contribution->contact_id
= $contactId;
3699 $contribution->find();
3700 while ($contribution->fetch()) {
3701 self
::deleteContribution($contribution->id
);
3706 * Get options for a given contribution field.
3707 * @see CRM_Core_DAO::buildOptions
3709 * @param string $fieldName
3710 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3711 * @param array $props whatever is known about this dao object.
3713 * @return array|bool
3715 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3716 $className = __CLASS__
;
3718 switch ($fieldName) {
3719 // This field is not part of this object but the api supports it
3720 case 'payment_processor':
3721 $className = 'CRM_Contribute_BAO_ContributionPage';
3722 // Filter results by contribution page
3723 if (!empty($props['contribution_page_id'])) {
3724 $page = civicrm_api('contribution_page', 'getsingle', array(
3726 'id' => ($props['contribution_page_id']),
3728 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3729 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3733 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3734 case 'honor_type_id':
3735 $className = 'CRM_Contribute_BAO_ContributionSoft';
3736 $fieldName = 'soft_credit_type_id';
3737 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3740 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3744 * Validate financial type.
3748 * @param int $financialTypeId
3749 * Financial Type id.
3751 * @param string $relationName
3753 * @return array|bool
3755 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3756 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3757 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3759 if (!$financialAccount) {
3760 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3767 * Function to record additional payment for partial and refund contributions.
3769 * @param int $contributionId
3770 * is the invoice contribution id (got created after processing participant payment).
3771 * @param array $trxnsData
3772 * to take user provided input of transaction details.
3773 * @param string $paymentType
3774 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3775 * @param int $participantId
3777 * @return null|object
3779 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3780 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3781 $getInfoOf['id'] = $contributionId;
3782 $defaults = array();
3783 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3784 if (!$participantId) {
3785 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3788 if ($paymentType == 'owed') {
3789 // build params for recording financial trxn entry
3790 $params['contribution'] = $contributionDAO;
3791 $params = array_merge($defaults, $params);
3792 $params['skipLineItem'] = TRUE;
3793 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3794 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3795 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3796 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3799 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3800 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3801 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3803 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3804 if (!empty($trxnId)) {
3805 $trxnId = $trxnId['trxn_id'];
3807 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3808 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3811 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3812 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3813 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3817 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3818 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3819 FROM civicrm_financial_trxn ft
3820 LEFT JOIN civicrm_entity_financial_trxn eft
3821 ON (ft.id = eft.financial_trxn_id)
3822 WHERE eft.entity_table = 'civicrm_contribution'
3823 AND eft.entity_id = {$contributionId}
3824 AND ft.to_financial_account_id != {$toFinancialAccount}
3825 AND ft.status_id = {$statusId}
3827 $query = CRM_Core_DAO
::executeQuery($sql);
3829 $sumOfPayments = $query->sum_of_payments
;
3832 if ($contributionDAO->total_amount
== $sumOfPayments) {
3833 // update contribution status and
3834 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3835 $contributionDAO->contribution_status_id
= $statusId;
3836 $contributionDAO->cancel_date
= 'null';
3837 $contributionDAO->cancel_reason
= NULL;
3838 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3839 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3840 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3841 $contributionDAO->save();
3843 //Change status of financial record too
3844 $financialTrxn->status_id
= $statusId;
3845 $financialTrxn->save();
3847 // note : not using the self::add method,
3848 // the reason because it performs 'status change' related code execution for financial records
3849 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3850 // are coded below i.e. just updating financial_item status to 'Paid'
3852 if ($participantId) {
3853 // update participant status
3854 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3855 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3856 foreach ($ids as $val) {
3857 $participantUpdate['id'] = $val;
3858 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3859 CRM_Event_BAO_Participant
::add($participantUpdate);
3863 // update financial item statuses
3864 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3865 $paidStatus = array_search('Paid', $financialItemStatus);
3867 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3868 $sqlFinancialItemUpdate = "
3869 UPDATE civicrm_financial_item fi
3870 LEFT JOIN civicrm_entity_financial_trxn eft
3871 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3872 SET status_id = {$paidStatus}
3873 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3875 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3878 elseif ($paymentType == 'refund') {
3879 // build params for recording financial trxn entry
3880 $params['contribution'] = $contributionDAO;
3881 $params = array_merge($defaults, $params);
3882 $params['skipLineItem'] = TRUE;
3883 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3884 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3886 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3887 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3888 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3890 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3892 // note : not using the self::add method,
3893 // the reason because it performs 'status change' related code execution for financial records
3894 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3895 // are coded below i.e. just updating financial_item status to 'Paid'
3896 if ($updateStatus) {
3897 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3899 // add financial item entry
3900 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3901 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3902 if (!empty($lineItems)) {
3903 foreach ($lineItems as $lineItemId => $lineItemValue) {
3904 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3905 $addFinancialEntry = array(
3906 'transaction_date' => $financialTrxn->trxn_date
,
3907 'contact_id' => $contributionDAO->contact_id
,
3908 'amount' => round($paid, 2),
3909 'status_id' => array_search('Paid', $financialItemStatus),
3910 'entity_id' => $lineItemId,
3911 'entity_table' => 'civicrm_line_item',
3913 $trxnIds['id'] = $financialTrxn->id
;
3914 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3917 if ($participantId) {
3918 // update participant status
3919 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3920 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3921 foreach ($ids as $val) {
3922 $participantUpdate['id'] = $val;
3923 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3924 CRM_Event_BAO_Participant
::add($participantUpdate);
3929 // activity creation
3930 if (!empty($financialTrxn)) {
3931 if ($participantId) {
3932 $inputParams['id'] = $participantId;
3935 $component = 'event';
3936 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3937 $entityObj = $entityObj[$participantId];
3939 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3941 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3943 return $financialTrxn;
3949 * @param $activityType
3951 * @param int $contributionId
3953 * @throws CRM_Core_Exception
3955 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3956 if ($component == 'event') {
3957 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3958 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3959 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3960 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3961 $targetCid = $entityObj->contact_id
;
3962 // source record id would be the contribution id
3963 $srcRecId = $contributionId;
3967 $activityParams = array(
3968 'source_contact_id' => $targetCid,
3969 'source_record_id' => $srcRecId,
3970 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3974 'subject' => $subject,
3975 'activity_date_time' => $date,
3976 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3980 'skipRecentView' => TRUE,
3983 // create activity with target contacts
3984 $session = CRM_Core_Session
::singleton();
3985 $id = $session->get('userID');
3987 $activityParams['source_contact_id'] = $id;
3988 $activityParams['target_contact_id'][] = $targetCid;
3990 CRM_Activity_BAO_Activity
::create($activityParams);
3994 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3998 * @param bool $getTrxnInfo
3999 * @param bool $usingLineTotal
4003 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4004 if ($component == 'event') {
4005 $entity = 'participant';
4006 $entityTable = 'civicrm_participant';
4007 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4009 if (!$contributionId) {
4010 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4011 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4012 $id = $primaryParticipantId;
4014 if (!$contributionId) {
4020 $contributionId = $id;
4021 $entity = 'contribution';
4022 $entityTable = 'civicrm_contribution';
4025 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4026 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4028 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4029 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4031 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4032 // for additional participants
4033 if ($entityTable == 'civicrm_participant') {
4034 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
4036 foreach ($ids as $val) {
4037 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
4041 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
4045 $baseTrxnId = $total['trxn_id'];
4046 $total = $total['total_amount'];
4049 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4050 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4052 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
4053 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4054 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
4056 if ($paymentBalance == 0 && $contributionIsPayLater) {
4057 $paymentBalance = $total;
4060 $info['total'] = $total;
4061 $info['paid'] = $total - $paymentBalance;
4062 $info['balance'] = $paymentBalance;
4064 $info['component'] = $component;
4065 $info['payLater'] = $contributionIsPayLater;
4067 if ($getTrxnInfo && $baseTrxnId) {
4068 $arRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4069 $arAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $arRelationTypeId);
4071 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4073 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4075 ft.payment_instrument_id,
4076 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency
4078 FROM civicrm_contribution con
4079 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4080 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4081 AND ft.to_financial_account_id != %2
4082 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4083 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4084 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4086 WHERE con.id = %1 AND ft.to_financial_account_id <> %3
4088 $queryParams = array(
4089 1 => array($contributionId, 'Integer'),
4090 2 => array($feeFinancialAccount, 'Integer'),
4091 3 => array($arAccount, 'Integer'),
4093 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4094 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4096 while ($resultDAO->fetch()) {
4097 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4098 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4100 'total_amount' => $resultDAO->total_amount
,
4101 'financial_type' => $resultDAO->financial_account
,
4102 'payment_instrument' => $paidByLabel,
4103 'receive_date' => $resultDAO->trxn_date
,
4104 'trxn_id' => $resultDAO->trxn_id
,
4105 'status' => $statuses[$resultDAO->status_id
],
4106 'currency' => $resultDAO->currency
,
4108 if ($paidByName == 'Check') {
4109 $val['check_number'] = $resultDAO->check_number
;
4113 $info['transaction'] = $rows;
4119 * Get financial account id has 'Sales Tax Account is' account relationship with financial type.
4121 * @param int $financialTypeId
4124 * Financial Account Id
4126 public static function getFinancialAccountId($financialTypeId) {
4127 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4128 $searchParams = array(
4129 'entity_table' => 'civicrm_financial_type',
4130 'entity_id' => $financialTypeId,
4131 'account_relationship' => $accountRel,
4134 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4136 return CRM_Utils_Array
::value('financial_account_id', $result);
4140 * Get the tax amount (misnamed function).
4142 * @param array $params
4143 * @param bool $isLineItem
4147 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4148 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4150 // Update contribution.
4151 if (!empty($params['id'])) {
4152 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4153 // there are no tax implications - early return.
4154 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4157 if (empty($params['prevContribution'])) {
4158 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4161 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4162 if (!isset($params[$field])) {
4163 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4164 // Tax amount gets added back on later....
4165 $params['total_amount'] = $params['prevContribution']->total_amount
-
4166 $params['prevContribution']->tax_amount
;
4169 $params[$field] = $params['prevContribution']->$field;
4170 if ($params[$field] != $params['prevContribution']->$field) {
4176 self
::calculateMissingAmountParams($params, $params['id']);
4177 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4178 // Assign tax Amount on update of contribution
4179 if (!empty($params['prevContribution']->tax_amount
)) {
4180 $params['tax_amount'] = 'null';
4181 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4182 foreach ($params['line_item'] as $setID => $priceField) {
4183 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4184 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4191 // New Contribution and update of contribution with tax rate financial type
4192 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4193 empty($params['skipLineItem']) && !$isLineItem
4195 $taxRateParams = $taxRates[$params['financial_type_id']];
4196 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4197 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4199 // Get Line Item on update of contribution
4200 if (isset($params['id'])) {
4201 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4204 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4206 foreach ($params['line_item'] as $setID => $priceField) {
4207 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4208 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4211 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4213 elseif (isset($params['api.line_item.create'])) {
4214 // Update total amount of contribution using lineItem
4215 $taxAmountArray = array();
4216 foreach ($params['api.line_item.create'] as $key => $value) {
4217 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4218 $taxRate = $taxRates[$value['financial_type_id']];
4219 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4220 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4223 $params['tax_amount'] = array_sum($taxAmountArray);
4224 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4227 // update line item of contrbution
4228 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4229 $taxRate = $taxRates[$params['financial_type_id']];
4230 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4231 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4238 * Check financial type validation on update of a contribution.
4240 * @param Integer $financialTypeId
4241 * Value of latest Financial Type.
4243 * @param Integer $contributionId
4246 * @param array $errors
4251 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4252 if (!empty($financialTypeId)) {
4253 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4254 if ($oldFinancialTypeId == $financialTypeId) {
4258 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4260 '1' => array($contributionId, 'Integer'),
4262 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4263 if ($result->N
> 1) {
4264 $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.');
4269 * Update related pledge payment payments.
4271 * This function has been refactored out of the back office contribution form and may
4272 * still overlap with other functions.
4274 * @param string $action
4275 * @param int $pledgePaymentID
4276 * @param int $contributionID
4277 * @param bool $adjustTotalAmount
4278 * @param float $total_amount
4279 * @param float $original_total_amount
4280 * @param int $contribution_status_id
4281 * @param int $original_contribution_status_id
4283 public static function updateRelatedPledge(
4289 $original_total_amount,
4290 $contribution_status_id,
4291 $original_contribution_status_id
4293 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4297 if ($pledgePaymentID) {
4298 //store contribution id in payment record.
4299 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4302 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4309 if (!$pledgePaymentID) {
4312 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4318 $updatePledgePaymentStatus = FALSE;
4320 // If either the status or the amount has changed we update the pledge status.
4321 if ($action & CRM_Core_Action
::ADD
) {
4322 $updatePledgePaymentStatus = TRUE;
4324 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4325 ($original_total_amount != $total_amount))
4327 $updatePledgePaymentStatus = TRUE;
4330 if ($updatePledgePaymentStatus) {
4331 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4332 array($pledgePaymentID),
4333 $contribution_status_id,
4342 * Compute the stats values
4344 * @param $stat either 'mode' or 'median'
4346 * @param $alias of civicrm_contribution
4348 public static function computeStats($stat, $sql, $alias = NULL) {
4349 $mode = $median = array();
4352 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4353 while ($modeDAO->fetch()) {
4354 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4355 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4364 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4365 foreach ($currencies as $currency => $val) {
4367 $where = "AND {$alias}.currency = '{$currency}'";
4368 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4372 $medianRow = floor($rowCount / 2);
4373 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4379 $medianValue = "SELECT {$alias}.total_amount as median
4381 ORDER BY median LIMIT {$medianRow},{$offset}";
4382 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4383 while ($medianValDAO->fetch()) {
4385 $midValue = $midValue +
$medianValDAO->median
;
4388 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4392 $midValue = $midValue / 2;
4393 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4404 * Is there only one line item attached to the contribution.
4410 * @throws \CiviCRM_API3_Exception
4412 public static function isSingleLineItem($id) {
4413 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4414 return ($lineItemCount == 1);
4418 * Complete an order.
4420 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4422 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4424 * Moving it out of the BaseIPN class is just the first step.
4426 * @param array $input
4428 * @param array $objects
4429 * @param CRM_Core_Transaction $transaction
4431 * @param CRM_Contribute_BAO_Contribution $contribution
4432 * @param bool $isRecurring
4433 * Duplication of param needs review. Only used by AuthorizeNetIPN
4434 * @param int $isFirstOrLastRecurringPayment
4435 * Deprecated param only used by AuthorizeNetIPN.
4437 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4438 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4439 // The previous details are used when calculating line items so keep it before any code that 'does something'
4440 if (!empty($contribution->id
)) {
4441 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4442 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4444 $inputContributionWhiteList = array(
4449 'payment_instrument_id',
4454 'contribution_status_id',
4456 if (self
::isSingleLineItem($primaryContributionID)) {
4457 $inputContributionWhiteList[] = 'financial_type_id';
4460 $participant = CRM_Utils_Array
::value('participant', $objects);
4461 $memberships = CRM_Utils_Array
::value('membership', $objects);
4462 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4463 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4464 $event = CRM_Utils_Array
::value('event', $objects);
4466 $paymentProcessorId = '';
4467 if (isset($objects['paymentProcessor'])) {
4468 if (is_array($objects['paymentProcessor'])) {
4469 $paymentProcessorId = $objects['paymentProcessor']['id'];
4472 $paymentProcessorId = $objects['paymentProcessor']->id
;
4476 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4478 $contributionParams = array_merge(array(
4479 'contribution_status_id' => $completedContributionStatusID,
4480 'source' => self
::getRecurringContributionDescription($contribution, $event),
4481 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4483 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4485 if ($recurringContributionID) {
4486 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4488 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4490 if (empty($contributionParams['receive_date']) && $changeDate) {
4491 $contributionParams['receive_date'] = $changeDate;
4494 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4495 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4497 if (is_numeric($memberships)) {
4498 $memberships = array($objects['membership']);
4502 if (isset($input['is_email_receipt'])) {
4503 $values['is_email_receipt'] = $input['is_email_receipt'];
4506 if ($input['component'] == 'contribute') {
4507 if ($contribution->contribution_page_id
) {
4508 // Figure out what we gain from this.
4509 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4511 elseif ($recurContrib && $recurringContributionID) {
4512 $values['amount'] = $recurContrib->amount
;
4513 $values['financial_type_id'] = $objects['contributionType']->id
;
4514 $values['title'] = $source = ts('Offline Recurring Contribution');
4517 if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
4518 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4519 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4520 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4523 if (!empty($memberships)) {
4524 foreach ($memberships as $membershipTypeIdKey => $membership) {
4526 $membershipParams = array(
4527 'id' => $membership->id
,
4528 'contact_id' => $membership->contact_id
,
4529 'is_test' => $membership->is_test
,
4530 'membership_type_id' => $membership->membership_type_id
,
4533 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4534 $membershipParams['membership_type_id'],
4535 $membershipParams['is_test'],
4536 $membershipParams['id']
4539 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4540 // this picks up membership type changes during renewals
4542 SELECT membership_type_id
4543 FROM civicrm_membership_log
4544 WHERE membership_id={$membershipParams['id']}
4547 $dao = CRM_Core_DAO
::executeQuery($sql);
4548 if ($dao->fetch()) {
4549 if (!empty($dao->membership_type_id
)) {
4550 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4555 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4556 $membershipParams['membership_type_id'],
4557 $primaryContributionID
4559 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4560 if ($currentMembership) {
4562 * Fixed FOR CRM-4433
4563 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4564 * when Contribution mode is notify and membership is for renewal )
4566 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4568 // @todo - we should pass membership_type_id instead of null here but not
4569 // adding as not sure of testing
4570 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4571 $changeDate, NULL, $membershipParams['num_terms']
4574 $dates['join_date'] = $currentMembership['join_date'];
4577 //get the status for membership.
4578 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4580 $dates['join_date'],
4583 $membershipParams['membership_type_id'],
4587 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4588 //we might be renewing membership,
4589 //so make status override false.
4590 $membershipParams['is_override'] = FALSE;
4591 //CRM-17723 - reset static $relatedContactIds array()
4593 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4594 civicrm_api3('Membership', 'create', $membershipParams);
4600 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4601 if ($event->is_email_confirm
) {
4602 // @todo this should be set by the function that sends the mail after sending.
4603 $contributionParams['receipt_date'] = $changeDate;
4605 $participantParams['id'] = $participant->id
;
4606 $participantParams['status_id'] = 'Registered';
4607 civicrm_api3('Participant', 'create', $participantParams);
4611 $contributionParams['id'] = $contribution->id
;
4613 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4614 // unsetting it here does NOT cause any other contribution test to fail!
4615 unset($contributionParams['financial_type_id']);
4616 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4618 // Add new soft credit against current $contribution.
4619 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4620 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4623 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4624 'labelColumn' => 'name',
4627 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4628 $input['payment_processor'] = $paymentProcessorId;
4631 if (!empty($contribution->_relatedObjects
['participant'])) {
4632 $input['contribution_mode'] = 'participant';
4633 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4635 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4636 $input['contribution_mode'] = 'membership';
4637 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4638 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4639 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4642 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4643 $transaction->commit();
4645 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4646 $contributionParams['contribution_status_id'], $input['amount']);
4648 // create an activity record
4649 if ($input['component'] == 'contribute') {
4651 $targetContactID = NULL;
4652 if (!empty($ids['related_contact'])) {
4653 $targetContactID = $contribution->contact_id
;
4654 $contribution->contact_id
= $ids['related_contact'];
4656 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4660 CRM_Activity_BAO_Activity
::addActivity($participant);
4663 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4664 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4665 if (!array_key_exists('is_email_receipt', $values) ||
4666 $values['is_email_receipt'] == 1
4668 civicrm_api3('Contribution', 'sendconfirmation', array(
4669 'id' => $contribution->id
,
4670 'payment_processor_id' => $paymentProcessorId,
4672 CRM_Core_Error
::debug_log_message("Receipt sent");
4675 CRM_Core_Error
::debug_log_message("Success: Database updated");
4677 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4678 $isFirstOrLastRecurringPayment);
4680 return $contributionResult;
4684 * Send receipt from contribution.
4686 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4688 * Note that the compose message part has been moved to contribution
4689 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4691 * @param array $input
4692 * Incoming data from Payment processor.
4694 * Related object IDs.
4695 * @param int $contributionID
4696 * @param array $values
4697 * Values related to objects that have already been loaded.
4698 * @param bool $recur
4699 * Is it part of a recurring contribution.
4700 * @param bool $returnMessageText
4701 * Should text be returned instead of sent. This.
4702 * is because the function is also used to generate pdfs
4705 * @throws \CRM_Core_Exception
4706 * @throws \CiviCRM_API3_Exception
4708 public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE,
4709 $returnMessageText = FALSE) {
4710 $input['is_recur'] = $recur;
4712 $contribution = new CRM_Contribute_BAO_Contribution();
4713 $contribution->id
= $contributionID;
4714 if (!$contribution->find(TRUE)) {
4715 throw new CRM_Core_Exception('Contribution does not exist');
4717 $contribution->loadRelatedObjects($input, $ids, TRUE);
4718 // set receipt from e-mail and name in value
4719 if (!$returnMessageText) {
4720 $session = CRM_Core_Session
::singleton();
4721 $userID = $session->get('userID');
4722 if (!empty($userID)) {
4723 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4724 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4725 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4729 $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4730 // Contribution ID should really always be set. But ?
4731 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4732 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4738 * Generate credit note id with next avaible number
4743 public static function createCreditNoteId() {
4744 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4746 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4747 $creditNoteId = NULL;
4751 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4752 $result = civicrm_api3('Contribution', 'getcount', array(
4754 'creditnote_id' => $creditNoteId,
4756 } while ($result > 0);
4758 return $creditNoteId;
4762 * Load related memberships.
4764 * Note that in theory it should be possible to retrieve these from the line_item table
4765 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4766 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4767 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4768 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4770 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4776 public function loadRelatedMembershipObjects(&$ids) {
4778 SELECT membership_id
4779 FROM civicrm_membership_payment
4780 WHERE contribution_id = %1 ";
4781 $params = array(1 => array($this->id
, 'Integer'));
4783 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4784 while ($dao->fetch()) {
4785 if ($dao->membership_id
) {
4786 if (!is_array($ids['membership'])) {
4787 $ids['membership'] = array();
4789 $ids['membership'][] = $dao->membership_id
;
4793 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4794 foreach ($ids['membership'] as $id) {
4796 $membership = new CRM_Member_BAO_Membership();
4797 $membership->id
= $id;
4798 if (!$membership->find(TRUE)) {
4799 throw new Exception("Could not find membership record: $id");
4801 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4802 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4803 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4804 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4805 $membership->free();
4812 * This function is used to record partial payments for contribution
4814 * @param array $contribution
4816 * @param array $params
4820 public static function recordPartialPayment($contribution, $params) {
4821 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4822 $pendingStatus = array(
4823 array_search('Pending', $contributionStatuses),
4824 array_search('In Progress', $contributionStatuses),
4826 $statusId = array_search('Completed', $contributionStatuses);
4827 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4828 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4829 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4831 elseif (!empty($params['payment_processor'])) {
4832 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4834 elseif (!empty($params['payment_instrument_id'])) {
4835 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4838 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4839 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4840 $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);
4842 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4843 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4844 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4845 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4846 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4847 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4848 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4849 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4850 $balanceTrxnParams['currency'] = $contribution['currency'];
4851 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4852 $balanceTrxnParams['status_id'] = $statusId;
4853 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4854 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4855 if ($fromFinancialAccountId != NULL &&
4856 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4858 $balanceTrxnParams['is_payment'] = 1;
4860 if (!empty($params['payment_processor'])) {
4861 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4863 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4867 * Get the description (source field) for the recurring contribution.
4869 * @param CRM_Contribute_BAO_Contribution $contribution
4870 * @param CRM_Event_DAO_Event|null $event
4873 * @throws \CiviCRM_API3_Exception
4875 protected static function getRecurringContributionDescription($contribution, $event) {
4876 if (!empty($contribution->source
)) {
4877 return $contribution->source
;
4879 elseif (!empty($contribution->contribution_page_id
)) {
4880 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4881 'id' => $contribution->contribution_page_id
,
4882 'return' => 'title',
4884 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4887 return ts('Online Event Registration') . ': ' . $event->title
;
4889 elseif (!empty($contribution->contribution_recur_id
)) {
4890 return 'recurring contribution';
4896 * Function to add payments for contribution
4897 * for Partially Paid status
4899 * @param array $lineItems
4900 * @param array $contributions
4901 * @param array $contributionStatusId
4904 public static function addPayments($lineItems, $contributions, $contributionStatusId = NULL) {
4905 // get financial trxn which is a payment
4906 $ftSql = "SELECT ft.id, ft.total_amount
4907 FROM civicrm_financial_trxn ft
4908 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4909 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4910 $sql = "SELECT fi.id, li.price_field_value_id
4911 FROM civicrm_financial_item fi
4912 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4913 WHERE li.contribution_id = %1";
4914 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4915 'labelColumn' => 'name',
4917 foreach ($contributions as $k => $contribution) {
4918 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4919 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4923 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4925 $trxnAmount = $ftDao->total_amount
;
4928 // get financial item
4929 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4930 while ($dao->fetch()) {
4931 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4935 'entity_table' => 'civicrm_financial_item',
4936 'financial_trxn_id' => $ftId,
4938 foreach ($lineItems as $key => $value) {
4939 if ($value['qty'] == 0) {
4942 $paid = $value['line_total'] * ($trxnAmount / $contribution->total_amount
);
4943 // Record Entity Financial Trxn
4944 $params['amount'] = round($paid, 2);
4945 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4947 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4953 * Function use to store line item proportionaly in
4954 * in entity financial trxn table
4956 * @param array $params
4957 * array of contribution params.
4958 * @param object $trxn
4959 * CRM_Financial_DAO_FinancialTrxn object
4960 * @param array $contribution
4963 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4964 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4965 if (!empty($lineItems)) {
4966 // get financial item
4967 $sql = "SELECT fi.id, li.price_field_value_id
4968 FROM civicrm_financial_item fi
4969 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4970 WHERE li.contribution_id = %1";
4971 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4972 while ($dao->fetch()) {
4973 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4976 'entity_table' => 'civicrm_financial_item',
4977 'financial_trxn_id' => $trxn->id
,
4979 foreach ($lineItems as $key => $value) {
4980 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4981 // Record Entity Financial Trxn
4982 $eftParams['amount'] = round($paid, 2);
4983 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4985 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4991 * Function to check line items
4993 * @param array $params
4994 * array of order params.
4997 public static function checkLineItems(&$params) {
4998 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4999 $lineItemAmount = 0;
5000 foreach ($params['line_items'] as &$lineItems) {
5001 foreach ($lineItems['line_item'] as &$item) {
5002 if (empty($item['financial_type_id'])) {
5003 $item['financial_type_id'] = $params['financial_type_id'];
5005 $lineItemAmount +
= $item['line_total'];
5008 if (!isset($totalAmount)) {
5009 $params['total_amount'] = $lineItemAmount;
5011 elseif ($totalAmount != $lineItemAmount) {
5012 throw new API_Exception("Line item total doesn't match with total amount.");
5017 * Get the financial account for the item associated with the new transaction.
5019 * @param array $params
5020 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
5024 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
5026 if (!empty($params['financial_account_id'])) {
5027 return $params['financial_account_id'];
5029 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5030 $preferredAccountsRelationships = array(
5031 'Refunded' => 'Credit/Contra Revenue Account is',
5032 'Chargeback' => 'Chargeback Account is',
5034 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5035 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5036 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5038 $preferredAccountsRelationships[$contributionStatus]
5041 return $prevFinancialItem->financial_account_id
;
5045 * ContributionPage values were being imposed onto values.
5047 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5048 * REALLY didn't want superimposed. The rest are left there in their overkill out
5051 * The rationale for making this explicit is that it was a case of carefully set values being
5052 * seemingly randonly overwritten without much care. In general I think array randomly setting
5053 * variables en mass is risky.
5055 * @param array $values
5059 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5060 $contributionPageValues = array();
5061 CRM_Contribute_BAO_ContributionPage
::setValues(
5062 $this->contribution_page_id
,
5063 $contributionPageValues
5065 $valuesToCopy = array(
5066 // These are the values that I believe to be useful.
5070 'pay_later_receipt',
5072 'receipt_from_email',
5073 'receipt_from_name',
5077 'honoree_profile_id',
5078 'onbehalf_profile_id',
5079 'honor_block_is_active',
5080 // Kinda might be - but would be on the contribution...
5083 // Included for 'fear of regression' but can't justify any use for these....
5085 'payment_processor',
5086 'financial_type_id',
5087 'amount_block_is_active',
5092 'default_amount_id',
5096 'initial_amount_help_text',
5097 'initial_amount_label',
5099 'is_allow_other_amount',
5100 'is_billing_required',
5101 'is_confirm_enabled',
5102 'is_credit_card_only',
5104 'is_partial_payment',
5105 'is_recur_installments',
5106 'is_recur_interval',
5110 'min_initial_amount',
5111 'recur_frequency_unit',
5118 foreach ($valuesToCopy as $valueToCopy) {
5119 if (isset($contributionPageValues[$valueToCopy])) {
5120 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5127 * Get values of CiviContribute Settings
5128 * and check if its enabled or not.
5129 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5130 * in serialized form. Usually this should be stored as flat settings for each form fields
5131 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5132 * settings we will live with an inconsistency because it's too hard to change for now.
5133 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5136 * @param string $name
5140 public static function checkContributeSettings($name = NULL) {
5141 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5144 return CRM_Utils_Array
::value($name, $contributeSettings);
5146 return $contributeSettings;
5150 * This function process contribution related objects.
5152 * @param int $contributionId
5153 * @param int $statusId
5154 * @param int|null $previousStatusId
5156 * @param string $receiveDate
5158 * @return null|string
5160 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5162 if (!$contributionId ||
!$statusId) {
5167 'contribution_id' => $contributionId,
5168 'contribution_status_id' => $statusId,
5169 'previous_contribution_status_id' => $previousStatusId,
5170 'receive_date' => $receiveDate,
5173 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5175 if (!is_array($updateResult) ||
5176 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5177 !is_array($updatedComponents) ||
5178 empty($updatedComponents)
5183 // get the user display name.
5185 SELECT display_name as displayName
5186 FROM civicrm_contact
5187 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5188 WHERE civicrm_contribution.id = {$contributionId}";
5189 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5191 // get the status message for user.
5192 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5194 if ($componentName == 'CiviMember') {
5195 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5196 CRM_Member_PseudoConstant
::membershipStatus()
5198 if ($updatedStatusName == 'Cancelled') {
5199 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5201 elseif ($updatedStatusName == 'Expired') {
5202 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5205 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5207 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5209 1 => $userDisplayName,
5217 if ($componentName == 'CiviEvent') {
5218 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5219 CRM_Event_PseudoConstant
::participantStatus()
5221 if ($updatedStatusName == 'Cancelled') {
5222 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5224 elseif ($updatedStatusName == 'Registered') {
5225 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5229 if ($componentName == 'CiviPledge') {
5230 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5231 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5233 if ($updatedStatusName == 'Cancelled') {
5234 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5236 elseif ($updatedStatusName == 'Failed') {
5237 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5239 elseif ($updatedStatusName == 'Completed') {
5240 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5249 * Get the contribution as it is in the database before being updated.
5251 * @param int $contributionID
5255 private static function getOriginalContribution($contributionID) {
5256 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5260 * Assign Test Value.
5262 * @param string $fieldName
5263 * @param array $fieldDef
5264 * @param int $counter
5266 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5267 if ($fieldName == 'tax_amount') {
5268 $this->{$fieldName} = "0.00";
5270 elseif ($fieldName == 'net_amount') {
5271 $this->{$fieldName} = "2.00";
5273 elseif ($fieldName == 'total_amount') {
5274 $this->{$fieldName} = "3.00";
5276 elseif ($fieldName == 'fee_amount') {
5277 $this->{$fieldName} = "1.00";
5280 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5285 * Check if contribution has participant/membership payment.
5287 * @param int $contributionId
5292 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5293 // get line item for contribution
5294 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution', NULL, TRUE, TRUE);
5295 // check if line item is for membership or participant
5296 foreach ($lineItems as $items) {
5297 if ($items['entity_table'] == 'civicrm_participant') {
5301 elseif ($items['entity_table'] == 'civicrm_membership') {
5313 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5315 * @param array $trxnParams
5316 * Financial trxn params
5317 * @param string $contributionParams
5318 * Contribution Params
5322 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5323 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5326 $statusId = $contributionParams['contribution']->contribution_status_id
;
5327 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5328 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5329 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5330 // Return if contribution status is not completed.
5331 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5332 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5333 && $contributionParams['prevContribution']->is_pay_later
== 0
5339 $params = $trxnParams;
5340 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5341 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
5342 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
5343 $params['to_financial_account_id'] = $arAccountId;
5344 $params['status_id'] = array_search('Pending', $contributionStatuses);
5345 $params['is_payment'] = FALSE;
5346 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5347 self
::$_trxnIDs[] = $trxn->id
;
5348 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];