3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Static field to hold financial trxn id's.
54 static $_trxnIDs = NULL;
57 * Field for all the objects related to this contribution
58 * @var array of objects (e.g membership object, participant object)
60 public $_relatedObjects = array();
63 * Field for the component - either 'event' (participant) or 'contribute'
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
68 * @var string component or event
70 public $_component = NULL;
73 * Possibly obsolete variable.
75 * If you use it please explain why it is set in the create function here.
79 public $trxn_result_code;
84 public function __construct() {
85 parent
::__construct();
89 * Takes an associative array and creates a contribution object.
91 * the function extract all the params it needs to initialize the create a
92 * contribution object. the params array could contain additional unused name/value
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
98 * The array that holds all the db ids.
100 * @return CRM_Contribute_BAO_Contribution|void
102 public static function add(&$params, $ids = array()) {
103 if (empty($params)) {
106 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
107 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
108 $duplicates = array();
109 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
110 $error = CRM_Core_Error
::singleton();
111 $d = implode(', ', $duplicates);
112 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
115 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
120 // first clean up all the money fields
121 $moneyFields = array(
125 'non_deductible_amount',
128 //if priceset is used, no need to cleanup money
129 if (!empty($params['skipCleanMoney'])) {
130 unset($moneyFields[0]);
133 foreach ($moneyFields as $field) {
134 if (isset($params[$field])) {
135 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
139 //set defaults in create mode
140 if (!$contributionID) {
141 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
144 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
145 //if contribution is created with cancelled or refunded status, add credit note id
146 if (!empty($params['contribution_status_id'])) {
147 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
148 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
149 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
151 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
152 $params['creditnote_id'] = self
::createCreditNoteId();
157 // Since the fee amount is expecting this (later on) ensure it is always set.
158 // It would only not be set for an update where it is unchanged.
159 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
163 && CRM_Utils_Array
::value('membership_id', $params)
164 && self
::checkContributeSettings('deferred_revenue_enabled')
166 $memberStartDate = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
167 if ($memberStartDate) {
168 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
171 self
::calculateMissingAmountParams($params, $contributionID);
173 if (!empty($params['payment_instrument_id'])) {
174 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
175 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
176 $params['check_number'] = 'null';
180 $setPrevContribution = TRUE;
181 // CRM-13964 partial payment
182 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
183 $partialAmtTotal = $params['partial_payment_total'];
184 $partialAmtPay = $params['partial_amount_pay'];
185 $params['total_amount'] = $partialAmtTotal;
186 if ($partialAmtPay < $partialAmtTotal) {
187 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
188 $params['is_pay_later'] = 0;
189 $setPrevContribution = FALSE;
192 if ($contributionID && $setPrevContribution) {
193 $params['prevContribution'] = self
::getOriginalContribution($contributionID);
196 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
197 && !($contributionStatus[$params['prevContribution']->contribution_status_id
] == 'Pending')
198 && !self
::allowUpdateRevenueRecognitionDate($contributionID)
200 unset($params['revenue_recognition_date']);
203 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
204 isset($params['financial_type_id']))) {
205 $params = CRM_Contribute_BAO_Contribution
::checkTaxAmount($params);
208 if ($contributionID) {
209 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
212 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
214 $contribution = new CRM_Contribute_BAO_Contribution();
215 $contribution->copyValues($params);
217 $contribution->id
= $contributionID;
219 if (empty($contribution->id
)) {
220 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
221 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
222 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
226 $result = $contribution->save();
228 // Add financial_trxn details as part of fix for CRM-4724
229 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
230 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
232 //add Account details
233 $params['contribution'] = $contribution;
234 self
::recordFinancialAccounts($params);
236 if (self
::isUpdateToRecurringContribution($params)) {
237 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
238 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
239 $contributionStatus[$params['contribution_status_id']]
243 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
245 if ($contributionID) {
246 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
249 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
256 * Is this contribution updating an existing recurring contribution.
258 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
259 * pending payment is being confirmed (or failing).
261 * @param array $params
265 public static function isUpdateToRecurringContribution($params) {
266 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
269 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
272 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
275 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
276 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
283 * Get defaults for new entity.
286 public static function getDefaults() {
288 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
289 FALSE, FALSE, FALSE, 'AND is_default = 1')
291 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
296 * Fetch the object and store the values in the values array.
298 * @param array $params
299 * Input parameters to find object.
300 * @param array $values
301 * Output values of the object.
303 * The array that holds all the db ids.
305 * @return CRM_Contribute_BAO_Contribution|null
306 * The found object or null
308 public static function getValues($params, &$values, &$ids) {
309 if (empty($params)) {
312 $contribution = new CRM_Contribute_BAO_Contribution();
314 $contribution->copyValues($params);
316 if ($contribution->find(TRUE)) {
317 $ids['contribution'] = $contribution->id
;
319 CRM_Core_DAO
::storeValues($contribution, $values);
321 return $contribution;
323 $null = NULL; // return by reference
328 * Get the values and resolve the most common mappings.
330 * Since contribution status is resolved in almost every function that calls getValues it makes
331 * sense to have an extra function to resolve it rather than repeat the code.
333 * Think carefully before adding more mappings to be resolved as there could be performance implications
334 * if this function starts to be called from more iterative functions.
336 * @param array $params
337 * Input parameters to find object.
340 * Array of the found contribution.
341 * @throws CRM_Core_Exception
343 public static function getValuesWithMappings($params) {
344 $values = $ids = array();
345 $contribution = self
::getValues($params, $values, $ids);
346 if (is_null($contribution)) {
347 throw new CRM_Core_Exception('No contribution found');
349 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
354 * Calculate net_amount & fee_amount if they are not set.
356 * Net amount should be total - fee.
357 * This should only be called for new contributions.
359 * @param array $params
360 * Params for a new contribution before they are saved.
361 * @param int|null $contributionID
362 * Contribution ID if we are dealing with an update.
364 * @throws \CiviCRM_API3_Exception
366 public static function calculateMissingAmountParams(&$params, $contributionID) {
367 if (!$contributionID && !isset($params['fee_amount'])) {
368 if (isset($params['total_amount']) && isset($params['net_amount'])) {
369 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
372 $params['fee_amount'] = 0;
375 if (!isset($params['net_amount'])) {
376 if (!$contributionID) {
377 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
380 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
381 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
382 // net_amount may need adjusting.
383 $contribution = civicrm_api3('Contribution', 'getsingle', array(
384 'id' => $contributionID,
385 'return' => array('total_amount', 'net_amount'),
387 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
388 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
389 $params['net_amount'] = $totalAmount - $feeAmount;
397 * @param $billingLocationTypeID
401 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
402 $hasBillingField = FALSE;
403 $billingFields = array(
411 //build address array
412 $addressParams = array();
413 $addressParams['location_type_id'] = $billingLocationTypeID;
414 $addressParams['is_billing'] = 1;
416 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
417 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
418 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
419 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
421 foreach ($billingFields as $value) {
422 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
423 if (!empty($addressParams[$value])) {
424 $hasBillingField = TRUE;
427 return array($hasBillingField, $addressParams);
431 * Get address params ready to be passed to the payment processor.
433 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
434 * To create an address we need state_province_id.
436 * @param array $params
437 * @param int $billingLocationTypeID
441 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
442 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
443 foreach ($addressParams as $name => $field) {
444 if (substr($name, 0, 8) == 'billing_') {
445 $addressParams[substr($name, 9)] = $addressParams[$field];
448 return array($hasBillingField, $addressParams);
452 * Get the number of terms for this contribution for a given membership type
453 * based on querying the line item table and relevant price field values
454 * Note that any one contribution should only be able to have one line item relating to a particular membership
457 * @param int $membershipTypeID
459 * @param int $contributionID
463 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
464 $numTerms = CRM_Core_DAO
::singleValueQuery("
465 SELECT membership_num_terms FROM civicrm_line_item li
466 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
467 WHERE contribution_id = %1 AND membership_type_id = %2",
468 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
470 // default of 1 is precautionary
471 return empty($numTerms) ?
1 : $numTerms;
475 * Takes an associative array and creates a contribution object.
477 * @param array $params
478 * (reference ) an assoc array of name/value pairs.
480 * The array that holds all the db ids.
482 * @return CRM_Contribute_BAO_Contribution
484 public static function create(&$params, $ids = array()) {
485 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
486 foreach ($dateFields as $df) {
487 if (isset($params[$df])) {
488 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
492 //if contribution is created with cancelled or refunded status, add credit note id
493 if (!empty($params['contribution_status_id'])) {
494 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
496 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
497 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
499 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
500 $params['creditnote_id'] = self
::createCreditNoteId();
505 $transaction = new CRM_Core_Transaction();
507 $contribution = self
::add($params, $ids);
509 if (is_a($contribution, 'CRM_Core_Error')) {
510 $transaction->rollback();
511 return $contribution;
514 $params['contribution_id'] = $contribution->id
;
516 if (!empty($params['custom']) &&
517 is_array($params['custom'])
519 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
522 $session = CRM_Core_Session
::singleton();
524 if (!empty($params['note'])) {
526 'entity_table' => 'civicrm_contribution',
527 'note' => $params['note'],
528 'entity_id' => $contribution->id
,
529 'contact_id' => $session->get('userID'),
530 'modified_date' => date('Ymd'),
532 if (!$noteParams['contact_id']) {
533 $noteParams['contact_id'] = $params['contact_id'];
535 CRM_Core_BAO_Note
::add($noteParams);
538 // make entry in batch entity batch table
539 if (!empty($params['batch_id'])) {
540 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
541 $titleFields = array(
547 $retrieveRequired = 0;
548 foreach ($titleFields as $titleField) {
549 if (!isset($contribution->$titleField)) {
550 $retrieveRequired = 1;
554 if ($retrieveRequired == 1) {
555 $contribution->find(TRUE);
559 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
561 $transaction->commit();
563 // check if activity record exist for this contribution, if
565 $activity = new CRM_Activity_DAO_Activity();
566 $activity->source_record_id
= $contribution->id
;
567 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
572 //CRM-18406: Update activity when edit contribution.
573 if ($activity->find(TRUE)) {
574 // CRM-13237 : if activity record found, update it with campaign id of contribution
575 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
576 $contribution->activity_id
= $activity->id
;
578 if (empty($contribution->contact_id
)) {
579 $contribution->find(TRUE);
581 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
583 // do not add to recent items for import, CRM-4399
584 if (empty($params['skipRecentView'])) {
585 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
586 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
588 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
589 $titleFields = array(
595 $retrieveRequired = 0;
596 foreach ($titleFields as $titleField) {
597 if (!isset($contribution->$titleField)) {
598 $retrieveRequired = 1;
602 if ($retrieveRequired == 1) {
603 $contribution->find(TRUE);
605 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
606 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
608 $recentOther = array();
609 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
610 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
611 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
615 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
616 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
617 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
621 // add the recently created Contribution
622 CRM_Utils_Recent
::add($title,
626 $contribution->contact_id
,
632 return $contribution;
636 * Get the values for pseudoconstants for name->value and reverse.
638 * @param array $defaults
639 * (reference) the default values, some of which need to be resolved.
640 * @param bool $reverse
641 * True if we want to resolve the values in the reverse direction (value -> name).
643 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
644 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
645 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
646 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
647 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
651 * Convert associative array names to values and vice-versa.
653 * This function is used by both the web form layer and the api. Note that
654 * the api needs the name => value conversion, also the view layer typically
655 * requires value => name conversion
657 * @param array $defaults
658 * @param string $property
659 * @param array $lookup
660 * @param bool $reverse
664 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
665 $id = $property . '_id';
667 $src = $reverse ?
$property : $id;
668 $dst = $reverse ?
$id : $property;
670 if (!array_key_exists($src, $defaults)) {
674 $look = $reverse ?
array_flip($lookup) : $lookup;
676 if (is_array($look)) {
677 if (!array_key_exists($defaults[$src], $look)) {
681 $defaults[$dst] = $look[$defaults[$src]];
686 * Retrieve DB object based on input parameters.
688 * It also stores all the retrieved values in the default array.
690 * @param array $params
691 * (reference ) an assoc array of name/value pairs.
692 * @param array $defaults
693 * (reference ) an assoc array to hold the name / value pairs.
694 * in a hierarchical manner
696 * (reference) the array that holds all the db ids.
698 * @return CRM_Contribute_BAO_Contribution
700 public static function retrieve(&$params, &$defaults, &$ids) {
701 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
702 return $contribution;
706 * Combine all the importable fields from the lower levels object.
708 * The ordering is important, since currently we do not have a weight
709 * scheme. Adding weight is super important and should be done in the
710 * next week or so, before this can be called complete.
712 * @param string $contactType
713 * @param bool $status
716 * array of importable Fields
718 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
719 if (!self
::$_importableFields) {
720 if (!self
::$_importableFields) {
721 self
::$_importableFields = array();
725 $fields = array('' => array('title' => ts('- do not import -')));
728 $fields = array('' => array('title' => ts('- Contribution Fields -')));
731 $note = CRM_Core_DAO_Note
::import();
732 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
733 unset($tmpFields['option_value']);
734 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
735 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
737 // Using new Dedupe rule.
739 'contact_type' => $contactType,
740 'used' => 'Unsupervised',
742 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
743 $tmpContactField = array();
744 if (is_array($fieldsArray)) {
745 foreach ($fieldsArray as $value) {
746 //skip if there is no dupe rule
747 if ($value == 'none') {
750 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
755 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
756 $tmpContactField[trim($value)] = $contactFields[trim($value)];
758 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
761 $title = $tmpContactField[trim($value)]['title'];
763 $tmpContactField[trim($value)]['title'] = $title;
767 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
768 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
769 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
770 $fields = array_merge($fields, $tmpContactField);
771 $fields = array_merge($fields, $tmpFields);
772 $fields = array_merge($fields, $note);
773 $fields = array_merge($fields, $optionFields);
774 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
775 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
776 self
::$_importableFields = $fields;
778 return self
::$_importableFields;
782 * Get exportable fields with pseudoconstants rendered as an extra field.
784 public static function getExportableFieldsWithPseudoConstants() {
785 $fields = self
::exportableFields();
786 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
791 * Combine all the exportable fields from the lower level objects.
793 * @param bool $checkPermission
796 * array of exportable Fields
798 public static function &exportableFields($checkPermission = TRUE) {
799 if (!self
::$_exportableFields) {
800 if (!self
::$_exportableFields) {
801 self
::$_exportableFields = array();
804 $impFields = CRM_Contribute_DAO_Contribution
::export();
805 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
806 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
807 $typeField = CRM_Financial_DAO_FinancialType
::export();
808 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
810 $contributionPage = array(
811 'contribution_page' => array(
812 'title' => ts('Contribution Page'),
813 'name' => 'contribution_page',
814 'where' => 'civicrm_contribution_page.title',
815 'data_type' => CRM_Utils_Type
::T_STRING
,
819 $contributionNote = array(
820 'contribution_note' => array(
821 'title' => ts('Contribution Note'),
822 'name' => 'contribution_note',
823 'data_type' => CRM_Utils_Type
::T_TEXT
,
827 $extraFields = array(
828 'contribution_batch' => array(
829 'title' => ts('Batch Name'),
834 $campaignTitle = array(
835 'contribution_campaign_title' => array(
836 'title' => ts('Campaign Title'),
837 'name' => 'campaign_title',
838 'where' => 'civicrm_campaign.title',
839 'data_type' => CRM_Utils_Type
::T_STRING
,
842 $softCreditFields = array(
843 'contribution_soft_credit_name' => array(
844 'name' => 'contribution_soft_credit_name',
845 'title' => 'Soft Credit For',
846 'where' => 'civicrm_contact_d.display_name',
847 'data_type' => CRM_Utils_Type
::T_STRING
,
849 'contribution_soft_credit_amount' => array(
850 'name' => 'contribution_soft_credit_amount',
851 'title' => 'Soft Credit Amount',
852 'where' => 'civicrm_contribution_soft.amount',
853 'data_type' => CRM_Utils_Type
::T_MONEY
,
855 'contribution_soft_credit_type' => array(
856 'name' => 'contribution_soft_credit_type',
857 'title' => 'Soft Credit Type',
858 'where' => 'contribution_softcredit_type.label',
859 'data_type' => CRM_Utils_Type
::T_STRING
,
861 'contribution_soft_credit_contribution_id' => array(
862 'name' => 'contribution_soft_credit_contribution_id',
863 'title' => 'Soft Credit For Contribution ID',
864 'where' => 'civicrm_contribution_soft.contribution_id',
865 'data_type' => CRM_Utils_Type
::T_INT
,
867 'contribution_soft_credit_contact_id' => array(
868 'name' => 'contribution_soft_credit_contact_id',
869 'title' => 'Soft Credit For Contact ID',
870 'where' => 'civicrm_contact_d.id',
871 'data_type' => CRM_Utils_Type
::T_INT
,
875 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
877 'contribution_product_id' => array(
878 'title' => ts('Premium'),
879 'name' => 'contribution_product_id',
880 'where' => 'civicrm_product.id',
881 'data_type' => CRM_Utils_Type
::T_INT
,
885 $fields = array_merge($impFields, $typeField, $contributionPage, $expFieldProduct,
886 $expFieldsContrib, $contributionNote, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
887 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
890 self
::$_exportableFields = $fields;
893 return self
::$_exportableFields;
897 * @param null $status
898 * @param null $startDate
899 * @param null $endDate
903 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
907 $where[] = 'contribution_status_id = 1';
911 $where[] = 'contribution_status_id = 3';
916 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
919 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
921 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
922 if ($financialTypes) {
923 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
924 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
927 $where[] = "c.financial_type_id IN (0)";
930 $whereCond = implode(' AND ', $where);
933 SELECT sum( total_amount ) as total_amount,
934 count( c.id ) as total_count,
936 FROM civicrm_contribution c
937 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
938 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
940 AND ( is_test = 0 OR is_test IS NULL )
941 AND contact.is_deleted = 0
945 $dao = CRM_Core_DAO
::executeQuery($query);
948 while ($dao->fetch()) {
949 $count +
= $dao->total_count
;
950 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
954 'amount' => implode(', ', $amount),
962 * Delete the indirect records associated with this contribution first.
967 * $results no of deleted Contribution on success, false otherwise
969 public static function deleteContribution($id) {
970 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
972 $transaction = new CRM_Core_Transaction();
975 //delete activity record
977 'source_record_id' => $id,
978 // activity type id for contribution
979 'activity_type_id' => 6,
982 CRM_Activity_BAO_Activity
::deleteActivity($params);
984 //delete billing address if exists for this contribution.
985 self
::deleteAddress($id);
987 //update pledge and pledge payment, CRM-3961
988 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
990 // remove entry from civicrm_price_set_entity, CRM-5095
991 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
992 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
994 // cleanup line items.
995 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
997 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
998 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
1000 if ($participantId) {
1001 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
1004 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
1008 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
1009 $noteId = key($note);
1011 CRM_Core_BAO_Note
::del($noteId, FALSE);
1014 $dao = new CRM_Contribute_DAO_Contribution();
1017 $results = $dao->delete();
1019 $transaction->commit();
1021 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1023 // delete the recently created Contribution
1024 $contributionRecent = array(
1026 'type' => 'Contribution',
1028 CRM_Utils_Recent
::del($contributionRecent);
1034 * React to a financial transaction (payment) failure.
1036 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1037 * payments is important for forensic and outreach reasons.
1039 * @param int $contributionID
1040 * @param int $contactID
1041 * @param string $message
1043 * @throws \CiviCRM_API3_Exception
1045 public static function failPayment($contributionID, $contactID, $message) {
1046 civicrm_api3('activity', 'create', array(
1047 'activity_type_id' => 'Failed Payment',
1048 'details' => $message,
1049 'subject' => ts('Payment failed at payment processor'),
1050 'source_record_id' => $contributionID,
1051 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1055 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
1056 civicrm_api3('contribution', 'create', array(
1057 'id' => $contributionID,
1058 'contribution_status_id' => 'Failed',
1063 * Check if there is a contribution with the same trxn_id or invoice_id.
1065 * @param array $input
1066 * An assoc array of name/value pairs.
1067 * @param array $duplicates
1068 * (reference) store ids of duplicate contribs.
1072 * true if duplicate, false otherwise
1074 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1076 $id = CRM_Utils_Array
::value('id', $input);
1078 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1079 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1085 $clause[] = "trxn_id = %1";
1086 $input[1] = array($trxn_id, 'String');
1090 $clause[] = "invoice_id = %2";
1091 $input[2] = array($invoice_id, 'String');
1094 if (empty($clause)) {
1098 $clause = implode(' OR ', $clause);
1100 $clause = "( $clause ) AND id != %3";
1101 $input[3] = array($id, 'Integer');
1104 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1105 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1107 while ($dao->fetch()) {
1108 $duplicates[] = $dao->id
;
1115 * Takes an associative array and creates a contribution_product object.
1117 * the function extract all the params it needs to initialize the create a
1118 * contribution_product object. the params array could contain additional unused name/value
1121 * @param array $params
1122 * (reference) an assoc array of name/value pairs.
1124 * @return CRM_Contribute_DAO_ContributionProduct
1126 public static function addPremium(&$params) {
1127 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1128 $contributionProduct->copyValues($params);
1129 return $contributionProduct->save();
1133 * Get list of contribution fields for profile.
1134 * For now we only allow custom contribution fields to be in
1137 * @param bool $addExtraFields
1138 * True if special fields needs to be added.
1141 * the list of contribution fields
1143 public static function getContributionFields($addExtraFields = TRUE) {
1144 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1145 // @todo remove this - this line was added because payment_instrument_id was not
1146 // set to exportable - but now it is.
1147 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1149 if ($addExtraFields) {
1150 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1153 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1155 foreach ($contributionFields as $key => $var) {
1156 if ($key == 'contribution_contact_id') {
1159 elseif ($key == 'contribution_campaign_id') {
1160 $var['title'] = ts('Campaign');
1162 $fields[$key] = $var;
1165 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1170 * Add extra fields specific to contribution.
1172 public static function getSpecialContributionFields() {
1173 $extraFields = array(
1174 'contribution_soft_credit_name' => array(
1175 'name' => 'contribution_soft_credit_name',
1176 'title' => 'Soft Credit Name',
1177 'headerPattern' => '/^soft_credit_name$/i',
1178 'where' => 'civicrm_contact_d.display_name',
1180 'contribution_soft_credit_email' => array(
1181 'name' => 'contribution_soft_credit_email',
1182 'title' => 'Soft Credit Email',
1183 'headerPattern' => '/^soft_credit_email$/i',
1184 'where' => 'soft_email.email',
1186 'contribution_soft_credit_phone' => array(
1187 'name' => 'contribution_soft_credit_phone',
1188 'title' => 'Soft Credit Phone',
1189 'headerPattern' => '/^soft_credit_phone$/i',
1190 'where' => 'soft_phone.phone',
1192 'contribution_soft_credit_contact_id' => array(
1193 'name' => 'contribution_soft_credit_contact_id',
1194 'title' => 'Soft Credit Contact ID',
1195 'headerPattern' => '/^soft_credit_contact_id$/i',
1196 'where' => 'civicrm_contribution_soft.contact_id',
1198 'contribution_pcp_title' => array(
1199 'name' => 'contribution_pcp_title',
1200 'title' => 'Personal Campaign Page Title',
1201 'headerPattern' => '/^contribution_pcp_title$/i',
1202 'where' => 'contribution_pcp.title',
1206 return $extraFields;
1210 * @param int $pageID
1214 public static function getCurrentandGoalAmount($pageID) {
1216 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1217 FROM civicrm_contribution_page p,
1218 civicrm_contribution c
1219 WHERE p.id = c.contribution_page_id
1221 AND c.cancel_date is null
1225 $config = CRM_Core_Config
::singleton();
1226 $params = array(1 => array($pageID, 'Integer'));
1227 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1229 if ($dao->fetch()) {
1230 return array($dao->goal
, $dao->total
);
1233 return array(NULL, NULL);
1238 * Get list of contributions which credit the passed in contact ID.
1240 * The returned array provides details about the original contribution & donor.
1242 * @todo - this is a confusing function called from one place. It has a test. It would be
1243 * nice to deprecate it.
1245 * @param int $honorId
1246 * In Honor of Contact ID.
1249 * list of contribution fields
1251 public static function getHonorContacts($honorId) {
1253 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1254 $honorDAO->contact_id
= $honorId;
1257 $type = CRM_Contribute_PseudoConstant
::financialType();
1259 while ($honorDAO->fetch()) {
1260 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1261 $contributionDAO->id
= $honorDAO->contribution_id
;
1263 if ($contributionDAO->find(TRUE)) {
1264 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1265 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1266 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1267 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1268 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1269 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1270 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1271 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1272 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1280 * Get the sort name of a contact for a particular contribution.
1283 * Id of the contribution.
1285 * @return null|string
1286 * sort name of the contact if found
1288 public static function sortName($id) {
1289 $id = CRM_Utils_Type
::escape($id, 'Integer');
1292 SELECT civicrm_contact.sort_name
1293 FROM civicrm_contribution, civicrm_contact
1294 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1295 AND civicrm_contribution.id = {$id}
1297 return CRM_Core_DAO
::singleValueQuery($query);
1301 * @param int $contactID
1305 public static function annual($contactID) {
1306 if (is_array($contactID)) {
1307 $contactIDs = implode(',', $contactID);
1310 $contactIDs = $contactID;
1313 $config = CRM_Core_Config
::singleton();
1314 $startDate = $endDate = NULL;
1316 $currentMonth = date('m');
1317 $currentDay = date('d');
1318 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1319 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1320 (int ) $config->fiscalYearStart
['d'] > $currentDay
1323 $year = date('Y') - 1;
1328 $nextYear = $year +
1;
1330 if ($config->fiscalYearStart
) {
1331 $newFiscalYearStart = $config->fiscalYearStart
;
1332 if ($newFiscalYearStart['M'] < 10) {
1333 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1335 if ($newFiscalYearStart['d'] < 10) {
1336 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1338 $config->fiscalYearStart
= $newFiscalYearStart;
1339 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1344 $startDate = "$year$monthDay";
1345 $endDate = "$nextYear$monthDay";
1346 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1347 $additionalWhere = " AND b.financial_type_id IN (0)";
1348 $liWhere = " AND i.financial_type_id IN (0)";
1349 if (!empty($financialTypes)) {
1350 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1351 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1354 SELECT count(*) as count,
1355 sum(total_amount) as amount,
1356 avg(total_amount) as average,
1358 FROM civicrm_contribution b
1359 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1360 WHERE b.contact_id IN ( $contactIDs )
1361 AND b.contribution_status_id = 1
1363 AND b.receive_date >= $startDate
1364 AND b.receive_date < $endDate
1368 $dao = CRM_Core_DAO
::executeQuery($query);
1370 $amount = $average = array();
1371 while ($dao->fetch()) {
1372 if ($dao->count
> 0 && $dao->amount
> 0) {
1373 $count +
= $dao->count
;
1374 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1375 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1381 implode(', ', $amount),
1382 implode(', ', $average),
1385 return array(0, 0, 0);
1389 * Check if there is a contribution with the params passed in.
1391 * Used for trxn_id,invoice_id and contribution_id
1393 * @param array $params
1394 * An assoc array of name/value pairs.
1397 * contribution id if success else NULL
1399 public static function checkDuplicateIds($params) {
1400 $dao = new CRM_Contribute_DAO_Contribution();
1404 foreach ($params as $k => $v) {
1406 $clause[] = "$k = '$v'";
1409 $clause = implode(' AND ', $clause);
1410 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1411 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1413 while ($dao->fetch()) {
1421 * Get the contribution details for component export.
1423 * @param int $exportMode
1425 * @param string $componentIds
1431 public static function getContributionDetails($exportMode, $componentIds) {
1432 $paymentDetails = array();
1433 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1435 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1436 $componentSelect = " civicrm_participant_payment.participant_id id";
1437 $additionalClause = "
1438 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1439 AND civicrm_participant_payment.participant_id {$componentClause} )
1442 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1443 $componentSelect = " civicrm_membership_payment.membership_id id";
1444 $additionalClause = "
1445 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1446 AND civicrm_membership_payment.membership_id {$componentClause} )
1449 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1450 $componentSelect = " civicrm_pledge_payment.id id";
1451 $additionalClause = "
1452 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1453 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1457 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1458 trxn_id, {$componentSelect}
1459 FROM civicrm_contribution
1460 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1461 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1462 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1463 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1464 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1465 AND option_group_contribution_status.id = contribution_status.option_group_id )
1469 $dao = CRM_Core_DAO
::executeQuery($query);
1471 while ($dao->fetch()) {
1472 $paymentDetails[$dao->id
] = array(
1473 'total_amount' => $dao->total_amount
,
1474 'contribution_status' => $dao->status
,
1475 'receive_date' => $dao->receive_date
,
1476 'pay_instru' => $dao->payment_instrument
,
1477 'trxn_id' => $dao->trxn_id
,
1481 return $paymentDetails;
1485 * Create address associated with contribution record.
1487 * As long as there is one or more billing field in the parameters we will create the address.
1489 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1492 * @param array $params
1493 * @param int $billingLocationTypeID
1498 public static function createAddress($params, $billingLocationTypeID) {
1499 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1500 if ($hasBillingField) {
1501 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1502 return $address->id
;
1509 * Delete billing address record related contribution.
1511 * @param int $contributionId
1512 * @param int $contactId
1514 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1516 $contactJoin = NULL;
1518 if ($contributionId) {
1519 $clauses[] = "cc.id = {$contributionId}";
1523 $clauses[] = "cco.id = {$contactId}";
1524 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1527 if (empty($clauses)) {
1528 CRM_Core_Error
::fatal();
1531 $condition = implode(' OR ', $clauses);
1535 FROM civicrm_address ca
1536 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1540 $dao = CRM_Core_DAO
::executeQuery($query);
1542 while ($dao->fetch()) {
1543 $params = array('id' => $dao->id
);
1544 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1549 * This function check online pending contribution associated w/
1550 * Online Event Registration or Online Membership signup.
1552 * @param int $componentId
1553 * Participant/membership id.
1554 * @param string $componentName
1558 * pending contribution id.
1560 public static function checkOnlinePendingContribution($componentId, $componentName) {
1561 $contributionId = NULL;
1562 if (!$componentId ||
1563 !in_array($componentName, array('Event', 'Membership'))
1565 return $contributionId;
1568 if ($componentName == 'Event') {
1569 $idName = 'participant_id';
1570 $componentTable = 'civicrm_participant';
1571 $paymentTable = 'civicrm_participant_payment';
1572 $source = ts('Online Event Registration');
1575 if ($componentName == 'Membership') {
1576 $idName = 'membership_id';
1577 $componentTable = 'civicrm_membership';
1578 $paymentTable = 'civicrm_membership_payment';
1579 $source = ts('Online Contribution');
1582 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1585 SELECT component.id as {$idName},
1586 componentPayment.contribution_id as contribution_id,
1587 contribution.source source,
1588 contribution.contribution_status_id as contribution_status_id,
1589 contribution.is_pay_later as is_pay_later
1590 FROM $componentTable component
1591 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1592 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1593 WHERE component.id = {$componentId}";
1595 $dao = CRM_Core_DAO
::executeQuery($query);
1597 while ($dao->fetch()) {
1598 if ($dao->contribution_id
&&
1599 $dao->is_pay_later
&&
1600 $dao->contribution_status_id
== $pendingStatusId &&
1601 strpos($dao->source
, $source) !== FALSE
1603 $contributionId = $dao->contribution_id
;
1608 return $contributionId;
1612 * Update contribution as well as related objects.
1614 * This function by-passes hooks - to address this - don't use this function.
1618 * Use api contribute.completetransaction
1619 * For failures use failPayment (preferably exposing by api in the process).
1621 * @param array $params
1622 * @param bool $processContributionObject
1625 * @throws \Exception
1627 public static function transitionComponents($params, $processContributionObject = FALSE) {
1628 // get minimum required values.
1629 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1630 $componentId = CRM_Utils_Array
::value('component_id', $params);
1631 $componentName = CRM_Utils_Array
::value('componentName', $params);
1632 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1633 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1635 // if we already processed contribution object pass previous status id.
1636 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1638 $updateResult = array();
1640 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1642 // we process only ( Completed, Cancelled, or Failed ) contributions.
1643 if (!$contributionId ||
1644 !in_array($contributionStatusId, array(
1645 array_search('Completed', $contributionStatuses),
1646 array_search('Cancelled', $contributionStatuses),
1647 array_search('Failed', $contributionStatuses),
1650 return $updateResult;
1653 if (!$componentName ||
!$componentId) {
1654 // get the related component details.
1655 $componentDetails = self
::getComponentDetails($contributionId);
1658 $componentDetails['contact_id'] = $contactId;
1659 $componentDetails['component'] = $componentName;
1661 if ($componentName == 'event') {
1662 $componentDetails['participant'] = $componentId;
1665 $componentDetails['membership'] = $componentId;
1669 if (!empty($componentDetails['contact_id'])) {
1670 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1676 // do check for required ids.
1677 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1678 return $updateResult;
1681 //now we are ready w/ required ids, start processing.
1683 $baseIPN = new CRM_Core_Payment_BaseIPN();
1685 $input = $ids = $objects = array();
1687 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1688 $ids['contribution'] = $contributionId;
1689 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1690 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1691 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1692 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1693 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1694 $ids['contributionRecur'] = NULL;
1695 $ids['contributionPage'] = NULL;
1697 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1698 CRM_Core_Error
::fatal();
1701 $memberships = &$objects['membership'];
1702 $participant = &$objects['participant'];
1703 $pledgePayment = &$objects['pledge_payment'];
1704 $contribution = &$objects['contribution'];
1706 if ($pledgePayment) {
1707 $pledgePaymentIDs = array();
1708 foreach ($pledgePayment as $key => $object) {
1709 $pledgePaymentIDs[] = $object->id
;
1711 $pledgeID = $pledgePayment[0]->pledge_id
;
1714 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1717 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1718 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1723 // we might want to process contribution object.
1724 $processContribution = FALSE;
1725 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1726 if (is_array($memberships)) {
1727 foreach ($memberships as $membership) {
1729 $newStatus = array_search('Cancelled', $membershipStatuses);
1732 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1733 $activityParam = array(
1734 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1735 'source_contact_id' => CRM_Core_Session
::singleton()->get('userID'),
1736 'target_contact_id' => $membership->contact_id
,
1737 'source_record_id' => $membership->id
,
1738 'activity_type_id' => 'Change Membership Status',
1739 'status_id' => 'Completed',
1740 'priority_id' => 'Normal',
1741 'activity_date_time' => 'now',
1744 $membership->status_id
= $newStatus;
1745 $membership->save();
1746 civicrm_api3('activity', 'create', $activityParam);
1748 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1749 if ($processContributionObject) {
1750 $processContribution = TRUE;
1757 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1758 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1760 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1761 if ($processContributionObject) {
1762 $processContribution = TRUE;
1766 if ($pledgePayment) {
1767 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1769 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1770 if ($processContributionObject) {
1771 $processContribution = TRUE;
1775 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1776 if (is_array($memberships)) {
1777 foreach ($memberships as $membership) {
1779 $membership->status_id
= array_search('Expired', $membershipStatuses);
1780 $membership->save();
1782 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1783 if ($processContributionObject) {
1784 $processContribution = TRUE;
1790 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1791 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1793 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1794 if ($processContributionObject) {
1795 $processContribution = TRUE;
1799 if ($pledgePayment) {
1800 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1802 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1803 if ($processContributionObject) {
1804 $processContribution = TRUE;
1808 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1810 // only pending contribution related object processed.
1811 if ($previousContriStatusId &&
1812 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1814 // this is case when we already processed contribution object.
1815 return $updateResult;
1817 elseif (!$previousContriStatusId &&
1818 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1820 // this is case when we are going to process contribution object later.
1821 return $updateResult;
1824 if (is_array($memberships)) {
1825 foreach ($memberships as $membership) {
1830 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1831 $membership->membership_type_id
,
1832 $membership->is_test
, $membership->id
1835 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1836 // this picks up membership type changes during renewals
1838 SELECT membership_type_id
1839 FROM civicrm_membership_log
1840 WHERE membership_id=$membership->id
1843 $dao = new CRM_Core_DAO();
1845 if ($dao->fetch()) {
1846 if (!empty($dao->membership_type_id
)) {
1847 $membership->membership_type_id
= $dao->membership_type_id
;
1848 $membership->save();
1851 // else fall back to using current membership type
1854 // Figure out number of terms
1856 $lineitems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
1857 foreach ($lineitems as $lineitem) {
1858 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1859 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1861 // in case membership_num_terms comes through as null or zero
1862 $numterms = $numterms >= 1 ?
$numterms : 1;
1867 // CRM-15735-to update the membership status as per the contribution receive date
1869 if (!empty($params['receive_date'])) {
1870 $joinDate = $params['receive_date'];
1871 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1872 $membership->end_date
,
1873 $membership->join_date
,
1874 $params['receive_date'],
1876 $membership->membership_type_id
,
1879 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1880 $membership->save();
1883 if ($currentMembership) {
1884 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1885 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1886 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1889 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1892 //get the status for membership.
1893 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1895 $dates['join_date'],
1898 $membership->membership_type_id
,
1902 $formattedParams = array(
1903 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1904 array_search('Current', $membershipStatuses)
1906 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1907 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1908 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1911 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1913 $membership->copyValues($formattedParams);
1914 $membership->save();
1916 //updating the membership log
1917 $membershipLog = array();
1918 $membershipLog = $formattedParams;
1919 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1920 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1922 $membershipLog['start_date'] = $logStartDate;
1923 $membershipLog['membership_id'] = $membership->id
;
1924 $membershipLog['modified_id'] = $membership->contact_id
;
1925 $membershipLog['modified_date'] = date('Ymd');
1926 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1928 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1930 //update related Memberships.
1931 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1933 //CRM-19678: No Membership Renewal Activity is created when a Pay Later is set to Completed
1934 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Renewal', $membership->contact_id
);
1936 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1939 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1940 if ($processContributionObject) {
1941 $processContribution = TRUE;
1944 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1950 $updatedStatusId = array_search('Registered', $participantStatuses);
1951 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1953 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1954 if ($processContributionObject) {
1955 $processContribution = TRUE;
1959 if ($pledgePayment) {
1960 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1962 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1963 if ($processContributionObject) {
1964 $processContribution = TRUE;
1969 // process contribution object.
1970 if ($processContribution) {
1971 $contributionParams = array();
1978 'payment_instrument_id',
1981 'financial_type_id',
1982 'contribution_status_id',
1983 'non_deductible_amount',
1987 foreach ($fields as $field) {
1988 if (empty($params[$field])) {
1991 $contributionParams[$field] = $params[$field];
1994 $ids = array('contribution' => $contributionId);
1995 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1998 return $updateResult;
2002 * Returns all contribution related object ids.
2004 * @param $contributionId
2008 public static function getComponentDetails($contributionId) {
2009 $componentDetails = $pledgePayment = array();
2010 if (!$contributionId) {
2011 return $componentDetails;
2015 SELECT c.id as contribution_id,
2016 c.contact_id as contact_id,
2017 c.contribution_recur_id,
2018 mp.membership_id as membership_id,
2019 m.membership_type_id as membership_type_id,
2020 pp.participant_id as participant_id,
2021 p.event_id as event_id,
2022 pgp.id as pledge_payment_id
2023 FROM civicrm_contribution c
2024 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2025 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2026 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2027 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2028 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2029 WHERE c.id = $contributionId";
2031 $dao = CRM_Core_DAO
::executeQuery($query);
2032 $componentDetails = array();
2034 while ($dao->fetch()) {
2035 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
2036 $componentDetails['contact_id'] = $dao->contact_id
;
2037 if ($dao->event_id
) {
2038 $componentDetails['event'] = $dao->event_id
;
2040 if ($dao->participant_id
) {
2041 $componentDetails['participant'] = $dao->participant_id
;
2043 if ($dao->membership_id
) {
2044 if (!isset($componentDetails['membership'])) {
2045 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2047 $componentDetails['membership'][] = $dao->membership_id
;
2048 $componentDetails['membership_type'][] = $dao->membership_type_id
;
2050 if ($dao->pledge_payment_id
) {
2051 $pledgePayment[] = $dao->pledge_payment_id
;
2053 if ($dao->contribution_recur_id
) {
2054 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2058 if ($pledgePayment) {
2059 $componentDetails['pledge_payment'] = $pledgePayment;
2062 return $componentDetails;
2066 * @param int $contactId
2067 * @param bool $includeSoftCredit
2069 * @return null|string
2071 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2075 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2076 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2077 $liWhere = " AND i.financial_type_id IN (0)";
2078 if (!empty($financialTypes)) {
2079 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2080 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2082 $contactContributionsSQL = "
2083 SELECT contribution.id AS id
2084 FROM civicrm_contribution contribution
2085 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2086 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2090 $contactSoftCreditContributionsSQL = "
2091 SELECT contribution.id
2092 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2093 ON ( contribution.id = softContribution.contribution_id )
2094 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2095 $query = "SELECT count( x.id ) count FROM ( ";
2096 $query .= $contactContributionsSQL;
2098 if ($includeSoftCredit) {
2099 $query .= " UNION ";
2100 $query .= $contactSoftCreditContributionsSQL;
2105 return CRM_Core_DAO
::singleValueQuery($query);
2109 * Repeat a transaction as part of a recurring series.
2111 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2112 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2113 * subsequent call to the contribution.completetransaction api.
2115 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2117 * @param CRM_Contribute_BAO_Contribution $contribution
2118 * @param array $input
2119 * @param array $contributionParams
2120 * @param int $paymentProcessorID
2123 * @throws CiviCRM_API3_Exception
2125 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
2126 if (!empty($contribution->id
)) {
2129 if (empty($contribution->id
)) {
2130 // Unclear why this would only be set for repeats.
2131 if (!empty($input['amount'])) {
2132 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2135 if (!empty($contributionParams['contribution_recur_id'])) {
2136 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2137 'id' => $contributionParams['contribution_recur_id'],
2139 if (!empty($recurringContribution['campaign_id'])) {
2140 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2141 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2143 if (!empty($recurringContribution['financial_type_id'])) {
2144 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2145 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2148 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution(
2149 $contributionParams['contribution_recur_id'],
2150 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2152 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2154 $contributionParams['status_id'] = 'Pending';
2155 if (isset($contributionParams['financial_type_id'])) {
2156 // Give precedence to passed in type.
2157 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2160 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2162 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2163 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2165 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2166 //do not create CC or BCC emails or profile notifications.
2167 //The if is just to be safe. Not sure if we can ever arrive with this unset
2168 // but per CRM-19478 it seems it can be 'null'
2169 if (isset($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
2170 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id
;
2173 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2174 $contribution->id
= $createContribution['id'];
2175 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2181 * Get individual id for onbehalf contribution.
2183 * @param int $contributionId
2185 * @param int $contributorId
2189 * containing organization id and individual id
2191 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2195 if (!$contributionId) {
2199 // fetch contributor id if null
2200 if (!$contributorId) {
2201 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2202 $contributionId, 'contact_id'
2206 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2207 $activityTypeId = array_search('Contribution', $activityTypeIds);
2209 if ($activityTypeId && $contributorId) {
2211 SELECT civicrm_activity_contact.contact_id
2212 FROM civicrm_activity_contact
2213 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2214 WHERE civicrm_activity.activity_type_id = %1
2215 AND civicrm_activity.source_record_id = %2
2216 AND civicrm_activity_contact.record_type_id = %3
2219 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2220 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2223 1 => array($activityTypeId, 'Integer'),
2224 2 => array($contributionId, 'Integer'),
2225 3 => array($sourceID, 'Integer'),
2228 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2230 // for on behalf contribution source is individual and contributor is organization
2231 if ($sourceContactId && $sourceContactId != $contributorId) {
2232 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2233 // get rel type id for employee of relation
2234 foreach ($relationshipTypeIds as $id => $typeVals) {
2235 if ($typeVals['name_a_b'] == 'Employee of') {
2236 $relationshipTypeId = $id;
2241 $rel = new CRM_Contact_DAO_Relationship();
2242 $rel->relationship_type_id
= $relationshipTypeId;
2243 $rel->contact_id_a
= $sourceContactId;
2244 $rel->contact_id_b
= $contributorId;
2245 if ($rel->find(TRUE)) {
2246 $ids['individual_id'] = $rel->contact_id_a
;
2247 $ids['organization_id'] = $rel->contact_id_b
;
2258 public static function getContributionDates() {
2259 $config = CRM_Core_Config
::singleton();
2260 $currentMonth = date('m');
2261 $currentDay = date('d');
2262 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2263 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2264 (int ) $config->fiscalYearStart
['d'] > $currentDay
2267 $year = date('Y') - 1;
2272 $year = array('Y' => $year);
2273 $yearDate = $config->fiscalYearStart
;
2274 $yearDate = array_merge($year, $yearDate);
2275 $yearDate = CRM_Utils_Date
::format($yearDate);
2277 $monthDate = date('Ym') . '01';
2283 'yearDate' => $yearDate,
2284 'monthDate' => $monthDate,
2289 * Load objects relations to contribution object.
2290 * Objects are stored in the $_relatedObjects property
2291 * In the first instance we are just moving functionality from BASEIpn -
2292 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2294 * Note that the unit test for the BaseIPN class tests this function
2296 * @param array $input
2297 * Input as delivered from Payment Processor.
2299 * Ids as Loaded by Payment Processor.
2300 * @param bool $loadAll
2301 * Load all related objects - even where id not passed in? (allows API to call this).
2306 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2308 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2309 if (empty($ids['contact']) && isset($this->contact_id
)) {
2310 $ids['contact'] = $this->contact_id
;
2313 if (empty($this->_component
)) {
2314 if (!empty($ids['event'])) {
2315 $this->_component
= 'event';
2318 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2322 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2323 // refactoring than anything else, and has unit test coverage.
2324 if (empty($this->financial_type_id
)) {
2328 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2333 if (!$paymentProcessorID && $this->contribution_page_id
) {
2334 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2335 $this->contribution_page_id
,
2338 if ($paymentProcessorID) {
2339 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2343 $ids['contributionType'] = $this->financial_type_id
;
2344 $ids['financialType'] = $this->financial_type_id
;
2345 if ($this->contribution_page_id
) {
2346 $ids['contributionPage'] = $this->contribution_page_id
;
2349 $this->loadRelatedEntitiesByID($ids);
2351 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2352 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2355 if (!empty($ids['pledge_payment'])) {
2356 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2357 if (empty($paymentID)) {
2360 $payment = new CRM_Pledge_BAO_PledgePayment();
2361 $payment->id
= $paymentID;
2362 if (!$payment->find(TRUE)) {
2363 throw new Exception("Could not find pledge payment record: " . $paymentID);
2365 $this->_relatedObjects
['pledge_payment'][] = $payment;
2369 $this->loadRelatedMembershipObjects($ids);
2371 if ($this->_component
!= 'contribute') {
2372 // we are in event mode
2373 // make sure event exists and is valid
2374 $event = new CRM_Event_BAO_Event();
2375 $event->id
= $ids['event'];
2376 if ($ids['event'] &&
2379 throw new Exception("Could not find event: " . $ids['event']);
2382 $this->_relatedObjects
['event'] = &$event;
2384 $participant = new CRM_Event_BAO_Participant();
2385 $participant->id
= $ids['participant'];
2386 if ($ids['participant'] &&
2387 !$participant->find(TRUE)
2389 throw new Exception("Could not find participant: " . $ids['participant']);
2391 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2393 $this->_relatedObjects
['participant'] = &$participant;
2395 // get the payment processor id from event - this is inaccurate see CRM-16923
2396 // in future we should look at throwing an exception here rather than an dubious guess.
2397 if (!$paymentProcessorID) {
2398 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2399 if ($paymentProcessorID) {
2400 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2405 if ($paymentProcessorID) {
2406 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2407 $this->is_test ?
'test' : 'live'
2409 $ids['paymentProcessor'] = $paymentProcessorID;
2410 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2416 * Create array of message information - ie. return html version, txt version, to field
2418 * @param array $input
2419 * Incoming information.
2420 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2421 * just check presence of recur object but maintaining legacy approach
2424 * IDs of related objects.
2425 * @param array $values
2426 * Any values that may have already been compiled by calling process.
2427 * This is augmented by values 'gathered' by gatherMessageValues
2428 * @param bool $returnMessageText
2429 * Distinguishes between whether to send message or return.
2430 * message text. We are working towards this function ALWAYS returning message text & calling
2431 * function doing emails / pdfs with it
2437 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2438 $this->loadRelatedObjects($input, $ids);
2440 if (empty($this->_component
)) {
2441 $this->_component
= CRM_Utils_Array
::value('component', $input);
2444 //not really sure what params might be passed in but lets merge em into values
2445 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2446 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
2447 if (!empty($input['receipt_date'])) {
2448 $values['receipt_date'] = $input['receipt_date'];
2451 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2452 //what does recur 'mean here - to do with payment processor return functionality but
2453 // what is the importance
2454 if (!empty($this->contribution_recur_id
) && !empty($this->_relatedObjects
['paymentProcessor'])) {
2455 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2457 $entityID = $entity = NULL;
2458 if (isset($ids['contribution'])) {
2459 $entity = 'contribution';
2460 $entityID = $ids['contribution'];
2462 if (!empty($ids['membership'])) {
2463 //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
2464 // 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
2465 // line having loaded an array
2466 $ids['membership'] = (array) $ids['membership'];
2467 $entity = 'membership';
2468 $entityID = $ids['membership'][0];
2471 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2472 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2473 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2475 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2476 //direct mode showing billing block, so use directIPN for temporary
2477 $template->assign('contributeMode', 'directIPN');
2480 // todo remove strtolower - check consistency
2481 if (strtolower($this->_component
) == 'event') {
2482 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2483 $values['event'] = array();
2485 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2487 //get location details
2488 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2489 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2491 $ufJoinParams = array(
2492 'entity_table' => 'civicrm_event',
2493 'entity_id' => $ids['event'],
2494 'module' => 'CiviEvent',
2497 list($custom_pre_id,
2499 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2501 $values['custom_pre_id'] = $custom_pre_id;
2502 $values['custom_post_id'] = $custom_post_ids;
2503 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2504 //and cases involving status updation through ipn
2505 // whatever that means!
2506 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2507 // perhaps we should throw an e-notice if amount is set & force total_amount?
2508 if (!empty($input['amount'])) {
2509 $values['totalAmount'] = $input['amount'];
2511 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
2512 if ($values['event']['is_email_confirm']) {
2513 $values['is_email_receipt'] = 1;
2516 if (!empty($ids['contribution'])) {
2517 $values['contributionId'] = $ids['contribution'];
2520 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2521 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2525 $values['contribution_id'] = $this->id
;
2526 if (!empty($ids['related_contact'])) {
2527 $values['related_contact'] = $ids['related_contact'];
2528 if (isset($ids['onbehalf_dupe_alert'])) {
2529 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2531 $entityBlock = array(
2532 'contact_id' => $ids['contact'],
2533 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2534 'Home', 'id', 'name'
2537 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2538 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2541 if ($this->is_test
) {
2544 if (!empty($this->_relatedObjects
['membership'])) {
2545 foreach ($this->_relatedObjects
['membership'] as $membership) {
2546 if ($membership->id
) {
2547 $values['isMembership'] = TRUE;
2548 $values['membership_assign'] = TRUE;
2550 // need to set the membership values here
2551 $template->assign('membership_name',
2552 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2554 $template->assign('mem_start_date', $membership->start_date
);
2555 $template->assign('mem_join_date', $membership->join_date
);
2556 $template->assign('mem_end_date', $membership->end_date
);
2557 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2558 $template->assign('mem_status', $membership_status);
2559 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2560 $values['is_pay_later'] = 1;
2562 // Pass amount to floatval as string '0.00' is considered a
2563 // valid amount and includes Fee section in the mail.
2564 if (isset($values['amount'])) {
2565 $values['amount'] = floatval($values['amount']);
2568 if (!empty($this->contribution_recur_id
) && $paymentObject) {
2569 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2570 $template->assign('cancelSubscriptionUrl', $url);
2571 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2572 $template->assign('updateSubscriptionBillingUrl', $url);
2573 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2574 $template->assign('updateSubscriptionUrl', $url);
2577 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2580 // otherwise if its about sending emails, continue sending without return, as we
2581 // don't want to exit the loop.
2586 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2592 * Gather values for contribution mail - this function has been created
2593 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2594 * Values related to the contribution in question are gathered
2596 * @param array $input
2597 * Input into function (probably from payment processor).
2598 * @param array $values
2600 * The set of ids related to the input.
2604 public function _gatherMessageValues($input, &$values, $ids = array()) {
2605 // set display address of contributor
2606 if ($this->address_id
) {
2607 $addressParams = array('id' => $this->address_id
);
2608 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2609 $addressDetails = array_values($addressDetails);
2611 // Else we assign the billing address of the contribution contact.
2613 $addressParams = array('contact_id' => $this->contact_id
, 'is_billing' => 1);
2614 $addressDetails = (array) CRM_Core_BAO_Address
::getValues($addressParams);
2615 $addressDetails = array_values($addressDetails);
2618 if (!empty($addressDetails[0]['display'])) {
2619 $values['address'] = $addressDetails[0]['display'];
2622 if ($this->_component
== 'contribute') {
2623 //get soft contributions
2624 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2625 if (!empty($softContributions)) {
2626 $values['softContributions'] = $softContributions['soft_credit'];
2628 if (isset($this->contribution_page_id
)) {
2629 // This is a call we want to use less, in favour of loading related objects.
2630 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
2631 if ($this->contribution_page_id
) {
2632 // This is precautionary as there are some legacy flows, but it should really be
2634 if (!isset($this->_relatedObjects
['contributionPage'])) {
2635 $this->loadRelatedEntitiesByID(array('contributionPage' => $this->contribution_page_id
));
2637 // CRM-8254 - override default currency if applicable
2638 $config = CRM_Core_Config
::singleton();
2639 $config->defaultCurrency
= CRM_Utils_Array
::value(
2642 $config->defaultCurrency
2646 // no contribution page -probably back office
2648 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2649 $values['title'] = 'Contribution';
2651 // set lineItem for contribution
2653 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($this->id
);
2654 if (!empty($lineItems)) {
2655 $firstLineItem = reset($lineItems);
2656 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2657 $values['priceSetID'] = $priceSet['id'];
2658 foreach ($lineItems as &$eachItem) {
2659 if (isset($this->_relatedObjects
['membership'])
2660 && is_array($this->_relatedObjects
['membership'])
2661 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2662 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2663 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2664 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2666 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2667 // However, that does create upgrade pain so would be better to be phased in.
2668 $values['useForMember'] = !$priceSet['is_quick_config'];
2670 $values['lineItem'][0] = $lineItems;
2674 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2678 // if this is onbehalf of contribution then set related contact
2679 if (!empty($relatedContact['individual_id'])) {
2680 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2685 $eventParams = array(
2686 'id' => $this->_relatedObjects
['event']->id
,
2688 $values['event'] = array();
2690 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2691 // add custom fields for event
2692 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2694 $eventCustomGroup = array();
2695 foreach ($eventGroupTree as $key => $group) {
2696 if ($key === 'info') {
2700 foreach ($group['fields'] as $k => $customField) {
2701 $groupLabel = $group['title'];
2702 if (!empty($customField['customValue'])) {
2703 foreach ($customField['customValue'] as $customFieldValues) {
2704 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2709 $values['event']['customGroup'] = $eventCustomGroup;
2711 //get participant details
2712 $participantParams = array(
2713 'id' => $this->_relatedObjects
['participant']->id
,
2716 $values['participant'] = array();
2718 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2719 // add custom fields for event
2720 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2721 $participantCustomGroup = array();
2722 foreach ($participantGroupTree as $key => $group) {
2723 if ($key === 'info') {
2727 foreach ($group['fields'] as $k => $customField) {
2728 $groupLabel = $group['title'];
2729 if (!empty($customField['customValue'])) {
2730 foreach ($customField['customValue'] as $customFieldValues) {
2731 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2736 $values['participant']['customGroup'] = $participantCustomGroup;
2738 //get location details
2739 $locationParams = array(
2740 'entity_id' => $this->_relatedObjects
['event']->id
,
2741 'entity_table' => 'civicrm_event',
2743 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2745 $ufJoinParams = array(
2746 'entity_table' => 'civicrm_event',
2747 'entity_id' => $ids['event'],
2748 'module' => 'CiviEvent',
2751 list($custom_pre_id,
2753 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2755 $values['custom_pre_id'] = $custom_pre_id;
2756 $values['custom_post_id'] = $custom_post_ids;
2758 // set lineItem for event contribution
2760 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2761 if (!empty($participantIds)) {
2762 foreach ($participantIds as $pIDs) {
2763 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2764 if (!CRM_Utils_System
::isNull($lineItem)) {
2765 $values['lineItem'][] = $lineItem;
2772 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2774 $customGroup = array();
2775 foreach ($groupTree as $key => $group) {
2776 if ($key === 'info') {
2780 foreach ($group['fields'] as $k => $customField) {
2781 $groupLabel = $group['title'];
2782 if (!empty($customField['customValue'])) {
2783 foreach ($customField['customValue'] as $customFieldValues) {
2784 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2789 $values['customGroup'] = $customGroup;
2795 * Assign message variables to template but try to break the habit.
2797 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2798 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2799 * multiple recurring payments for processors like IATS that use tokens.
2801 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2802 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2803 * Note we send directly from this function in some cases because it is only partly refactored.
2805 * Don't call this function directly as the signature will change.
2809 * @param bool $returnMessageText
2813 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2814 $template = CRM_Core_Smarty
::singleton();
2815 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2816 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2817 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2819 // For some unit tests contribution cannot contain paymentProcessor information
2820 $billingMode = empty($this->_relatedObjects
['paymentProcessor']) ? CRM_Core_Payment
::BILLING_MODE_NOTIFY
: $this->_relatedObjects
['paymentProcessor']['billing_mode'];
2821 $template->assign('contributeMode', CRM_Utils_Array
::value($billingMode, CRM_Core_SelectValues
::contributeMode()));
2823 //assign honor information to receipt message
2824 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2826 if (isset($softRecord['soft_credit'])) {
2827 //if id of contribution page is present
2828 if (!empty($values['id'])) {
2829 $values['honor'] = array(
2830 'honor_profile_values' => array(),
2831 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2832 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2835 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2836 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2839 //offline contribution
2840 $softCreditTypes = $softCredits = array();
2841 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2842 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2843 $softCredits[$key] = array(
2844 'Name' => $softCredit['contact_name'],
2845 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2848 $template->assign('softCreditTypes', $softCreditTypes);
2849 $template->assign('softCredits', $softCredits);
2853 $dao = new CRM_Contribute_DAO_ContributionProduct();
2854 $dao->contribution_id
= $this->id
;
2855 if ($dao->find(TRUE)) {
2856 $premiumId = $dao->product_id
;
2857 $template->assign('option', $dao->product_option
);
2859 $productDAO = new CRM_Contribute_DAO_Product();
2860 $productDAO->id
= $premiumId;
2861 $productDAO->find(TRUE);
2862 $template->assign('selectPremium', TRUE);
2863 $template->assign('product_name', $productDAO->name
);
2864 $template->assign('price', $productDAO->price
);
2865 $template->assign('sku', $productDAO->sku
);
2867 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2868 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2869 if (!$values['amount'] && isset($this->total_amount
)) {
2870 $values['amount'] = $this->total_amount
;
2873 // add the new contribution values
2874 if (strtolower($this->_component
) == 'contribute') {
2876 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2877 $softDAO->contribution_id
= $this->id
;
2878 if ($softDAO->find(TRUE)) {
2879 $template->assign('pcpBlock', TRUE);
2880 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2881 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2882 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2884 //assign the pcp page title for email subject
2885 $pcpDAO = new CRM_PCP_DAO_PCP();
2886 $pcpDAO->id
= $softDAO->pcp_id
;
2887 if ($pcpDAO->find(TRUE)) {
2888 $template->assign('title', $pcpDAO->title
);
2893 if ($this->financial_type_id
) {
2894 $values['financial_type_id'] = $this->financial_type_id
;
2897 $template->assign('trxn_id', $this->trxn_id
);
2898 $template->assign('receive_date',
2899 CRM_Utils_Date
::processDate($this->receive_date
)
2901 $values['receipt_date'] = (empty($this->receipt_date
) ?
NULL : $this->receipt_date
);
2902 $template->assign('action', $this->is_test ?
1024 : 1);
2903 $template->assign('receipt_text',
2904 CRM_Utils_Array
::value('receipt_text',
2908 $template->assign('is_monetary', 1);
2909 $template->assign('is_recur', !empty($this->contribution_recur_id
));
2910 $template->assign('currency', $this->currency
);
2911 $template->assign('address', CRM_Utils_Address
::format($input));
2912 if (!empty($values['customGroup'])) {
2913 $template->assign('customGroup', $values['customGroup']);
2915 if (!empty($values['softContributions'])) {
2916 $template->assign('softContributions', $values['softContributions']);
2918 if ($this->_component
== 'event') {
2919 $template->assign('title', $values['event']['title']);
2920 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2921 $viewRoles = array();
2922 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2923 $viewRoles[] = $participantRoles[$v];
2925 $values['event']['participant_role'] = implode(', ', $viewRoles);
2926 $template->assign('event', $values['event']);
2927 $template->assign('participant', $values['participant']);
2928 $template->assign('location', $values['location']);
2929 $template->assign('customPre', $values['custom_pre_id']);
2930 $template->assign('customPost', $values['custom_post_id']);
2933 if ($this->_relatedObjects
['participant']->is_test
) {
2937 $values['params'] = array();
2938 //to get email of primary participant.
2939 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2940 $primaryAmount[] = array(
2941 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2942 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2944 //build an array of cId/pId of participants
2945 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2946 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2947 //send receipt to additional participant if exists
2948 if (count($additionalIDs)) {
2949 $template->assign('isPrimary', 0);
2950 $template->assign('customProfile', NULL);
2951 //set additionalParticipant true
2952 $values['params']['additionalParticipant'] = TRUE;
2953 foreach ($additionalIDs as $pId => $cId) {
2955 //to change the status pending to completed
2956 $additional = new CRM_Event_DAO_Participant();
2957 $additional->id
= $pId;
2958 $additional->contact_id
= $cId;
2959 $additional->find(TRUE);
2960 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2961 $additional->status_id
= 1;
2962 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2963 //if additional participant dont have email
2965 if (!$additionalParticipantInfo) {
2966 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2968 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2969 $primaryAmount[] = array(
2970 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2971 'amount' => $additional->fee_amount
,
2973 $additional->save();
2974 $additional->free();
2975 $template->assign('amount', $amount);
2976 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2980 //build an array of custom profile and assigning it to template
2981 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2983 if (count($customProfile)) {
2984 $template->assign('customProfile', $customProfile);
2987 // for primary contact
2988 $values['params']['additionalParticipant'] = FALSE;
2989 $template->assign('isPrimary', 1);
2990 $template->assign('amount', $primaryAmount);
2991 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2992 if ($this->payment_instrument_id
) {
2993 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2994 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2996 // carry paylater, since we did not created billing,
2997 // so need to pull email from primary location, CRM-4395
2998 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
3004 * Check whether payment processor supports
3005 * cancellation of contribution subscription
3007 * @param int $contributionId
3010 * @param bool $isNotCancelled
3014 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3015 $cacheKeyString = "$contributionId";
3016 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
3018 static $supportsCancel = array();
3020 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3021 $supportsCancel[$cacheKeyString] = FALSE;
3022 $isCancelled = FALSE;
3024 if ($isNotCancelled) {
3025 $isCancelled = self
::isSubscriptionCancelled($contributionId);
3028 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
3029 if (!empty($paymentObject)) {
3030 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3033 return $supportsCancel[$cacheKeyString];
3037 * Check whether subscription is already cancelled.
3039 * @param int $contributionId
3043 * contribution status
3045 public static function isSubscriptionCancelled($contributionId) {
3047 SELECT cr.contribution_status_id
3048 FROM civicrm_contribution_recur cr
3049 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3050 WHERE con.id = %1 LIMIT 1";
3051 $params = array(1 => array($contributionId, 'Integer'));
3052 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
3053 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
3054 if ($status == 'Cancelled') {
3061 * Create all financial accounts entry.
3063 * @param array $params
3064 * Contribution object, line item array and params for trxn.
3067 * @param array $financialTrxnValues
3069 * @return null|object
3071 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3072 $skipRecords = $update = $return = $isRelatedId = FALSE;
3074 $additionalParticipantId = array();
3075 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3076 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3078 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3079 $entityId = $params['participant_id'];
3080 $entityTable = 'civicrm_participant';
3081 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3083 elseif (!empty($params['membership_id'])) {
3084 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3085 // are created off one contribution should be handled elsewhere
3086 $entityId = $params['membership_id'];
3087 $entityTable = 'civicrm_membership';
3090 $entityId = $params['contribution']->id
;
3091 $entityTable = 'civicrm_contribution';
3094 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3095 $isRelatedId = TRUE;
3098 $entityID[] = $entityId;
3099 if (!empty($additionalParticipantId)) {
3100 $entityID +
= $additionalParticipantId;
3102 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3103 if (empty($params['prevContribution'])) {
3110 $statusId = $params['contribution']->contribution_status_id
;
3111 // CRM-13964 partial payment
3112 if ($contributionStatus == 'Partially paid'
3113 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3115 $partialAmtPay = CRM_Utils_Rule
::cleanMoney($params['partial_amount_pay']);
3116 $partialAmtTotal = CRM_Utils_Rule
::cleanMoney($params['partial_payment_total']);
3118 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3119 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3120 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3121 $params['total_amount'] = $partialAmtPay;
3123 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3124 if (empty($balanceTrxnInfo['trxn_id'])) {
3125 // create new balance transaction record
3126 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3127 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3129 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3130 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3131 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3132 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3133 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3134 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3135 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3136 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3137 $balanceTrxnParams['status_id'] = $statusId;
3138 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3139 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3140 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3141 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3143 $balanceTrxnParams['is_payment'] = 1;
3145 if (!empty($params['payment_processor'])) {
3146 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3148 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3152 // build line item array if its not set in $params
3153 if (empty($params['line_item']) ||
$additionalParticipantId) {
3154 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3157 if ($contributionStatus != 'Failed' &&
3158 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3160 $skipRecords = TRUE;
3161 $pendingStatus = array(
3165 if (in_array($contributionStatus, $pendingStatus)) {
3166 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3167 $params['financial_type_id'],
3168 'Accounts Receivable Account is'
3171 elseif (!empty($params['payment_processor'])) {
3172 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3173 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3174 'id' => $params['payment_processor'],
3175 'return' => 'payment_instrument_id',
3178 elseif (!empty($params['payment_instrument_id'])) {
3179 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3182 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3183 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3184 $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);
3187 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3188 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3189 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3191 //build financial transaction params
3192 $trxnParams = array(
3193 'contribution_id' => $params['contribution']->id
,
3194 'to_financial_account_id' => $params['to_financial_account_id'],
3195 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3196 'total_amount' => $totalAmount,
3197 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3198 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3199 'currency' => $params['contribution']->currency
,
3200 'trxn_id' => $params['contribution']->trxn_id
,
3201 'status_id' => $statusId,
3202 'payment_instrument_id' => CRM_Utils_Array
::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id
),
3203 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3205 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback' ||
$contributionStatus == 'Cancelled') {
3206 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3207 if (isset($params['refund_trxn_id'])) {
3208 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3209 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3212 //CRM-16259, set is_payment flag for non pending status
3213 if (!in_array($contributionStatus, $pendingStatus)) {
3214 $trxnParams['is_payment'] = 1;
3216 if (!empty($params['payment_processor'])) {
3217 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3220 if (isset($fromFinancialAccountId)) {
3221 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3224 // consider external values passed for recording transaction entry
3225 if (!empty($financialTrxnValues)) {
3226 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3229 $params['trxnParams'] = $trxnParams;
3231 if (!empty($params['prevContribution'])) {
3233 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3234 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3235 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3236 if (!isset($params['trxnParams']['trxn_id'])) {
3237 // Actually I have no idea why we are overwriting any values from the previous contribution.
3238 // (filling makes sense to me). However, only protecting this value as I really really know we
3239 // don't want this one overwritten.
3241 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3243 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3245 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3246 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3247 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3249 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3250 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3253 //if financial type is changed
3254 if (!empty($params['financial_type_id']) &&
3255 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3257 $accountRelationship = 'Income Account is';
3258 if (!empty($params['revenue_recognition_date']) ||
$params['prevContribution']->revenue_recognition_date
) {
3259 $accountRelationship = 'Deferred Revenue Account is';
3261 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' "));
3262 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3263 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3264 if ($oldFinancialAccount != $newFinancialAccount) {
3265 $params['total_amount'] = 0;
3266 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3267 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3268 $params['prevContribution']->financial_type_id
, $relationTypeId);
3271 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3272 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3273 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3276 self
::updateFinancialAccounts($params, 'changeFinancialType');
3277 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3278 $params['financial_account_id'] = $newFinancialAccount;
3279 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3280 self
::updateFinancialAccounts($params);
3281 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3283 $params['deferred_financial_account_id'] = $newFinancialAccount;
3287 //Update contribution status
3288 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3289 if (!isset($params['refund_trxn_id'])) {
3290 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3291 // gets preference over another so I am only 'protecting' a very specific tested flow
3292 // and letting natural justice take care of the rest.
3293 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3295 if (!empty($params['contribution_status_id']) &&
3296 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3298 //Update Financial Records
3299 self
::updateFinancialAccounts($params, 'changedStatus');
3303 // change Payment Instrument for a Completed contribution
3304 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3305 // instrument is null and now new payment instrument is added along with the payment
3306 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3307 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3308 if (array_key_exists('payment_instrument_id', $params)) {
3309 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3310 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3311 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3313 //check if status is changed from Pending to Completed
3314 // do not update payment instrument changes for Pending to Completed
3315 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3316 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3318 // for all other statuses create new financial records
3319 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3320 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3321 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3325 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3326 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3327 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3329 // for any other payment instrument changes create new financial records
3330 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3331 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3332 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3335 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3336 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3338 // another special case when check number is changed, create new financial records
3339 // create financial trxn with negative amount
3340 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3341 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3342 // create financial trxn with positive amount
3343 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3344 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3345 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3350 //if Change contribution amount
3351 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3352 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3353 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3354 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3355 if (isset($totalAmount) &&
3356 $totalAmount != $params['prevContribution']->total_amount
3358 //Update Financial Records
3359 $params['trxnParams']['from_financial_account_id'] = NULL;
3360 self
::updateFinancialAccounts($params, 'changedAmount');
3365 // Looks like we might have a data correction update.
3366 // This would be a case where a transaction id has been entered but it is incorrect &
3367 // the person goes back in & fixes it, as opposed to a new transaction.
3368 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3369 // the data fix scenario.
3371 if (isset($params['refund_trxn_id'])) {
3372 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3373 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3374 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3377 $cardType = CRM_Utils_Array
::value('card_type', $params);
3378 $panTruncation = CRM_Utils_Array
::value('pan_truncation', $params);
3379 CRM_Core_BAO_FinancialTrxn
::updateCreditCardDetails($params['contribution']->id
, $panTruncation, $cardType);
3384 // records finanical trxn and entity financial trxn
3385 // also make it available as return value
3386 self
::recordAlwaysAccountsReceivable($trxnParams, $params);
3387 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3388 $params['entity_id'] = $financialTxn->id
;
3389 if (empty($params['partial_payment_total']) && empty($params['partial_amount_pay'])) {
3390 self
::$_trxnIDs[] = $financialTxn->id
;
3394 // record line items and financial items
3395 if (empty($params['skipLineItem'])) {
3396 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3399 // create batch entry if batch_id is passed and
3400 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3401 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3402 $entityParams = array(
3403 'batch_id' => $params['batch_id'],
3404 'entity_table' => 'civicrm_financial_trxn',
3405 'entity_id' => $financialTxn->id
,
3407 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3410 // when a fee is charged
3411 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3412 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3415 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3416 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3418 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3419 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3420 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3422 unset($params['line_item']);
3423 self
::$_trxnIDs = NULL;
3428 * Update all financial accounts entry.
3430 * @param array $params
3431 * Contribution object, line item array and params for trxn.
3433 * @param string $context
3436 * @param null $skipTrxn
3439 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3440 $itemAmount = $trxnID = NULL;
3441 //get all the statuses
3442 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3443 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3444 if (($previousContributionStatus == 'Pending'
3445 ||
$previousContributionStatus == 'In Progress')
3446 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3447 && $context == 'changePaymentInstrument'
3451 if ((($previousContributionStatus == 'Partially paid'
3452 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3453 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3454 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3455 && $context == 'changedStatus'
3459 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3460 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3462 if ($context == 'changedStatus') {
3463 //get all the statuses
3464 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3465 $cancelledTaxAmount = 0;
3466 if ($previousContributionStatus == 'Completed'
3467 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3469 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3470 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3471 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3472 $creditNoteId = self
::createCreditNoteId();
3473 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3476 elseif (($previousContributionStatus == 'Pending'
3477 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3479 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3480 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3481 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3483 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3484 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3485 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3486 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3487 $creditNoteId = self
::createCreditNoteId();
3488 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3492 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3495 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3497 elseif ($context == 'changePaymentInstrument') {
3498 $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount'];
3499 $deferredFinancialAccount = CRM_Utils_Array
::value('deferred_financial_account_id', $params);
3500 if (empty($deferredFinancialAccount)) {
3501 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' "));
3502 $deferredFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $relationTypeId);
3504 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC', FALSE, NULL, $deferredFinancialAccount);
3505 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3506 if ($params['total_amount'] != $params['trxnParams']['total_amount']) {
3507 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3508 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3511 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3512 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3517 if ($context == 'changedStatus') {
3518 if (($previousContributionStatus == 'Pending'
3519 ||
$previousContributionStatus == 'In Progress')
3520 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3522 if (empty($params['line_item'])) {
3524 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3525 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3526 // & this can be removed
3529 self
::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
3530 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3531 $params['entity_id'] = self
::$_trxnIDs[] = $trxn->id
;
3532 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3533 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3535 $entityParams = array(
3536 'entity_table' => 'civicrm_financial_item',
3538 foreach ($params['line_item'] as $fieldId => $fields) {
3539 foreach ($fields as $fieldValueId => $fieldValues) {
3541 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3542 2 => array($fieldValues['id'], 'Integer'),
3544 CRM_Core_DAO
::executeQuery($query, $fparams);
3546 1 => array($fieldValues['id'], 'Integer'),
3548 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3549 while ($financialItem->fetch()) {
3550 $entityParams['entity_id'] = $financialItem->id
;
3551 $entityParams['amount'] = $financialItem->amount
;
3552 foreach (self
::$_trxnIDs as $tID) {
3553 $entityParams['financial_trxn_id'] = $tID;
3554 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3562 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3563 $params['entity_id'] = $trxn->id
;
3564 if ($context != 'changePaymentInstrument') {
3565 $itemParams['entity_table'] = 'civicrm_line_item';
3566 $trxnIds['id'] = $params['entity_id'];
3567 foreach ($params['line_item'] as $fieldId => $fields) {
3568 foreach ($fields as $fieldValueId => $fieldValues) {
3569 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($fieldValues['id']);
3570 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3571 if ($params['contribution']->receive_date
) {
3572 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3575 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3577 $currency = $params['prevContribution']->currency
;
3578 if ($params['contribution']->currency
) {
3579 $currency = $params['contribution']->currency
;
3582 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3585 if (!empty($params['is_quick_config'])) {
3586 $amount = $itemAmount;
3588 $amount = $params['total_amount'];
3592 $amount = $diff * $fieldValues['line_total'];
3595 $itemParams = array(
3596 'transaction_date' => $receiveDate,
3597 'contact_id' => $params['prevContribution']->contact_id
,
3598 'currency' => $currency,
3599 'amount' => $amount,
3600 'description' => $prevFinancialItem->description
,
3601 'status_id' => $prevFinancialItem->status_id
,
3602 'financial_account_id' => $financialAccount,
3603 'entity_table' => 'civicrm_line_item',
3604 'entity_id' => $fieldValues['id'],
3606 $financialItem = CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3607 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3608 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id
;
3610 if ($fieldValues['tax_amount']) {
3611 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3612 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3613 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3614 $itemParams['description'] = $taxTerm;
3615 if ($fieldValues['financial_type_id']) {
3616 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3618 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3623 if ($context == 'changeFinancialType') {
3624 $params['skipLineItem'] = FALSE;
3625 foreach ($params['line_item'] as &$lineItems) {
3626 foreach ($lineItems as &$line) {
3627 $line['financial_type_id'] = $params['financial_type_id'];
3631 if ($context == 'changePaymentInstrument') {
3632 // store financial item Proportionaly.
3633 $trxnParams = array(
3634 'total_amount' => $trxn->total_amount
,
3635 'contribution_id' => $params['contribution']->id
,
3637 self
::assignProportionalLineItems($trxnParams, $trxn->id
, $params['prevContribution']->total_amount
);
3639 CRM_Core_BAO_FinancialTrxn
::createDeferredTrxn(CRM_Utils_Array
::value('line_item', $params), $params['contribution'], TRUE, $context);
3643 * Is this contribution status a reversal.
3645 * If so we would expect to record a negative value in the financial_trxn table.
3647 * @param int $status_id
3651 public static function isContributionStatusNegative($status_id) {
3652 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3653 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3657 * Check status validation on update of a contribution.
3659 * @param array $values
3660 * Previous form values before submit.
3662 * @param array $fields
3663 * The input form values.
3665 * @param array $errors
3670 public static function checkStatusValidation($values, &$fields, &$errors) {
3671 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3672 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3673 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3677 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3678 $checkStatus = array(
3679 'Cancelled' => array('Completed', 'Refunded'),
3680 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3681 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3682 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3683 'Refunded' => array('Cancelled', 'Completed'),
3684 'Partially paid' => array('Completed'),
3687 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3688 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3690 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3691 1 => $contributionStatuses[$values['contribution_status_id']],
3692 2 => $contributionStatuses[$fields['contribution_status_id']],
3698 * Delete contribution of contact.
3702 * @param int $contactId
3706 public static function deleteContactContribution($contactId) {
3707 $contribution = new CRM_Contribute_DAO_Contribution();
3708 $contribution->contact_id
= $contactId;
3709 $contribution->find();
3710 while ($contribution->fetch()) {
3711 self
::deleteContribution($contribution->id
);
3716 * Get options for a given contribution field.
3717 * @see CRM_Core_DAO::buildOptions
3719 * @param string $fieldName
3720 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3721 * @param array $props whatever is known about this dao object.
3723 * @return array|bool
3725 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3726 $className = __CLASS__
;
3728 if (isset($props['orderColumn'])) {
3729 $params['orderColumn'] = $props['orderColumn'];
3731 switch ($fieldName) {
3732 // This field is not part of this object but the api supports it
3733 case 'payment_processor':
3734 $className = 'CRM_Contribute_BAO_ContributionPage';
3735 // Filter results by contribution page
3736 if (!empty($props['contribution_page_id'])) {
3737 $page = civicrm_api('contribution_page', 'getsingle', array(
3739 'id' => ($props['contribution_page_id']),
3741 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3742 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3746 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3747 case 'honor_type_id':
3748 $className = 'CRM_Contribute_BAO_ContributionSoft';
3749 $fieldName = 'soft_credit_type_id';
3750 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3753 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3757 * Validate financial type.
3761 * @param int $financialTypeId
3762 * Financial Type id.
3764 * @param string $relationName
3766 * @return array|bool
3768 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3769 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3770 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3772 if (!$financialAccount) {
3773 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3780 * Function to record additional payment for partial and refund contributions.
3782 * @param int $contributionId
3783 * is the invoice contribution id (got created after processing participant payment).
3784 * @param array $trxnsData
3785 * to take user provided input of transaction details.
3786 * @param string $paymentType
3787 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3788 * @param int $participantId
3789 * @param bool $updateStatus
3791 * @return null|object
3793 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3794 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3795 $getInfoOf['id'] = $contributionId;
3796 $defaults = array();
3797 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3798 if (!$participantId) {
3799 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
3802 if ($paymentType == 'owed') {
3803 // build params for recording financial trxn entry
3804 $params['contribution'] = $contributionDAO;
3805 $params = array_merge($defaults, $params);
3806 $params['skipLineItem'] = TRUE;
3807 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3808 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3809 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3810 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3813 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3814 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3815 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3817 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3818 if (!empty($trxnId)) {
3819 $trxnId = $trxnId['trxn_id'];
3821 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3822 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3825 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3826 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3827 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3831 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3832 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3833 FROM civicrm_financial_trxn ft
3834 LEFT JOIN civicrm_entity_financial_trxn eft
3835 ON (ft.id = eft.financial_trxn_id)
3836 WHERE eft.entity_table = 'civicrm_contribution'
3837 AND eft.entity_id = {$contributionId}
3838 AND ft.to_financial_account_id != {$toFinancialAccount}
3839 AND ft.status_id = {$statusId}
3841 $query = CRM_Core_DAO
::executeQuery($sql);
3843 $sumOfPayments = $query->sum_of_payments
;
3846 if ($contributionDAO->total_amount
== $sumOfPayments) {
3847 // update contribution status and
3848 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3849 $contributionDAO->contribution_status_id
= $statusId;
3850 $contributionDAO->cancel_date
= 'null';
3851 $contributionDAO->cancel_reason
= NULL;
3852 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3853 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3854 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3855 $contributionDAO->save();
3857 //Change status of financial record too
3858 $financialTrxn->status_id
= $statusId;
3859 $financialTrxn->save();
3861 // note : not using the self::add method,
3862 // the reason because it performs 'status change' related code execution for financial records
3863 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3864 // are coded below i.e. just updating financial_item status to 'Paid'
3866 if ($participantId) {
3867 // update participant status
3868 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3869 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3870 foreach ($ids as $val) {
3871 $participantUpdate['id'] = $val;
3872 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3873 CRM_Event_BAO_Participant
::add($participantUpdate);
3877 // update financial item statuses
3878 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3879 $paidStatus = array_search('Paid', $financialItemStatus);
3881 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3882 $sqlFinancialItemUpdate = "
3883 UPDATE civicrm_financial_item fi
3884 LEFT JOIN civicrm_entity_financial_trxn eft
3885 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3886 SET status_id = {$paidStatus}
3887 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3889 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3892 elseif ($paymentType == 'refund') {
3893 // build params for recording financial trxn entry
3894 $params['contribution'] = $contributionDAO;
3895 $params = array_merge($defaults, $params);
3896 $params['skipLineItem'] = TRUE;
3897 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3898 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3900 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3901 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3902 // @todo remove deprecated fn call.
3903 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3905 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3907 // note : not using the self::add method,
3908 // the reason because it performs 'status change' related code execution for financial records
3909 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3910 // are coded below i.e. just updating financial_item status to 'Paid'
3911 if ($updateStatus) {
3912 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3914 // add financial item entry
3915 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3916 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionDAO->id
);
3917 if (!empty($lineItems)) {
3918 foreach ($lineItems as $lineItemId => $lineItemValue) {
3919 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount
/ $contributionDAO->total_amount
);
3920 $addFinancialEntry = array(
3921 'transaction_date' => $financialTrxn->trxn_date
,
3922 'contact_id' => $contributionDAO->contact_id
,
3923 'amount' => round($paid, 2),
3924 'status_id' => array_search('Paid', $financialItemStatus),
3925 'entity_id' => $lineItemId,
3926 'entity_table' => 'civicrm_line_item',
3928 $trxnIds['id'] = $financialTrxn->id
;
3929 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3932 if ($participantId) {
3933 // update participant status
3934 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3935 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3936 foreach ($ids as $val) {
3937 $participantUpdate['id'] = $val;
3938 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3939 CRM_Event_BAO_Participant
::add($participantUpdate);
3944 // activity creation
3945 if (!empty($financialTrxn)) {
3946 if ($participantId) {
3947 $inputParams['id'] = $participantId;
3950 $component = 'event';
3951 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3952 $entityObj = $entityObj[$participantId];
3955 $entityObj = $contributionDAO;
3956 $component = 'contribution';
3958 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3960 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3962 return $financialTrxn;
3968 * @param $activityType
3970 * @param int $contributionId
3972 * @throws CRM_Core_Exception
3974 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3975 if ($component == 'event') {
3976 $title = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3979 $title = ts('Contribution');
3981 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3982 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3983 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3984 $targetCid = $entityObj->contact_id
;
3985 // source record id would be the contribution id
3986 $srcRecId = $contributionId;
3989 $activityParams = array(
3990 'source_contact_id' => $targetCid,
3991 'source_record_id' => $srcRecId,
3992 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3996 'subject' => $subject,
3997 'activity_date_time' => $date,
3998 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
4002 'skipRecentView' => TRUE,
4005 // create activity with target contacts
4006 $session = CRM_Core_Session
::singleton();
4007 $id = $session->get('userID');
4009 $activityParams['source_contact_id'] = $id;
4010 $activityParams['target_contact_id'][] = $targetCid;
4012 CRM_Activity_BAO_Activity
::create($activityParams);
4016 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4020 * @param bool $getTrxnInfo
4021 * @param bool $usingLineTotal
4025 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
4026 if ($component == 'event') {
4027 $entity = 'participant';
4028 $entityTable = 'civicrm_participant';
4029 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4031 if (!$contributionId) {
4032 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4033 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4034 $id = $primaryParticipantId;
4036 if (!$contributionId) {
4042 $contributionId = $id;
4043 $entity = 'contribution';
4044 $entityTable = 'civicrm_contribution';
4047 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
4048 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
4050 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
4051 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4053 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
4054 $total = CRM_Price_BAO_LineItem
::getLineTotal($contributionId);
4057 $baseTrxnId = $total['trxn_id'];
4058 $total = $total['total_amount'];
4061 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
4062 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
4064 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
4065 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4066 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
4068 if ($paymentBalance == 0 && $contributionIsPayLater) {
4069 $paymentBalance = $total;
4072 $info['total'] = $total;
4073 $info['paid'] = $total - $paymentBalance;
4074 $info['balance'] = $paymentBalance;
4076 $info['component'] = $component;
4077 $info['payLater'] = $contributionIsPayLater;
4079 if ($getTrxnInfo && $baseTrxnId) {
4080 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
4082 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4084 ft.payment_instrument_id,
4085 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type
4087 FROM civicrm_contribution con
4088 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4089 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4090 AND ft.to_financial_account_id != %2
4091 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
4092 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
4093 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
4095 WHERE con.id = %1 AND ft.is_payment = 1
4097 $queryParams = array(
4098 1 => array($contributionId, 'Integer'),
4099 2 => array($feeFinancialAccount, 'Integer'),
4101 $resultDAO = CRM_Core_DAO
::executeQuery($sql, $queryParams);
4102 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4104 while ($resultDAO->fetch()) {
4105 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4106 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4107 if ($resultDAO->card_type
) {
4108 $creditCardType = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type', $resultDAO->card_type
);
4109 $pantruncation = '';
4110 if ($resultDAO->pan_truncation
) {
4111 $pantruncation = ": {$resultDAO->pan_truncation}";
4113 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4116 'total_amount' => $resultDAO->total_amount
,
4117 'financial_type' => $resultDAO->financial_account
,
4118 'payment_instrument' => $paidByLabel,
4119 'receive_date' => $resultDAO->trxn_date
,
4120 'trxn_id' => $resultDAO->trxn_id
,
4121 'status' => $statuses[$resultDAO->status_id
],
4122 'currency' => $resultDAO->currency
,
4124 if ($paidByName == 'Check') {
4125 $val['check_number'] = $resultDAO->check_number
;
4129 $info['transaction'] = $rows;
4135 * Get financial account id has 'Sales Tax Account is' account relationship with financial type.
4137 * @param int $financialTypeId
4140 * Financial Account Id
4142 public static function getFinancialAccountId($financialTypeId) {
4143 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4144 $searchParams = array(
4145 'entity_table' => 'civicrm_financial_type',
4146 'entity_id' => $financialTypeId,
4147 'account_relationship' => $accountRel,
4150 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4152 return CRM_Utils_Array
::value('financial_account_id', $result);
4156 * Get the tax amount (misnamed function).
4158 * @param array $params
4159 * @param bool $isLineItem
4163 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4164 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4166 // Update contribution.
4167 if (!empty($params['id'])) {
4168 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4169 // there are no tax implications - early return.
4170 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4173 if (empty($params['prevContribution'])) {
4174 $params['prevContribution'] = self
::getOriginalContribution($params['id']);
4177 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
4178 if (!isset($params[$field])) {
4179 if ($field == 'total_amount' && $params['prevContribution']->tax_amount
) {
4180 // Tax amount gets added back on later....
4181 $params['total_amount'] = $params['prevContribution']->total_amount
-
4182 $params['prevContribution']->tax_amount
;
4185 $params[$field] = $params['prevContribution']->$field;
4186 if ($params[$field] != $params['prevContribution']->$field) {
4192 self
::calculateMissingAmountParams($params, $params['id']);
4193 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4194 // Assign tax Amount on update of contribution
4195 if (!empty($params['prevContribution']->tax_amount
)) {
4196 $params['tax_amount'] = 'null';
4197 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4198 foreach ($params['line_item'] as $setID => $priceField) {
4199 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4200 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4207 // New Contribution and update of contribution with tax rate financial type
4208 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4209 empty($params['skipLineItem']) && !$isLineItem
4211 $taxRateParams = $taxRates[$params['financial_type_id']];
4212 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4213 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4215 // Get Line Item on update of contribution
4216 if (isset($params['id'])) {
4217 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4220 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4222 foreach ($params['line_item'] as $setID => $priceField) {
4223 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4224 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4227 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4229 elseif (isset($params['api.line_item.create'])) {
4230 // Update total amount of contribution using lineItem
4231 $taxAmountArray = array();
4232 foreach ($params['api.line_item.create'] as $key => $value) {
4233 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4234 $taxRate = $taxRates[$value['financial_type_id']];
4235 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4236 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4239 $params['tax_amount'] = array_sum($taxAmountArray);
4240 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4243 // update line item of contrbution
4244 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4245 $taxRate = $taxRates[$params['financial_type_id']];
4246 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4247 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4254 * Check financial type validation on update of a contribution.
4256 * @param Integer $financialTypeId
4257 * Value of latest Financial Type.
4259 * @param Integer $contributionId
4262 * @param array $errors
4267 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4268 if (!empty($financialTypeId)) {
4269 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4270 if ($oldFinancialTypeId == $financialTypeId) {
4274 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4276 '1' => array($contributionId, 'Integer'),
4278 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4279 if ($result->N
> 1) {
4280 $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.');
4285 * Update related pledge payment payments.
4287 * This function has been refactored out of the back office contribution form and may
4288 * still overlap with other functions.
4290 * @param string $action
4291 * @param int $pledgePaymentID
4292 * @param int $contributionID
4293 * @param bool $adjustTotalAmount
4294 * @param float $total_amount
4295 * @param float $original_total_amount
4296 * @param int $contribution_status_id
4297 * @param int $original_contribution_status_id
4299 public static function updateRelatedPledge(
4305 $original_total_amount,
4306 $contribution_status_id,
4307 $original_contribution_status_id
4309 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4313 if ($pledgePaymentID) {
4314 //store contribution id in payment record.
4315 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4318 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4325 if (!$pledgePaymentID) {
4328 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4334 $updatePledgePaymentStatus = FALSE;
4336 // If either the status or the amount has changed we update the pledge status.
4337 if ($action & CRM_Core_Action
::ADD
) {
4338 $updatePledgePaymentStatus = TRUE;
4340 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4341 ($original_total_amount != $total_amount))
4343 $updatePledgePaymentStatus = TRUE;
4346 if ($updatePledgePaymentStatus) {
4347 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4348 array($pledgePaymentID),
4349 $contribution_status_id,
4358 * Compute the stats values
4360 * @param string $stat either 'mode' or 'median'
4361 * @param string $sql
4362 * @param string $alias of civicrm_contribution
4364 * @return array|null
4366 public static function computeStats($stat, $sql, $alias = NULL) {
4367 $mode = $median = array();
4370 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4371 while ($modeDAO->fetch()) {
4372 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4373 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4382 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4383 foreach ($currencies as $currency => $val) {
4385 $where = "AND {$alias}.currency = '{$currency}'";
4386 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4390 $medianRow = floor($rowCount / 2);
4391 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4397 $medianValue = "SELECT {$alias}.total_amount as median
4399 ORDER BY median LIMIT {$medianRow},{$offset}";
4400 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4401 while ($medianValDAO->fetch()) {
4403 $midValue = $midValue +
$medianValDAO->median
;
4406 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4410 $midValue = $midValue / 2;
4411 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4422 * Is there only one line item attached to the contribution.
4428 * @throws \CiviCRM_API3_Exception
4430 public static function isSingleLineItem($id) {
4431 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4432 return ($lineItemCount == 1);
4436 * Complete an order.
4438 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4440 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4442 * Moving it out of the BaseIPN class is just the first step.
4444 * @param array $input
4446 * @param array $objects
4447 * @param CRM_Core_Transaction $transaction
4449 * @param CRM_Contribute_BAO_Contribution $contribution
4450 * @param bool $isRecurring
4451 * Duplication of param needs review. Only used by AuthorizeNetIPN
4452 * @param int $isFirstOrLastRecurringPayment
4453 * Deprecated param only used by AuthorizeNetIPN.
4457 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4458 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4459 // The previous details are used when calculating line items so keep it before any code that 'does something'
4460 if (!empty($contribution->id
)) {
4461 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4462 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4464 $inputContributionWhiteList = array(
4469 'payment_instrument_id',
4474 'contribution_status_id',
4476 if (self
::isSingleLineItem($primaryContributionID)) {
4477 $inputContributionWhiteList[] = 'financial_type_id';
4480 $participant = CRM_Utils_Array
::value('participant', $objects);
4481 $memberships = CRM_Utils_Array
::value('membership', $objects);
4482 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4483 $recurringContributionID = (empty($recurContrib->id
)) ?
NULL : $recurContrib->id
;
4484 $event = CRM_Utils_Array
::value('event', $objects);
4486 $paymentProcessorId = '';
4487 if (isset($objects['paymentProcessor'])) {
4488 if (is_array($objects['paymentProcessor'])) {
4489 $paymentProcessorId = $objects['paymentProcessor']['id'];
4492 $paymentProcessorId = $objects['paymentProcessor']->id
;
4496 $completedContributionStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4498 $contributionParams = array_merge(array(
4499 'contribution_status_id' => $completedContributionStatusID,
4500 'source' => self
::getRecurringContributionDescription($contribution, $event),
4501 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4503 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
4505 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4506 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4507 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'])) {
4508 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects
['paymentProcessor']['payment_instrument_id'];
4511 if ($recurringContributionID) {
4512 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4514 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4516 if (empty($contributionParams['receive_date']) && $changeDate) {
4517 $contributionParams['receive_date'] = $changeDate;
4520 self
::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
4521 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4523 if (is_numeric($memberships)) {
4524 $memberships = array($objects['membership']);
4528 if (isset($input['is_email_receipt'])) {
4529 $values['is_email_receipt'] = $input['is_email_receipt'];
4532 if ($input['component'] == 'contribute') {
4533 if ($contribution->contribution_page_id
) {
4534 // Figure out what we gain from this.
4535 // Note that we may have overwritten the is_email_receipt input, fix that below.
4536 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4538 elseif ($recurContrib && $recurringContributionID) {
4539 $values['amount'] = $recurContrib->amount
;
4540 $values['financial_type_id'] = $objects['contributionType']->id
;
4541 $values['title'] = $source = ts('Offline Recurring Contribution');
4544 if (isset($input['is_email_receipt'])) {
4545 // CRM-19601 - we may have overwritten this above.
4546 $values['is_email_receipt'] = $input['is_email_receipt'];
4548 elseif ($recurContrib && $recurringContributionID) {
4549 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4550 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4551 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4554 if (!empty($memberships)) {
4555 foreach ($memberships as $membershipTypeIdKey => $membership) {
4557 $membershipParams = array(
4558 'id' => $membership->id
,
4559 'contact_id' => $membership->contact_id
,
4560 'is_test' => $membership->is_test
,
4561 'membership_type_id' => $membership->membership_type_id
,
4564 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4565 $membershipParams['membership_type_id'],
4566 $membershipParams['is_test'],
4567 $membershipParams['id']
4570 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4571 // this picks up membership type changes during renewals
4572 // @todo this is almost certainly an obsolete sql call, the pre-change
4573 // membership is accessible via $this->_relatedObjects
4575 SELECT membership_type_id
4576 FROM civicrm_membership_log
4577 WHERE membership_id={$membershipParams['id']}
4580 $dao = CRM_Core_DAO
::executeQuery($sql);
4581 if ($dao->fetch()) {
4582 if (!empty($dao->membership_type_id
)) {
4583 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4588 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4589 $membershipParams['membership_type_id'],
4590 $primaryContributionID
4592 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4593 if ($currentMembership) {
4595 * Fixed FOR CRM-4433
4596 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4597 * when Contribution mode is notify and membership is for renewal )
4599 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4601 // @todo - we should pass membership_type_id instead of null here but not
4602 // adding as not sure of testing
4603 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4604 $changeDate, NULL, $membershipParams['num_terms']
4607 $dates['join_date'] = $currentMembership['join_date'];
4610 //get the status for membership.
4611 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4613 $dates['join_date'],
4616 $membershipParams['membership_type_id'],
4620 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4621 //we might be renewing membership,
4622 //so make status override false.
4623 $membershipParams['is_override'] = FALSE;
4624 //CRM-17723 - reset static $relatedContactIds array()
4626 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4627 civicrm_api3('Membership', 'create', $membershipParams);
4628 //CRM-19600: Add Membership Renewal activity
4629 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Renewal', $membership->contact_id
);
4635 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4636 if ($event->is_email_confirm
) {
4637 // @todo this should be set by the function that sends the mail after sending.
4638 $contributionParams['receipt_date'] = $changeDate;
4640 $participantParams['id'] = $participant->id
;
4641 $participantParams['status_id'] = 'Registered';
4642 civicrm_api3('Participant', 'create', $participantParams);
4646 $contributionParams['id'] = $contribution->id
;
4648 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
4649 // unsetting it here does NOT cause any other contribution test to fail!
4650 unset($contributionParams['financial_type_id']);
4651 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4653 // Add new soft credit against current $contribution.
4654 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4655 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4658 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4659 'labelColumn' => 'name',
4662 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4663 $input['payment_processor'] = $paymentProcessorId;
4666 if (!empty($contribution->_relatedObjects
['participant'])) {
4667 $input['contribution_mode'] = 'participant';
4668 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4670 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4671 $input['contribution_mode'] = 'membership';
4672 $contribution->contribution_status_id
= $contributionParams['contribution_status_id'];
4673 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4674 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4677 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4678 $transaction->commit();
4680 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution->id
, $recurringContributionID,
4681 $contributionParams['contribution_status_id'], $input['amount']);
4683 // create an activity record
4684 if ($input['component'] == 'contribute') {
4686 $targetContactID = NULL;
4687 if (!empty($ids['related_contact'])) {
4688 $targetContactID = $contribution->contact_id
;
4689 $contribution->contact_id
= $ids['related_contact'];
4691 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4695 CRM_Activity_BAO_Activity
::addActivity($participant);
4698 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4699 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4700 if (!array_key_exists('is_email_receipt', $values) ||
4701 $values['is_email_receipt'] == 1
4703 civicrm_api3('Contribution', 'sendconfirmation', array(
4704 'id' => $contribution->id
,
4705 'payment_processor_id' => $paymentProcessorId,
4707 CRM_Core_Error
::debug_log_message("Receipt sent");
4710 CRM_Core_Error
::debug_log_message("Success: Database updated");
4712 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4713 $isFirstOrLastRecurringPayment);
4715 return $contributionResult;
4719 * Send receipt from contribution.
4721 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4723 * Note that the compose message part has been moved to contribution
4724 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4726 * @param array $input
4727 * Incoming data from Payment processor.
4729 * Related object IDs.
4730 * @param int $contributionID
4731 * @param array $values
4732 * Values related to objects that have already been loaded.
4733 * @param bool $returnMessageText
4734 * Should text be returned instead of sent. This.
4735 * is because the function is also used to generate pdfs
4738 * @throws \CRM_Core_Exception
4739 * @throws \CiviCRM_API3_Exception
4741 public static function sendMail(&$input, &$ids, $contributionID, &$values,
4742 $returnMessageText = FALSE) {
4744 $contribution = new CRM_Contribute_BAO_Contribution();
4745 $contribution->id
= $contributionID;
4746 if (!$contribution->find(TRUE)) {
4747 throw new CRM_Core_Exception('Contribution does not exist');
4749 $contribution->loadRelatedObjects($input, $ids, TRUE);
4750 // set receipt from e-mail and name in value
4751 if (!$returnMessageText) {
4752 list($values['receipt_from_name'], $values['receipt_from_email']) = self
::generateFromEmailAndName($input, $contribution);
4754 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4755 // Contribution ID should really always be set. But ?
4756 if (!$returnMessageText && (!isset($input['receipt_update']) ||
$input['receipt_update']) && empty($contribution->receipt_date
)) {
4757 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id
));
4763 * Generate From email and from name in an array values
4765 public static function generateFromEmailAndName($input, $contribution) {
4766 // Use input valuse if supplied.
4767 if (!empty($input['receipt_from_email'])) {
4768 return array(CRM_Utils_array
::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4770 // if we are still empty see if we can use anything from a contribution page.
4771 $pageValues = array();
4772 if (!empty($contribution->contribution_page_id
)) {
4773 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id
));
4775 // if we are still empty see if we can use anything from a contribution page.
4776 if (!empty($pageValues['receipt_from_email'])) {
4777 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4779 // If we are still empty fall back to the domain or logged in user information.
4780 return CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
4784 * Generate credit note id with next avaible number
4789 public static function createCreditNoteId() {
4790 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4792 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4793 $creditNoteId = NULL;
4797 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4798 $result = civicrm_api3('Contribution', 'getcount', array(
4800 'creditnote_id' => $creditNoteId,
4802 } while ($result > 0);
4804 return $creditNoteId;
4808 * Load related memberships.
4810 * Note that in theory it should be possible to retrieve these from the line_item table
4811 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4812 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4813 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4814 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4816 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4822 public function loadRelatedMembershipObjects(&$ids) {
4824 SELECT membership_id
4825 FROM civicrm_membership_payment
4826 WHERE contribution_id = %1 ";
4827 $params = array(1 => array($this->id
, 'Integer'));
4828 $ids['membership'] = (array) CRM_Utils_Array
::value('membership', $ids, array());
4830 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4831 while ($dao->fetch()) {
4832 if ($dao->membership_id
&& !in_array($dao->membership_id
, $ids['membership'])) {
4833 $ids['membership'][$dao->membership_id
] = $dao->membership_id
;
4837 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4838 foreach ($ids['membership'] as $id) {
4840 $membership = new CRM_Member_BAO_Membership();
4841 $membership->id
= $id;
4842 if (!$membership->find(TRUE)) {
4843 throw new Exception("Could not find membership record: $id");
4845 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4846 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4847 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4848 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4849 $membership->free();
4856 * This function is used to record partial payments for contribution
4858 * @param array $contribution
4860 * @param array $params
4864 public static function recordPartialPayment($contribution, $params) {
4865 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4866 $pendingStatus = array(
4867 array_search('Pending', $contributionStatuses),
4868 array_search('In Progress', $contributionStatuses),
4870 $statusId = array_search('Completed', $contributionStatuses);
4871 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4872 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4873 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4875 elseif (!empty($params['payment_processor'])) {
4876 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4878 elseif (!empty($params['payment_instrument_id'])) {
4879 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4882 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4883 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4884 $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);
4886 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4887 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4888 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4889 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4890 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4891 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4892 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4893 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4894 $balanceTrxnParams['currency'] = $contribution['currency'];
4895 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4896 $balanceTrxnParams['status_id'] = $statusId;
4897 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4898 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4899 if ($fromFinancialAccountId != NULL &&
4900 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4902 $balanceTrxnParams['is_payment'] = 1;
4904 if (!empty($params['payment_processor'])) {
4905 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4907 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4911 * Get the description (source field) for the recurring contribution.
4913 * @param CRM_Contribute_BAO_Contribution $contribution
4914 * @param CRM_Event_DAO_Event|null $event
4917 * @throws \CiviCRM_API3_Exception
4919 protected static function getRecurringContributionDescription($contribution, $event) {
4920 if (!empty($contribution->source
)) {
4921 return $contribution->source
;
4923 elseif (!empty($contribution->contribution_page_id
) && is_numeric($contribution->contribution_page_id
)) {
4924 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4925 'id' => $contribution->contribution_page_id
,
4926 'return' => 'title',
4928 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4931 return ts('Online Event Registration') . ': ' . $event->title
;
4933 elseif (!empty($contribution->contribution_recur_id
)) {
4934 return 'recurring contribution';
4940 * Function to add payments for contribution
4941 * for Partially Paid status
4943 * @param array $contributions
4944 * @param array $contributionStatusId
4947 public static function addPayments($contributions, $contributionStatusId = NULL) {
4948 // get financial trxn which is a payment
4949 $ftSql = "SELECT ft.id, ft.total_amount
4950 FROM civicrm_financial_trxn ft
4951 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4952 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
4953 $contributionStatus = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4954 'labelColumn' => 'name',
4956 foreach ($contributions as $k => $contribution) {
4957 if (!($contributionStatus[$contribution->contribution_status_id
] == 'Partially paid'
4958 || CRM_Utils_Array
::value($contributionStatusId, $contributionStatus) == 'Partially paid')
4962 $ftDao = CRM_Core_DAO
::executeQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4965 // store financial item Proportionaly.
4966 $trxnParams = array(
4967 'total_amount' => $ftDao->total_amount
,
4968 'contribution_id' => $contribution->id
,
4970 self
::assignProportionalLineItems($trxnParams, $ftDao->id
, $contribution->total_amount
);
4975 * Function use to store line item proportionaly in
4976 * in entity financial trxn table
4978 * @param array $trxnParams
4980 * @param Integer $trxnId
4982 * @param float $contributionTotalAmount
4985 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4986 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($trxnParams['contribution_id']);
4987 if (!empty($lineItems)) {
4988 // get financial item
4989 list($ftIds, $taxItems) = self
::getLastFinancialItemIds($trxnParams['contribution_id']);
4990 $entityParams = array(
4991 'contribution_total_amount' => $contributionTotalAmount,
4992 'trxn_total_amount' => $trxnParams['total_amount'],
4993 'trxn_id' => $trxnId,
4995 self
::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
5000 * Function to check line items.
5002 * @param array $params
5003 * array of order params.
5005 * @throws \API_Exception
5007 public static function checkLineItems(&$params) {
5008 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
5009 $lineItemAmount = 0;
5010 foreach ($params['line_items'] as &$lineItems) {
5011 foreach ($lineItems['line_item'] as &$item) {
5012 if (empty($item['financial_type_id'])) {
5013 $item['financial_type_id'] = $params['financial_type_id'];
5015 $lineItemAmount +
= $item['line_total'];
5018 if (!isset($totalAmount)) {
5019 $params['total_amount'] = $lineItemAmount;
5021 elseif ($totalAmount != $lineItemAmount) {
5022 throw new API_Exception("Line item total doesn't match with total amount.");
5027 * Get the financial account for the item associated with the new transaction.
5029 * @param array $params
5030 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
5034 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
5036 if (!empty($params['financial_account_id'])) {
5037 return $params['financial_account_id'];
5039 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
5040 $preferredAccountsRelationships = array(
5041 'Refunded' => 'Credit/Contra Revenue Account is',
5042 'Chargeback' => 'Chargeback Account is',
5044 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5045 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
5046 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
5048 $preferredAccountsRelationships[$contributionStatus]
5051 return $prevFinancialItem->financial_account_id
;
5055 * ContributionPage values were being imposed onto values.
5057 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5058 * REALLY didn't want superimposed. The rest are left there in their overkill out
5061 * The rationale for making this explicit is that it was a case of carefully set values being
5062 * seemingly randonly overwritten without much care. In general I think array randomly setting
5063 * variables en mass is risky.
5065 * @param array $values
5069 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5070 $contributionPageValues = array();
5071 CRM_Contribute_BAO_ContributionPage
::setValues(
5072 $this->contribution_page_id
,
5073 $contributionPageValues
5075 $valuesToCopy = array(
5076 // These are the values that I believe to be useful.
5079 'pay_later_receipt',
5081 'receipt_from_email',
5082 'receipt_from_name',
5086 'honoree_profile_id',
5087 'onbehalf_profile_id',
5088 'honor_block_is_active',
5089 // Kinda might be - but would be on the contribution...
5092 // Included for 'fear of regression' but can't justify any use for these....
5094 'payment_processor',
5095 'financial_type_id',
5096 'amount_block_is_active',
5101 'default_amount_id',
5105 'initial_amount_help_text',
5106 'initial_amount_label',
5108 'is_allow_other_amount',
5109 'is_billing_required',
5110 'is_confirm_enabled',
5111 'is_credit_card_only',
5113 'is_partial_payment',
5114 'is_recur_installments',
5115 'is_recur_interval',
5119 'min_initial_amount',
5120 'recur_frequency_unit',
5127 foreach ($valuesToCopy as $valueToCopy) {
5128 if (isset($contributionPageValues[$valueToCopy])) {
5129 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5136 * Get values of CiviContribute Settings
5137 * and check if its enabled or not.
5138 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5139 * in serialized form. Usually this should be stored as flat settings for each form fields
5140 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5141 * settings we will live with an inconsistency because it's too hard to change for now.
5142 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
5145 * @param string $name
5149 public static function checkContributeSettings($name = NULL) {
5150 $contributeSettings = Civi
::settings()->get('contribution_invoice_settings');
5153 return CRM_Utils_Array
::value($name, $contributeSettings);
5155 return $contributeSettings;
5159 * This function process contribution related objects.
5161 * @param int $contributionId
5162 * @param int $statusId
5163 * @param int|null $previousStatusId
5165 * @param string $receiveDate
5167 * @return null|string
5169 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5171 if (!$contributionId ||
!$statusId) {
5176 'contribution_id' => $contributionId,
5177 'contribution_status_id' => $statusId,
5178 'previous_contribution_status_id' => $previousStatusId,
5179 'receive_date' => $receiveDate,
5182 $updateResult = CRM_Contribute_BAO_Contribution
::transitionComponents($params);
5184 if (!is_array($updateResult) ||
5185 !($updatedComponents = CRM_Utils_Array
::value('updatedComponents', $updateResult)) ||
5186 !is_array($updatedComponents) ||
5187 empty($updatedComponents)
5192 // get the user display name.
5194 SELECT display_name as displayName
5195 FROM civicrm_contact
5196 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5197 WHERE civicrm_contribution.id = {$contributionId}";
5198 $userDisplayName = CRM_Core_DAO
::singleValueQuery($sql);
5200 // get the status message for user.
5201 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5203 if ($componentName == 'CiviMember') {
5204 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5205 CRM_Member_PseudoConstant
::membershipStatus()
5207 if ($updatedStatusName == 'Cancelled') {
5208 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5210 elseif ($updatedStatusName == 'Expired') {
5211 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5214 $endDate = CRM_Utils_Array
::value('membership_end_date', $updateResult);
5216 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5218 1 => $userDisplayName,
5226 if ($componentName == 'CiviEvent') {
5227 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5228 CRM_Event_PseudoConstant
::participantStatus()
5230 if ($updatedStatusName == 'Cancelled') {
5231 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5233 elseif ($updatedStatusName == 'Registered') {
5234 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5238 if ($componentName == 'CiviPledge') {
5239 $updatedStatusName = CRM_Utils_Array
::value($updatedStatusId,
5240 CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name')
5242 if ($updatedStatusName == 'Cancelled') {
5243 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5245 elseif ($updatedStatusName == 'Failed') {
5246 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5248 elseif ($updatedStatusName == 'Completed') {
5249 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5258 * Get the contribution as it is in the database before being updated.
5260 * @param int $contributionID
5264 private static function getOriginalContribution($contributionID) {
5265 return self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
5269 * Assign Test Value.
5271 * @param string $fieldName
5272 * @param array $fieldDef
5273 * @param int $counter
5275 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5276 if ($fieldName == 'tax_amount') {
5277 $this->{$fieldName} = "0.00";
5279 elseif ($fieldName == 'net_amount') {
5280 $this->{$fieldName} = "2.00";
5282 elseif ($fieldName == 'total_amount') {
5283 $this->{$fieldName} = "3.00";
5285 elseif ($fieldName == 'fee_amount') {
5286 $this->{$fieldName} = "1.00";
5289 parent
::assignTestValues($fieldName, $fieldDef, $counter);
5294 * Check if contribution has participant/membership payment.
5296 * @param int $contributionId
5301 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5302 // get line item for contribution
5303 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($contributionId);
5304 // check if line item is for membership or participant
5305 foreach ($lineItems as $items) {
5306 if ($items['entity_table'] == 'civicrm_participant') {
5310 elseif ($items['entity_table'] == 'civicrm_membership') {
5322 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5324 * @param array $trxnParams
5325 * Financial trxn params
5326 * @param string $contributionParams
5327 * Contribution Params
5331 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5332 if (!self
::checkContributeSettings('always_post_to_accounts_receivable')) {
5335 $statusId = $contributionParams['contribution']->contribution_status_id
;
5336 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
5337 $contributionStatus = empty($statusId) ?
NULL : $contributionStatuses[$statusId];
5338 $previousContributionStatus = empty($contributionParams['prevContribution']) ?
NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id
];
5339 // Return if contribution status is not completed.
5340 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5341 ||
(!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5342 && $contributionParams['prevContribution']->is_pay_later
== 0
5348 $params = $trxnParams;
5349 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $contributionParams) ?
$contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id
;
5350 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
5351 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
5352 $params['to_financial_account_id'] = $arAccountId;
5353 $params['status_id'] = array_search('Pending', $contributionStatuses);
5354 $params['is_payment'] = FALSE;
5355 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params);
5356 self
::$_trxnIDs[] = $trxn->id
;
5357 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5361 * Calculate financial item amount when contribution is updated.
5363 * @param array $params
5364 * contribution params
5365 * @param array $amountParams
5367 * @param string $context
5371 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5372 if (!empty($params['is_quick_config'])) {
5373 $amount = $amountParams['item_amount'];
5375 $amount = $params['total_amount'];
5376 if ($context === NULL) {
5377 $amount -= CRM_Utils_Array
::value('tax_amount', $params, 0);
5382 $amount = $amountParams['line_total'];
5383 if ($context == 'changedAmount') {
5384 $amount -= $amountParams['previous_line_total'];
5386 $amount *= $amountParams['diff'];
5392 * Retrieve Sales Tax Financial Accounts.
5398 public static function getSalesTaxFinancialAccounts() {
5399 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5400 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5401 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5402 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5403 $queryParams = array(1 => array($accountRel, 'Integer'));
5404 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
5405 $financialAccount = array();
5406 while ($dao->fetch()) {
5407 $financialAccount[$dao->id
] = $dao->id
;
5409 return $financialAccount;
5413 * Create tax entry in civicrm_entity_financial_trxn table.
5415 * @param array $entityParams
5417 * @param array $eftParams
5420 public static function createProportionalEntry($entityParams, $eftParams) {
5421 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5422 // Record Entity Financial Trxn; CRM-20145
5423 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils
::formatAmount($paid);
5424 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5428 * Create array of last financial item id's.
5430 * @param int $contributionId
5434 public static function getLastFinancialItemIds($contributionId) {
5435 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5436 FROM civicrm_financial_item fi
5437 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5438 WHERE li.contribution_id = %1";
5439 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5440 $ftIds = $taxItems = array();
5441 $salesTaxFinancialAccount = self
::getSalesTaxFinancialAccounts();
5442 while ($dao->fetch()) {
5443 /* if sales tax item*/
5444 if (in_array($dao->financial_account_id
, $salesTaxFinancialAccount)) {
5445 $taxItems[$dao->price_field_value_id
] = array(
5446 'financial_item_id' => $dao->id
,
5447 'amount' => $dao->tax_amount
,
5451 $ftIds[$dao->price_field_value_id
] = $dao->id
;
5454 return array($ftIds, $taxItems);
5458 * Create proportional entries in civicrm_entity_financial_trxn.
5460 * @param array $entityParams
5462 * @param array $lineItems
5464 * @param array $ftIds
5466 * @param array $taxItems
5469 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5471 'entity_table' => 'civicrm_financial_item',
5472 'financial_trxn_id' => $entityParams['trxn_id'],
5474 foreach ($lineItems as $key => $value) {
5475 if ($value['qty'] == 0) {
5478 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5479 $entityParams['line_item_amount'] = $value['line_total'];
5480 self
::createProportionalEntry($entityParams, $eftParams);
5481 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5482 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5483 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5484 self
::createProportionalEntry($entityParams, $eftParams);
5490 * Load entities related to the contribution into $this->_relatedObjects.
5494 * @throws \CRM_Core_Exception
5496 protected function loadRelatedEntitiesByID($ids) {
5498 'contact' => 'CRM_Contact_BAO_Contact',
5499 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5500 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5501 'financialType' => 'CRM_Financial_BAO_FinancialType',
5502 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5504 foreach ($entities as $entity => $bao) {
5505 if (!empty($ids[$entity])) {
5506 $this->_relatedObjects
[$entity] = new $bao();
5507 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
5508 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
5509 throw new CRM_Core_Exception($entity . ' could not be loaded');
5516 * Should an email receipt be sent for this contribution when complete.
5518 * @param array $input
5522 protected function isEmailReceipt($input) {
5523 if (isset($input['is_email_receipt'])) {
5524 return $input['is_email_receipt'];
5526 if (!empty($this->_relatedObjects
['contribution_page_id'])) {
5527 return $this->_relatedObjects
['contribution_page_id']->is_email_receipt
;