3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 * @return \CRM_Contribute_DAO_Contribution
81 public function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object.
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params
93 * (reference ) an assoc array of name/value pairs.
95 * The array that holds all the db ids.
97 * @return CRM_Contribute_BAO_Contribution|void
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
139 self
::calculateMissingAmountParams($params);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
174 $config = CRM_Core_Config
::singleton();
175 $contribution->currency
= $config->defaultCurrency
;
178 if ($contributionID && $setPrevContribution) {
179 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
182 $result = $contribution->save();
184 // Add financial_trxn details as part of fix for CRM-4724
185 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
186 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
188 //add Account details
189 $params['contribution'] = $contribution;
190 self
::recordFinancialAccounts($params);
192 // reset the group contact cache for this group
193 CRM_Contact_BAO_GroupContactCache
::remove();
195 if ($contributionID) {
196 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
199 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
206 * Get defaults for new entity.
209 public static function getDefaults() {
211 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
212 FALSE, FALSE, FALSE, 'AND is_default = 1')
214 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
219 * Given the list of params in the params array, fetch the object
220 * and store the values in the values array
222 * @param array $params
223 * Input parameters to find object.
224 * @param array $values
225 * Output values of the object.
227 * The array that holds all the db ids.
229 * @return CRM_Contribute_BAO_Contribution|null
230 * The found object or null
232 public static function getValues($params, &$values, &$ids) {
233 if (empty($params)) {
236 $contribution = new CRM_Contribute_BAO_Contribution();
238 $contribution->copyValues($params);
240 if ($contribution->find(TRUE)) {
241 $ids['contribution'] = $contribution->id
;
243 CRM_Core_DAO
::storeValues($contribution, $values);
245 return $contribution;
247 $null = NULL; // return by reference
252 * Calculate net_amount & fee_amount if they are not set.
254 * Net amount should be total - fee.
255 * This should only be called for new contributions.
257 * @param array $params
258 * Params for a new contribution before they are saved.
260 public static function calculateMissingAmountParams(&$params) {
261 if (!isset($params['fee_amount'])) {
262 if (isset($params['total_amount']) && isset($params['net_amount'])) {
263 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
266 $params['fee_amount'] = 0;
269 if (!isset($params['net_amount'])) {
270 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
276 * @param $billingLocationTypeID
280 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
281 $hasBillingField = FALSE;
282 $billingFields = array(
290 //build address array
291 $addressParams = array();
292 $addressParams['location_type_id'] = $billingLocationTypeID;
293 $addressParams['is_billing'] = 1;
295 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
296 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
297 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
298 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
300 foreach ($billingFields as $value) {
301 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
302 if (!empty($addressParams[$value])) {
303 $hasBillingField = TRUE;
306 return array($hasBillingField, $addressParams);
310 * Get address params ready to be passed to the payment processor.
312 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
313 * To create an address we need state_province_id.
315 * @param array $params
316 * @param int $billingLocationTypeID
320 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
321 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
322 foreach ($addressParams as $name => $field) {
323 if (substr($name, 0, 8) == 'billing_') {
324 $addressParams[substr($name, 9)] = $addressParams[$field];
327 return array($hasBillingField, $addressParams);
331 * Get the number of terms for this contribution for a given membership type
332 * based on querying the line item table and relevant price field values
333 * Note that any one contribution should only be able to have one line item relating to a particular membership
336 * @param int $membershipTypeID
338 * @param int $contributionID
342 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
343 $numTerms = CRM_Core_DAO
::singleValueQuery("
344 SELECT membership_num_terms FROM civicrm_line_item li
345 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
346 WHERE contribution_id = %1 AND membership_type_id = %2",
347 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
349 // default of 1 is precautionary
350 return empty($numTerms) ?
1 : $numTerms;
354 * Takes an associative array and creates a contribution object.
356 * @param array $params
357 * (reference ) an assoc array of name/value pairs.
359 * The array that holds all the db ids.
361 * @return CRM_Contribute_BAO_Contribution
363 public static function create(&$params, $ids = array()) {
364 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
365 foreach ($dateFields as $df) {
366 if (isset($params[$df])) {
367 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
371 $transaction = new CRM_Core_Transaction();
373 $contribution = self
::add($params, $ids);
375 if (is_a($contribution, 'CRM_Core_Error')) {
376 $transaction->rollback();
377 return $contribution;
380 $params['contribution_id'] = $contribution->id
;
382 if (!empty($params['custom']) &&
383 is_array($params['custom'])
385 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
388 $session = CRM_Core_Session
::singleton();
390 if (!empty($params['note'])) {
392 'entity_table' => 'civicrm_contribution',
393 'note' => $params['note'],
394 'entity_id' => $contribution->id
,
395 'contact_id' => $session->get('userID'),
396 'modified_date' => date('Ymd'),
398 if (!$noteParams['contact_id']) {
399 $noteParams['contact_id'] = $params['contact_id'];
401 CRM_Core_BAO_Note
::add($noteParams);
404 // make entry in batch entity batch table
405 if (!empty($params['batch_id'])) {
406 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
407 $titleFields = array(
413 $retrieveRequired = 0;
414 foreach ($titleFields as $titleField) {
415 if (!isset($contribution->$titleField)) {
416 $retrieveRequired = 1;
420 if ($retrieveRequired == 1) {
421 $contribution->find(TRUE);
425 // Handle soft credit and / or link to personal campaign page
426 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
428 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
430 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
431 $softParams = array();
432 $softParams['contribution_id'] = $contribution->id
;
433 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
434 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
435 $pcp['pcp_made_through_id'], 'contact_id'
437 $softParams['currency'] = $contribution->currency
;
438 $softParams['amount'] = $contribution->total_amount
;
439 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
440 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
441 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
442 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
443 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
444 //Send notification to owner for PCP
445 if ($contributionSoft->pcp_id
) {
446 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
449 //Delete PCP against this contribution and create new on submitted PCP information
450 elseif (array_key_exists('pcp', $params) && $pcpId) {
451 $deleteParams = array('id' => $pcpId);
452 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
454 if (isset($params['soft_credit'])) {
455 $softParams = $params['soft_credit'];
457 if (!empty($softIDs)) {
458 foreach ($softIDs as $softID) {
459 if (!in_array($softID, $params['soft_credit_ids'])) {
460 $deleteParams = array('id' => $softID);
461 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
466 foreach ($softParams as $softParam) {
467 $softParam['contribution_id'] = $contribution->id
;
468 $softParam['currency'] = $contribution->currency
;
469 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
470 if (empty($softParam['amount'])) {
471 $softParam['amount'] = $contribution->total_amount
;
473 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
477 $transaction->commit();
479 // check if activity record exist for this contribution, if
481 $activity = new CRM_Activity_DAO_Activity();
482 $activity->source_record_id
= $contribution->id
;
483 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
487 if (!$activity->find(TRUE)) {
488 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
491 // CRM-13237 : if activity record found, update it with campaign id of contribution
492 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
495 // do not add to recent items for import, CRM-4399
496 if (empty($params['skipRecentView'])) {
497 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
498 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
500 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
501 $titleFields = array(
507 $retrieveRequired = 0;
508 foreach ($titleFields as $titleField) {
509 if (!isset($contribution->$titleField)) {
510 $retrieveRequired = 1;
514 if ($retrieveRequired == 1) {
515 $contribution->find(TRUE);
517 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
518 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
520 $recentOther = array();
521 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
522 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
523 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
527 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
528 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
529 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
533 // add the recently created Contribution
534 CRM_Utils_Recent
::add($title,
538 $contribution->contact_id
,
544 return $contribution;
548 * Get the values for pseudoconstants for name->value and reverse.
550 * @param array $defaults
551 * (reference) the default values, some of which need to be resolved.
552 * @param bool $reverse
553 * True if we want to resolve the values in the reverse direction (value -> name).
555 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
556 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
557 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
558 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
559 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
563 * Convert associative array names to values and vice-versa.
565 * This function is used by both the web form layer and the api. Note that
566 * the api needs the name => value conversion, also the view layer typically
567 * requires value => name conversion
569 * @param array $defaults
570 * @param string $property
571 * @param array $lookup
572 * @param bool $reverse
576 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
577 $id = $property . '_id';
579 $src = $reverse ?
$property : $id;
580 $dst = $reverse ?
$id : $property;
582 if (!array_key_exists($src, $defaults)) {
586 $look = $reverse ?
array_flip($lookup) : $lookup;
588 if (is_array($look)) {
589 if (!array_key_exists($defaults[$src], $look)) {
593 $defaults[$dst] = $look[$defaults[$src]];
598 * Retrieve DB object based on input parameters.
600 * It also stores all the retrieved values in the default array.
602 * @param array $params
603 * (reference ) an assoc array of name/value pairs.
604 * @param array $defaults
605 * (reference ) an assoc array to hold the name / value pairs.
606 * in a hierarchical manner
608 * (reference) the array that holds all the db ids.
610 * @return CRM_Contribute_BAO_Contribution
612 public static function retrieve(&$params, &$defaults, &$ids) {
613 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
614 return $contribution;
618 * Combine all the importable fields from the lower levels object.
620 * The ordering is important, since currently we do not have a weight
621 * scheme. Adding weight is super important and should be done in the
622 * next week or so, before this can be called complete.
624 * @param string $contactType
625 * @param bool $status
628 * array of importable Fields
630 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
631 if (!self
::$_importableFields) {
632 if (!self
::$_importableFields) {
633 self
::$_importableFields = array();
637 $fields = array('' => array('title' => ts('- do not import -')));
640 $fields = array('' => array('title' => ts('- Contribution Fields -')));
643 $note = CRM_Core_DAO_Note
::import();
644 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
645 unset($tmpFields['option_value']);
646 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
647 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
649 // Using new Dedupe rule.
651 'contact_type' => $contactType,
652 'used' => 'Unsupervised',
654 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
655 $tmpContactField = array();
656 if (is_array($fieldsArray)) {
657 foreach ($fieldsArray as $value) {
658 //skip if there is no dupe rule
659 if ($value == 'none') {
662 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
667 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
668 $tmpContactField[trim($value)] = $contactFields[trim($value)];
670 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
673 $title = $tmpContactField[trim($value)]['title'];
675 $tmpContactField[trim($value)]['title'] = $title;
679 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
680 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
681 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
682 $fields = array_merge($fields, $tmpContactField);
683 $fields = array_merge($fields, $tmpFields);
684 $fields = array_merge($fields, $note);
685 $fields = array_merge($fields, $optionFields);
686 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
687 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
688 self
::$_importableFields = $fields;
690 return self
::$_importableFields;
696 public static function &exportableFields() {
697 if (!self
::$_exportableFields) {
698 if (!self
::$_exportableFields) {
699 self
::$_exportableFields = array();
702 $impFields = CRM_Contribute_DAO_Contribution
::export();
703 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
704 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
705 $typeField = CRM_Financial_DAO_FinancialType
::export();
706 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
707 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
708 $contributionStatus = array(
709 'contribution_status' => array(
710 'title' => ts('Contribution Status'),
711 'name' => 'contribution_status',
712 'data_type' => CRM_Utils_Type
::T_STRING
,
716 $contributionPage = array(
717 'contribution_page' => array(
718 'title' => ts('Contribution Page'),
719 'name' => 'contribution_page',
720 'where' => 'civicrm_contribution_page.title',
721 'data_type' => CRM_Utils_Type
::T_STRING
,
725 $contributionNote = array(
726 'contribution_note' => array(
727 'title' => ts('Contribution Note'),
728 'name' => 'contribution_note',
729 'data_type' => CRM_Utils_Type
::T_TEXT
,
733 $contributionRecurId = array(
734 'contribution_recur_id' => array(
735 'title' => ts('Recurring Contributions ID'),
736 'name' => 'contribution_recur_id',
737 'where' => 'civicrm_contribution.contribution_recur_id',
738 'data_type' => CRM_Utils_Type
::T_INT
,
742 $extraFields = array(
743 'contribution_batch' => array(
744 'title' => ts('Batch Name'),
748 $softCreditFields = array(
749 'contribution_soft_credit_name' => array(
750 'name' => 'contribution_soft_credit_name',
751 'title' => 'Soft Credit For',
752 'where' => 'civicrm_contact_d.display_name',
753 'data_type' => CRM_Utils_Type
::T_STRING
,
755 'contribution_soft_credit_amount' => array(
756 'name' => 'contribution_soft_credit_amount',
757 'title' => 'Soft Credit Amount',
758 'where' => 'civicrm_contribution_soft.amount',
759 'data_type' => CRM_Utils_Type
::T_MONEY
,
761 'contribution_soft_credit_type' => array(
762 'name' => 'contribution_soft_credit_type',
763 'title' => 'Soft Credit Type',
764 'where' => 'contribution_softcredit_type.label',
765 'data_type' => CRM_Utils_Type
::T_STRING
,
767 'contribution_soft_credit_contribution_id' => array(
768 'name' => 'contribution_soft_credit_contribution_id',
769 'title' => 'Soft Credit For Contribution ID',
770 'where' => 'civicrm_contribution_soft.contribution_id',
771 'data_type' => CRM_Utils_Type
::T_INT
,
775 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
777 'contribution_product_id' => array(
778 'title' => ts('Premium'),
779 'name' => 'contribution_product_id',
780 'where' => 'civicrm_product.id',
781 'data_type' => CRM_Utils_Type
::T_INT
,
785 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
786 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
787 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
790 self
::$_exportableFields = $fields;
793 return self
::$_exportableFields;
797 * @param null $status
798 * @param null $startDate
799 * @param null $endDate
803 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
807 $where[] = 'contribution_status_id = 1';
811 $where[] = 'contribution_status_id = 3';
816 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
819 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
822 $whereCond = implode(' AND ', $where);
825 SELECT sum( total_amount ) as total_amount,
826 count( civicrm_contribution.id ) as total_count,
828 FROM civicrm_contribution
829 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
831 AND ( is_test = 0 OR is_test IS NULL )
832 AND contact.is_deleted = 0
836 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
839 while ($dao->fetch()) {
840 $count +
= $dao->total_count
;
841 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
845 'amount' => implode(', ', $amount),
853 * Delete the indirect records associated with this contribution first.
858 * $results no of deleted Contribution on success, false otherwise
860 public static function deleteContribution($id) {
861 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
863 $transaction = new CRM_Core_Transaction();
866 //delete activity record
868 'source_record_id' => $id,
869 // activity type id for contribution
870 'activity_type_id' => 6,
873 CRM_Activity_BAO_Activity
::deleteActivity($params);
875 //delete billing address if exists for this contribution.
876 self
::deleteAddress($id);
878 //update pledge and pledge payment, CRM-3961
879 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
881 // remove entry from civicrm_price_set_entity, CRM-5095
882 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
883 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
885 // cleanup line items.
886 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
888 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
889 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
891 if ($participantId) {
892 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
895 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
899 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
900 $noteId = key($note);
902 CRM_Core_BAO_Note
::del($noteId, FALSE);
905 $dao = new CRM_Contribute_DAO_Contribution();
908 $results = $dao->delete();
910 $transaction->commit();
912 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
914 // delete the recently created Contribution
915 $contributionRecent = array(
917 'type' => 'Contribution',
919 CRM_Utils_Recent
::del($contributionRecent);
925 * React to a financial transaction (payment) failure.
927 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
928 * payments is important for forensic and outreach reasons.
930 * @param int $contributionID
931 * @param string $message
933 public static function failPayment($contributionID, $contactID, $message) {
934 civicrm_api3('activity', 'create', array(
935 'activity_type_id' => 'Failed Payment',
936 'details' => $message,
937 'subject' => ts('Payment failed at payment processor'),
938 'source_record_id' => $contributionID,
939 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
945 * Check if there is a contribution with the same trxn_id or invoice_id.
947 * @param array $input
948 * An assoc array of name/value pairs.
949 * @param array $duplicates
950 * (reference) store ids of duplicate contribs.
954 * true if duplicate, false otherwise
956 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
958 $id = CRM_Utils_Array
::value('id', $input);
960 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
961 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
967 $clause[] = "trxn_id = %1";
968 $input[1] = array($trxn_id, 'String');
972 $clause[] = "invoice_id = %2";
973 $input[2] = array($invoice_id, 'String');
976 if (empty($clause)) {
980 $clause = implode(' OR ', $clause);
982 $clause = "( $clause ) AND id != %3";
983 $input[3] = array($id, 'Integer');
986 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
987 $dao = CRM_Core_DAO
::executeQuery($query, $input);
989 while ($dao->fetch()) {
990 $duplicates[] = $dao->id
;
997 * Takes an associative array and creates a contribution_product object.
999 * the function extract all the params it needs to initialize the create a
1000 * contribution_product object. the params array could contain additional unused name/value
1003 * @param array $params
1004 * (reference) an assoc array of name/value pairs.
1006 * @return CRM_Contribute_DAO_ContributionProduct
1008 public static function addPremium(&$params) {
1009 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1010 $contributionProduct->copyValues($params);
1011 return $contributionProduct->save();
1015 * Get list of contribution fields for profile.
1016 * For now we only allow custom contribution fields to be in
1019 * @param bool $addExtraFields
1020 * True if special fields needs to be added.
1023 * the list of contribution fields
1025 public static function getContributionFields($addExtraFields = TRUE) {
1026 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1027 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1029 if ($addExtraFields) {
1030 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1033 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1035 foreach ($contributionFields as $key => $var) {
1036 if ($key == 'contribution_contact_id') {
1039 elseif ($key == 'contribution_campaign_id') {
1040 $var['title'] = ts('Campaign');
1042 $fields[$key] = $var;
1045 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1050 * Add extra fields specific to contribution.
1052 public static function getSpecialContributionFields() {
1053 $extraFields = array(
1054 'contribution_soft_credit_name' => array(
1055 'name' => 'contribution_soft_credit_name',
1056 'title' => 'Soft Credit Name',
1057 'headerPattern' => '/^soft_credit_name$/i',
1058 'where' => 'civicrm_contact_d.display_name',
1060 'contribution_soft_credit_email' => array(
1061 'name' => 'contribution_soft_credit_email',
1062 'title' => 'Soft Credit Email',
1063 'headerPattern' => '/^soft_credit_email$/i',
1064 'where' => 'soft_email.email',
1066 'contribution_soft_credit_phone' => array(
1067 'name' => 'contribution_soft_credit_phone',
1068 'title' => 'Soft Credit Phone',
1069 'headerPattern' => '/^soft_credit_phone$/i',
1070 'where' => 'soft_phone.phone',
1072 'contribution_soft_credit_contact_id' => array(
1073 'name' => 'contribution_soft_credit_contact_id',
1074 'title' => 'Soft Credit Contact ID',
1075 'headerPattern' => '/^soft_credit_contact_id$/i',
1076 'where' => 'civicrm_contribution_soft.contact_id',
1080 return $extraFields;
1084 * @param int $pageID
1088 public static function getCurrentandGoalAmount($pageID) {
1090 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1091 FROM civicrm_contribution_page p,
1092 civicrm_contribution c
1093 WHERE p.id = c.contribution_page_id
1095 AND c.cancel_date is null
1099 $config = CRM_Core_Config
::singleton();
1100 $params = array(1 => array($pageID, 'Integer'));
1101 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1103 if ($dao->fetch()) {
1104 return array($dao->goal
, $dao->total
);
1107 return array(NULL, NULL);
1112 * Get list of contribution In Honor of contact Ids.
1114 * @param int $honorId
1115 * In Honor of Contact ID.
1118 * list of contribution fields
1120 public static function getHonorContacts($honorId) {
1122 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1123 $honorDAO->contact_id
= $honorId;
1126 $type = CRM_Contribute_PseudoConstant
::financialType();
1128 while ($honorDAO->fetch()) {
1129 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1130 $contributionDAO->id
= $honorDAO->contribution_id
;
1132 if ($contributionDAO->find(TRUE)) {
1133 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1134 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1135 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1136 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1137 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1138 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1139 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1140 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1141 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1149 * Get the sort name of a contact for a particular contribution.
1152 * Id of the contribution.
1154 * @return null|string
1155 * sort name of the contact if found
1157 public static function sortName($id) {
1158 $id = CRM_Utils_Type
::escape($id, 'Integer');
1161 SELECT civicrm_contact.sort_name
1162 FROM civicrm_contribution, civicrm_contact
1163 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1164 AND civicrm_contribution.id = {$id}
1166 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1170 * @param int $contactID
1174 public static function annual($contactID) {
1175 if (is_array($contactID)) {
1176 $contactIDs = implode(',', $contactID);
1179 $contactIDs = $contactID;
1182 $config = CRM_Core_Config
::singleton();
1183 $startDate = $endDate = NULL;
1185 $currentMonth = date('m');
1186 $currentDay = date('d');
1187 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1188 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1189 (int ) $config->fiscalYearStart
['d'] > $currentDay
1192 $year = date('Y') - 1;
1197 $nextYear = $year +
1;
1199 if ($config->fiscalYearStart
) {
1200 if ($config->fiscalYearStart
['M'] < 10) {
1201 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1203 if ($config->fiscalYearStart
['d'] < 10) {
1204 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1206 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1211 $startDate = "$year$monthDay";
1212 $endDate = "$nextYear$monthDay";
1215 SELECT count(*) as count,
1216 sum(total_amount) as amount,
1217 avg(total_amount) as average,
1219 FROM civicrm_contribution b
1220 WHERE b.contact_id IN ( $contactIDs )
1221 AND b.contribution_status_id = 1
1223 AND b.receive_date >= $startDate
1224 AND b.receive_date < $endDate
1227 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1229 $amount = $average = array();
1230 while ($dao->fetch()) {
1231 if ($dao->count
> 0 && $dao->amount
> 0) {
1232 $count +
= $dao->count
;
1233 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1234 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1240 implode(', ', $amount),
1241 implode(', ', $average),
1244 return array(0, 0, 0);
1248 * Check if there is a contribution with the params passed in.
1250 * Used for trxn_id,invoice_id and contribution_id
1252 * @param array $params
1253 * An assoc array of name/value pairs.
1256 * contribution id if success else NULL
1258 public static function checkDuplicateIds($params) {
1259 $dao = new CRM_Contribute_DAO_Contribution();
1263 foreach ($params as $k => $v) {
1265 $clause[] = "$k = '$v'";
1268 $clause = implode(' AND ', $clause);
1269 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1270 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1272 while ($dao->fetch()) {
1280 * Get the contribution details for component export.
1282 * @param int $exportMode
1284 * @param string $componentIds
1290 public static function getContributionDetails($exportMode, $componentIds) {
1291 $paymentDetails = array();
1292 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1294 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1295 $componentSelect = " civicrm_participant_payment.participant_id id";
1296 $additionalClause = "
1297 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1298 AND civicrm_participant_payment.participant_id {$componentClause} )
1301 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1302 $componentSelect = " civicrm_membership_payment.membership_id id";
1303 $additionalClause = "
1304 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1305 AND civicrm_membership_payment.membership_id {$componentClause} )
1308 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1309 $componentSelect = " civicrm_pledge_payment.id id";
1310 $additionalClause = "
1311 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1312 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1316 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1317 trxn_id, {$componentSelect}
1318 FROM civicrm_contribution
1319 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1320 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1321 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1322 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1323 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1324 AND option_group_contribution_status.id = contribution_status.option_group_id )
1328 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1330 while ($dao->fetch()) {
1331 $paymentDetails[$dao->id
] = array(
1332 'total_amount' => $dao->total_amount
,
1333 'contribution_status' => $dao->status
,
1334 'receive_date' => $dao->receive_date
,
1335 'pay_instru' => $dao->payment_instrument
,
1336 'trxn_id' => $dao->trxn_id
,
1340 return $paymentDetails;
1344 * Create address associated with contribution record.
1346 * As long as there is one or more billing field in the parameters we will create the address.
1348 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1351 * @param array $params
1352 * @param int $billingLocationTypeID
1357 public static function createAddress($params, $billingLocationTypeID) {
1358 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1359 if ($hasBillingField) {
1360 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1361 return $address->id
;
1368 * Delete billing address record related contribution.
1370 * @param int $contributionId
1371 * @param int $contactId
1373 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1375 $contactJoin = NULL;
1377 if ($contributionId) {
1378 $clauses[] = "cc.id = {$contributionId}";
1382 $clauses[] = "cco.id = {$contactId}";
1383 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1386 if (empty($clauses)) {
1387 CRM_Core_Error
::fatal();
1390 $condition = implode(' OR ', $clauses);
1394 FROM civicrm_address ca
1395 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1399 $dao = CRM_Core_DAO
::executeQuery($query);
1401 while ($dao->fetch()) {
1402 $params = array('id' => $dao->id
);
1403 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1408 * This function check online pending contribution associated w/
1409 * Online Event Registration or Online Membership signup.
1411 * @param int $componentId
1412 * Participant/membership id.
1413 * @param string $componentName
1417 * pending contribution id.
1419 public static function checkOnlinePendingContribution($componentId, $componentName) {
1420 $contributionId = NULL;
1421 if (!$componentId ||
1422 !in_array($componentName, array('Event', 'Membership'))
1424 return $contributionId;
1427 if ($componentName == 'Event') {
1428 $idName = 'participant_id';
1429 $componentTable = 'civicrm_participant';
1430 $paymentTable = 'civicrm_participant_payment';
1431 $source = ts('Online Event Registration');
1434 if ($componentName == 'Membership') {
1435 $idName = 'membership_id';
1436 $componentTable = 'civicrm_membership';
1437 $paymentTable = 'civicrm_membership_payment';
1438 $source = ts('Online Contribution');
1441 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1444 SELECT component.id as {$idName},
1445 componentPayment.contribution_id as contribution_id,
1446 contribution.source source,
1447 contribution.contribution_status_id as contribution_status_id,
1448 contribution.is_pay_later as is_pay_later
1449 FROM $componentTable component
1450 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1451 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1452 WHERE component.id = {$componentId}";
1454 $dao = CRM_Core_DAO
::executeQuery($query);
1456 while ($dao->fetch()) {
1457 if ($dao->contribution_id
&&
1458 $dao->is_pay_later
&&
1459 $dao->contribution_status_id
== $pendingStatusId &&
1460 strpos($dao->source
, $source) !== FALSE
1462 $contributionId = $dao->contribution_id
;
1467 return $contributionId;
1471 * Update contribution as well as related objects.
1473 * @param array $params
1474 * @param bool $processContributionObject
1477 * @throws \Exception
1479 public static function transitionComponents($params, $processContributionObject = FALSE) {
1480 // get minimum required values.
1481 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1482 $componentId = CRM_Utils_Array
::value('component_id', $params);
1483 $componentName = CRM_Utils_Array
::value('componentName', $params);
1484 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1485 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1487 // if we already processed contribution object pass previous status id.
1488 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1490 $updateResult = array();
1492 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1494 // we process only ( Completed, Cancelled, or Failed ) contributions.
1495 if (!$contributionId ||
1496 !in_array($contributionStatusId, array(
1497 array_search('Completed', $contributionStatuses),
1498 array_search('Cancelled', $contributionStatuses),
1499 array_search('Failed', $contributionStatuses),
1502 return $updateResult;
1505 if (!$componentName ||
!$componentId) {
1506 // get the related component details.
1507 $componentDetails = self
::getComponentDetails($contributionId);
1510 $componentDetails['contact_id'] = $contactId;
1511 $componentDetails['component'] = $componentName;
1513 if ($componentName == 'event') {
1514 $componentDetails['participant'] = $componentId;
1517 $componentDetails['membership'] = $componentId;
1521 if (!empty($componentDetails['contact_id'])) {
1522 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1528 // do check for required ids.
1529 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1530 return $updateResult;
1533 //now we are ready w/ required ids, start processing.
1535 $baseIPN = new CRM_Core_Payment_BaseIPN();
1537 $input = $ids = $objects = array();
1539 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1540 $ids['contribution'] = $contributionId;
1541 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1542 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1543 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1544 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1545 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1546 $ids['contributionRecur'] = NULL;
1547 $ids['contributionPage'] = NULL;
1549 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1550 CRM_Core_Error
::fatal();
1553 $memberships = &$objects['membership'];
1554 $participant = &$objects['participant'];
1555 $pledgePayment = &$objects['pledge_payment'];
1556 $contribution = &$objects['contribution'];
1558 if ($pledgePayment) {
1559 $pledgePaymentIDs = array();
1560 foreach ($pledgePayment as $key => $object) {
1561 $pledgePaymentIDs[] = $object->id
;
1563 $pledgeID = $pledgePayment[0]->pledge_id
;
1566 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1569 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1570 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1575 // we might want to process contribution object.
1576 $processContribution = FALSE;
1577 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1578 if (is_array($memberships)) {
1579 foreach ($memberships as $membership) {
1581 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1582 $membership->save();
1584 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1585 if ($processContributionObject) {
1586 $processContribution = TRUE;
1593 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1594 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1596 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1597 if ($processContributionObject) {
1598 $processContribution = TRUE;
1602 if ($pledgePayment) {
1603 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1605 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1606 if ($processContributionObject) {
1607 $processContribution = TRUE;
1611 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1612 if (is_array($memberships)) {
1613 foreach ($memberships as $membership) {
1615 $membership->status_id
= array_search('Expired', $membershipStatuses);
1616 $membership->save();
1618 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1619 if ($processContributionObject) {
1620 $processContribution = TRUE;
1626 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1627 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1629 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1630 if ($processContributionObject) {
1631 $processContribution = TRUE;
1635 if ($pledgePayment) {
1636 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1638 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1639 if ($processContributionObject) {
1640 $processContribution = TRUE;
1644 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1646 // only pending contribution related object processed.
1647 if ($previousContriStatusId &&
1648 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1650 // this is case when we already processed contribution object.
1651 return $updateResult;
1653 elseif (!$previousContriStatusId &&
1654 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1656 // this is case when we are going to process contribution object later.
1657 return $updateResult;
1660 if (is_array($memberships)) {
1661 foreach ($memberships as $membership) {
1666 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1667 $membership->membership_type_id
,
1668 $membership->is_test
, $membership->id
1671 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1672 // this picks up membership type changes during renewals
1674 SELECT membership_type_id
1675 FROM civicrm_membership_log
1676 WHERE membership_id=$membership->id
1679 $dao = new CRM_Core_DAO();
1681 if ($dao->fetch()) {
1682 if (!empty($dao->membership_type_id
)) {
1683 $membership->membership_type_id
= $dao->membership_type_id
;
1684 $membership->save();
1687 // else fall back to using current membership type
1690 // Figure out number of terms
1692 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1693 foreach ($lineitems as $lineitem) {
1694 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1695 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1697 // in case membership_num_terms comes through as null or zero
1698 $numterms = $numterms >= 1 ?
$numterms : 1;
1703 // CRM-15735-to update the membership status as per the contribution receive date
1705 if (!empty($params['receive_date'])) {
1706 $joinDate = $params['receive_date'];
1707 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1708 $membership->end_date
,
1709 $membership->join_date
,
1710 $params['receive_date'],
1712 $membership->membership_type_id
,
1715 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1716 $membership->save();
1719 if ($currentMembership) {
1720 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1721 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1722 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1725 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1728 //get the status for membership.
1729 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1731 $dates['join_date'],
1734 $membership->membership_type_id
,
1738 $formattedParams = array(
1739 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1740 array_search('Current', $membershipStatuses)
1742 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1743 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1744 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1747 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1749 $membership->copyValues($formattedParams);
1750 $membership->save();
1752 //updating the membership log
1753 $membershipLog = array();
1754 $membershipLog = $formattedParams;
1755 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1756 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1758 $membershipLog['start_date'] = $logStartDate;
1759 $membershipLog['membership_id'] = $membership->id
;
1760 $membershipLog['modified_id'] = $membership->contact_id
;
1761 $membershipLog['modified_date'] = date('Ymd');
1762 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1764 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1766 //update related Memberships.
1767 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1769 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1772 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1773 if ($processContributionObject) {
1774 $processContribution = TRUE;
1777 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1783 $updatedStatusId = array_search('Registered', $participantStatuses);
1784 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1786 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1787 if ($processContributionObject) {
1788 $processContribution = TRUE;
1792 if ($pledgePayment) {
1793 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1795 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1796 if ($processContributionObject) {
1797 $processContribution = TRUE;
1802 // process contribution object.
1803 if ($processContribution) {
1804 $contributionParams = array();
1811 'payment_instrument_id',
1814 'financial_type_id',
1815 'contribution_status_id',
1816 'non_deductible_amount',
1820 foreach ($fields as $field) {
1821 if (empty($params[$field])) {
1824 $contributionParams[$field] = $params[$field];
1827 $ids = array('contribution' => $contributionId);
1828 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1831 return $updateResult;
1835 * Returns all contribution related object ids.
1837 * @param $contributionId
1841 public static function getComponentDetails($contributionId) {
1842 $componentDetails = $pledgePayment = array();
1843 if (!$contributionId) {
1844 return $componentDetails;
1848 SELECT c.id as contribution_id,
1849 c.contact_id as contact_id,
1850 c.contribution_recur_id,
1851 mp.membership_id as membership_id,
1852 m.membership_type_id as membership_type_id,
1853 pp.participant_id as participant_id,
1854 p.event_id as event_id,
1855 pgp.id as pledge_payment_id
1856 FROM civicrm_contribution c
1857 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1858 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1859 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1860 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1861 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1862 WHERE c.id = $contributionId";
1864 $dao = CRM_Core_DAO
::executeQuery($query);
1865 $componentDetails = array();
1867 while ($dao->fetch()) {
1868 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1869 $componentDetails['contact_id'] = $dao->contact_id
;
1870 if ($dao->event_id
) {
1871 $componentDetails['event'] = $dao->event_id
;
1873 if ($dao->participant_id
) {
1874 $componentDetails['participant'] = $dao->participant_id
;
1876 if ($dao->membership_id
) {
1877 if (!isset($componentDetails['membership'])) {
1878 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1880 $componentDetails['membership'][] = $dao->membership_id
;
1881 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1883 if ($dao->pledge_payment_id
) {
1884 $pledgePayment[] = $dao->pledge_payment_id
;
1886 if ($dao->contribution_recur_id
) {
1887 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1891 if ($pledgePayment) {
1892 $componentDetails['pledge_payment'] = $pledgePayment;
1895 return $componentDetails;
1899 * @param int $contactId
1900 * @param bool $includeSoftCredit
1902 * @return null|string
1904 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1909 $contactContributionsSQL = "
1910 SELECT contribution.id AS id
1911 FROM civicrm_contribution contribution
1912 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1914 $contactSoftCreditContributionsSQL = "
1915 SELECT contribution.id
1916 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1917 ON ( contribution.id = softContribution.contribution_id )
1918 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1919 $query = "SELECT count( x.id ) count FROM ( ";
1920 $query .= $contactContributionsSQL;
1922 if ($includeSoftCredit) {
1923 $query .= " UNION ";
1924 $query .= $contactSoftCreditContributionsSQL;
1929 return CRM_Core_DAO
::singleValueQuery($query);
1933 * Get individual id for onbehalf contribution.
1935 * @param int $contributionId
1937 * @param int $contributorId
1941 * containing organization id and individual id
1943 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1947 if (!$contributionId) {
1951 // fetch contributor id if null
1952 if (!$contributorId) {
1953 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1954 $contributionId, 'contact_id'
1958 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1959 $activityTypeId = array_search('Contribution', $activityTypeIds);
1961 if ($activityTypeId && $contributorId) {
1963 SELECT civicrm_activity_contact.contact_id
1964 FROM civicrm_activity_contact
1965 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1966 WHERE civicrm_activity.activity_type_id = %1
1967 AND civicrm_activity.source_record_id = %2
1968 AND civicrm_activity_contact.record_type_id = %3
1971 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1972 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1975 1 => array($activityTypeId, 'Integer'),
1976 2 => array($contributionId, 'Integer'),
1977 3 => array($sourceID, 'Integer'),
1980 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1982 // for on behalf contribution source is individual and contributor is organization
1983 if ($sourceContactId && $sourceContactId != $contributorId) {
1984 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1985 // get rel type id for employee of relation
1986 foreach ($relationshipTypeIds as $id => $typeVals) {
1987 if ($typeVals['name_a_b'] == 'Employee of') {
1988 $relationshipTypeId = $id;
1993 $rel = new CRM_Contact_DAO_Relationship();
1994 $rel->relationship_type_id
= $relationshipTypeId;
1995 $rel->contact_id_a
= $sourceContactId;
1996 $rel->contact_id_b
= $contributorId;
1997 if ($rel->find(TRUE)) {
1998 $ids['individual_id'] = $rel->contact_id_a
;
1999 $ids['organization_id'] = $rel->contact_id_b
;
2010 public static function getContributionDates() {
2011 $config = CRM_Core_Config
::singleton();
2012 $currentMonth = date('m');
2013 $currentDay = date('d');
2014 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2015 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2016 (int ) $config->fiscalYearStart
['d'] > $currentDay
2019 $year = date('Y') - 1;
2024 $year = array('Y' => $year);
2025 $yearDate = $config->fiscalYearStart
;
2026 $yearDate = array_merge($year, $yearDate);
2027 $yearDate = CRM_Utils_Date
::format($yearDate);
2029 $monthDate = date('Ym') . '01';
2035 'yearDate' => $yearDate,
2036 'monthDate' => $monthDate,
2041 * Load objects relations to contribution object.
2042 * Objects are stored in the $_relatedObjects property
2043 * In the first instance we are just moving functionality from BASEIpn -
2044 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2046 * Note that the unit test for the BaseIPN class tests this function
2048 * @param array $input
2049 * Input as delivered from Payment Processor.
2051 * Ids as Loaded by Payment Processor.
2052 * @param bool $required
2053 * Is Payment processor / contribution page required.
2054 * @param bool $loadAll
2055 * Load all related objects - even where id not passed in? (allows API to call this).
2060 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
2062 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2063 if (empty($ids['contact']) && isset($this->contact_id
)) {
2064 $ids['contact'] = $this->contact_id
;
2067 if (empty($this->_component
)) {
2068 if (!empty($ids['event'])) {
2069 $this->_component
= 'event';
2072 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2075 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2076 $contributionType = new CRM_Financial_BAO_FinancialType();
2077 $contributionType->id
= $this->financial_type_id
;
2078 $contributionType->find(TRUE);
2080 if (!empty($ids['contact'])) {
2081 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2082 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2083 $this->_relatedObjects
['contact']->find(TRUE);
2085 $this->_relatedObjects
['contributionType'] = $contributionType;
2087 if ($this->_component
== 'contribute') {
2088 // retrieve the other optional objects first so
2089 // stuff down the line can use this info and do things
2091 //in any case get the memberships associated with the contribution
2092 //because we now support multiple memberships w/ price set
2093 // see if there are any other memberships to be considered for same contribution.
2095 SELECT membership_id
2096 FROM civicrm_membership_payment
2097 WHERE contribution_id = %1 ";
2098 $params = array(1 => array($this->id
, 'Integer'));
2100 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2101 while ($dao->fetch()) {
2102 if ($dao->membership_id
) {
2103 if (!is_array($ids['membership'])) {
2104 $ids['membership'] = array();
2106 $ids['membership'][] = $dao->membership_id
;
2110 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2111 foreach ($ids['membership'] as $id) {
2113 $membership = new CRM_Member_BAO_Membership();
2114 $membership->id
= $id;
2115 if (!$membership->find(TRUE)) {
2116 throw new Exception("Could not find membership record: $id");
2118 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2119 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2120 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2121 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2122 $membership->free();
2127 if (!empty($ids['pledge_payment'])) {
2129 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2130 if (empty($paymentID)) {
2133 $payment = new CRM_Pledge_BAO_PledgePayment();
2134 $payment->id
= $paymentID;
2135 if (!$payment->find(TRUE)) {
2136 throw new Exception("Could not find pledge payment record: " . $paymentID);
2138 $this->_relatedObjects
['pledge_payment'][] = $payment;
2142 if (!empty($ids['contributionRecur'])) {
2143 $recur = new CRM_Contribute_BAO_ContributionRecur();
2144 $recur->id
= $ids['contributionRecur'];
2145 if (!$recur->find(TRUE)) {
2146 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2148 $this->_relatedObjects
['contributionRecur'] = &$recur;
2149 //get payment processor id from recur object.
2150 $paymentProcessorID = $recur->payment_processor_id
;
2152 //for normal contribution get the payment processor id.
2153 if (!$paymentProcessorID) {
2154 if ($this->contribution_page_id
) {
2155 // get the payment processor id from contribution page
2156 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2157 $this->contribution_page_id
,
2161 //fail to load payment processor id.
2162 elseif (empty($ids['pledge_payment'])) {
2163 $loadObjectSuccess = TRUE;
2165 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2167 return $loadObjectSuccess;
2172 // we are in event mode
2173 // make sure event exists and is valid
2174 $event = new CRM_Event_BAO_Event();
2175 $event->id
= $ids['event'];
2176 if ($ids['event'] &&
2179 throw new Exception("Could not find event: " . $ids['event']);
2182 $this->_relatedObjects
['event'] = &$event;
2184 $participant = new CRM_Event_BAO_Participant();
2185 $participant->id
= $ids['participant'];
2186 if ($ids['participant'] &&
2187 !$participant->find(TRUE)
2189 throw new Exception("Could not find participant: " . $ids['participant']);
2191 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2193 $this->_relatedObjects
['participant'] = &$participant;
2195 if (!$paymentProcessorID) {
2196 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2200 if ($paymentProcessorID) {
2201 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2202 $this->is_test ?
'test' : 'live'
2204 $ids['paymentProcessor'] = $paymentProcessorID;
2205 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2207 elseif ($required) {
2208 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2215 * Create array of message information - ie. return html version, txt version, to field
2217 * @param array $input
2218 * Incoming information.
2219 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2220 * just check presence of recur object but maintaining legacy approach
2223 * IDs of related objects.
2224 * @param array $values
2225 * Any values that may have already been compiled by calling process.
2226 * This is augmented by values 'gathered' by gatherMessageValues
2227 * @param bool $recur
2228 * @param bool $returnMessageText
2229 * Distinguishes between whether to send message or return.
2230 * message text. We are working towards this function ALWAYS returning message text & calling
2231 * function doing emails / pdfs with it
2237 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2238 if (empty($this->_relatedObjects
)) {
2239 $this->loadRelatedObjects($input, $ids);
2241 if (empty($this->_component
)) {
2242 $this->_component
= CRM_Utils_Array
::value('component', $input);
2245 //not really sure what params might be passed in but lets merge em into values
2246 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2247 $template = CRM_Core_Smarty
::singleton();
2248 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2249 //what does recur 'mean here - to do with payment processor return functionality but
2250 // what is the importance
2251 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2252 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2254 $entityID = $entity = NULL;
2255 if (isset($ids['contribution'])) {
2256 $entity = 'contribution';
2257 $entityID = $ids['contribution'];
2259 if (!empty($ids['membership'])) {
2260 //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
2261 // 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
2262 // line having loaded an array
2263 $ids['membership'] = (array) $ids['membership'];
2264 $entity = 'membership';
2265 $entityID = $ids['membership'][0];
2268 $url = $paymentObject->subscriptionURL($entityID, $entity);
2269 $template->assign('cancelSubscriptionUrl', $url);
2271 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2272 $template->assign('updateSubscriptionBillingUrl', $url);
2274 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2275 $template->assign('updateSubscriptionUrl', $url);
2277 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2278 //direct mode showing billing block, so use directIPN for temporary
2279 $template->assign('contributeMode', 'directIPN');
2282 // todo remove strtolower - check consistency
2283 if (strtolower($this->_component
) == 'event') {
2284 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2285 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2289 $values['contribution_id'] = $this->id
;
2290 if (!empty($ids['related_contact'])) {
2291 $values['related_contact'] = $ids['related_contact'];
2292 if (isset($ids['onbehalf_dupe_alert'])) {
2293 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2295 $entityBlock = array(
2296 'contact_id' => $ids['contact'],
2297 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2298 'Home', 'id', 'name'
2301 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2302 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2305 if ($this->is_test
) {
2308 if (!empty($this->_relatedObjects
['membership'])) {
2309 foreach ($this->_relatedObjects
['membership'] as $membership) {
2310 if ($membership->id
) {
2311 $values['isMembership'] = TRUE;
2313 // need to set the membership values here
2314 $template->assign('membership_assign', 1);
2315 $template->assign('membership_name',
2316 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2318 $template->assign('mem_start_date', $membership->start_date
);
2319 $template->assign('mem_join_date', $membership->join_date
);
2320 $template->assign('mem_end_date', $membership->end_date
);
2321 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2322 $template->assign('mem_status', $membership_status);
2323 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2324 $template->assign('is_pay_later', 1);
2327 // if separate payment there are two contributions recorded and the
2328 // admin will need to send a receipt for each of them separately.
2329 // we dont link the two in the db (but can potentially infer it if needed)
2330 $template->assign('is_separate_payment', 0);
2332 if ($recur && $paymentObject) {
2333 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2334 $template->assign('cancelSubscriptionUrl', $url);
2335 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2336 $template->assign('updateSubscriptionBillingUrl', $url);
2337 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2338 $template->assign('updateSubscriptionUrl', $url);
2341 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2344 // otherwise if its about sending emails, continue sending without return, as we
2345 // don't want to exit the loop.
2350 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2356 * Gather values for contribution mail - this function has been created
2357 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2358 * Values related to the contribution in question are gathered
2360 * @param array $input
2361 * Input into function (probably from payment processor).
2362 * @param array $values
2364 * The set of ids related to the input.
2368 public function _gatherMessageValues($input, &$values, $ids = array()) {
2369 // set display address of contributor
2370 if ($this->address_id
) {
2371 $addressParams = array('id' => $this->address_id
);
2372 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2373 $addressDetails = array_values($addressDetails);
2374 $values['address'] = $addressDetails[0]['display'];
2376 if ($this->_component
== 'contribute') {
2377 if (isset($this->contribution_page_id
)) {
2378 CRM_Contribute_BAO_ContributionPage
::setValues(
2379 $this->contribution_page_id
,
2382 if ($this->contribution_page_id
) {
2383 // CRM-8254 - override default currency if applicable
2384 $config = CRM_Core_Config
::singleton();
2385 $config->defaultCurrency
= CRM_Utils_Array
::value(
2388 $config->defaultCurrency
2392 // no contribution page -probably back office
2394 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2395 $values['is_email_receipt'] = 1;
2396 $values['title'] = 'Contribution';
2398 // set lineItem for contribution
2400 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2401 if (!empty($lineItem)) {
2402 $itemId = key($lineItem);
2403 foreach ($lineItem as &$eachItem) {
2404 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2405 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2406 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2407 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2410 $values['lineItem'][0] = $lineItem;
2411 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2415 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2419 // if this is onbehalf of contribution then set related contact
2420 if (!empty($relatedContact['individual_id'])) {
2421 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2426 $eventParams = array(
2427 'id' => $this->_relatedObjects
['event']->id
,
2429 $values['event'] = array();
2431 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2433 //get location details
2434 $locationParams = array(
2435 'entity_id' => $this->_relatedObjects
['event']->id
,
2436 'entity_table' => 'civicrm_event',
2438 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2440 $ufJoinParams = array(
2441 'entity_table' => 'civicrm_event',
2442 'entity_id' => $ids['event'],
2443 'module' => 'CiviEvent',
2446 list($custom_pre_id,
2448 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2450 $values['custom_pre_id'] = $custom_pre_id;
2451 $values['custom_post_id'] = $custom_post_ids;
2453 // set lineItem for event contribution
2455 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2456 if (!empty($participantIds)) {
2457 foreach ($participantIds as $pIDs) {
2458 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2459 if (!CRM_Utils_System
::isNull($lineItem)) {
2460 $values['lineItem'][] = $lineItem;
2471 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2472 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2473 * Note we send directly from this function in some cases because it is only partly refactored
2474 * Don't call this function directly as the signature will change
2478 * @param CRM_Core_SMARTY $template
2479 * @param bool $recur
2480 * @param bool $returnMessageText
2484 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2485 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2486 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2487 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2488 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2489 $template->assign('useForMember', TRUE);
2491 //assign honor information to receipt message
2492 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2494 if (isset($softRecord['soft_credit'])) {
2495 //if id of contribution page is present
2496 if (!empty($values['id'])) {
2497 $values['honor'] = array(
2498 'honor_profile_values' => array(),
2499 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2500 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2502 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2504 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2505 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2508 //offline contribution
2509 $softCreditTypes = $softCredits = array();
2510 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2511 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2512 $softCredits[$key] = array(
2513 'Name' => $softCredit['contact_name'],
2514 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2517 $template->assign('softCreditTypes', $softCreditTypes);
2518 $template->assign('softCredits', $softCredits);
2522 $dao = new CRM_Contribute_DAO_ContributionProduct();
2523 $dao->contribution_id
= $this->id
;
2524 if ($dao->find(TRUE)) {
2525 $premiumId = $dao->product_id
;
2526 $template->assign('option', $dao->product_option
);
2528 $productDAO = new CRM_Contribute_DAO_Product();
2529 $productDAO->id
= $premiumId;
2530 $productDAO->find(TRUE);
2531 $template->assign('selectPremium', TRUE);
2532 $template->assign('product_name', $productDAO->name
);
2533 $template->assign('price', $productDAO->price
);
2534 $template->assign('sku', $productDAO->sku
);
2536 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2537 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2538 if (empty($amount) && isset($this->total_amount
)) {
2539 $amount = $this->total_amount
;
2541 $template->assign('amount', $amount);
2542 // add the new contribution values
2543 if (strtolower($this->_component
) == 'contribute') {
2545 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2546 $softDAO->contribution_id
= $this->id
;
2547 if ($softDAO->find(TRUE)) {
2548 $template->assign('pcpBlock', TRUE);
2549 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2550 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2551 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2553 //assign the pcp page title for email subject
2554 $pcpDAO = new CRM_PCP_DAO_PCP();
2555 $pcpDAO->id
= $softDAO->pcp_id
;
2556 if ($pcpDAO->find(TRUE)) {
2557 $template->assign('title', $pcpDAO->title
);
2562 if ($this->financial_type_id
) {
2563 $values['financial_type_id'] = $this->financial_type_id
;
2566 $template->assign('trxn_id', $this->trxn_id
);
2567 $template->assign('receive_date',
2568 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2570 $template->assign('contributeMode', 'notify');
2571 $template->assign('action', $this->is_test ?
1024 : 1);
2572 $template->assign('receipt_text',
2573 CRM_Utils_Array
::value('receipt_text',
2577 $template->assign('is_monetary', 1);
2578 $template->assign('is_recur', (bool) $recur);
2579 $template->assign('currency', $this->currency
);
2580 $template->assign('address', CRM_Utils_Address
::format($input));
2581 if ($this->_component
== 'event') {
2582 $template->assign('title', $values['event']['title']);
2583 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2584 $viewRoles = array();
2585 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2586 $viewRoles[] = $participantRoles[$v];
2588 $values['event']['participant_role'] = implode(', ', $viewRoles);
2589 $template->assign('event', $values['event']);
2590 $template->assign('location', $values['location']);
2591 $template->assign('customPre', $values['custom_pre_id']);
2592 $template->assign('customPost', $values['custom_post_id']);
2595 if ($this->_relatedObjects
['participant']->is_test
) {
2599 $values['params'] = array();
2600 //to get email of primary participant.
2601 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2602 $primaryAmount[] = array(
2603 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2604 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2606 //build an array of cId/pId of participants
2607 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2608 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2609 //send receipt to additional participant if exists
2610 if (count($additionalIDs)) {
2611 $template->assign('isPrimary', 0);
2612 $template->assign('customProfile', NULL);
2613 //set additionalParticipant true
2614 $values['params']['additionalParticipant'] = TRUE;
2615 foreach ($additionalIDs as $pId => $cId) {
2617 //to change the status pending to completed
2618 $additional = new CRM_Event_DAO_Participant();
2619 $additional->id
= $pId;
2620 $additional->contact_id
= $cId;
2621 $additional->find(TRUE);
2622 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2623 $additional->status_id
= 1;
2624 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2625 //if additional participant dont have email
2627 if (!$additionalParticipantInfo) {
2628 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2630 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2631 $primaryAmount[] = array(
2632 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2633 'amount' => $additional->fee_amount
,
2635 $additional->save();
2636 $additional->free();
2637 $template->assign('amount', $amount);
2638 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2642 //build an array of custom profile and assigning it to template
2643 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2645 if (count($customProfile)) {
2646 $template->assign('customProfile', $customProfile);
2649 // for primary contact
2650 $values['params']['additionalParticipant'] = FALSE;
2651 $template->assign('isPrimary', 1);
2652 $template->assign('amount', $primaryAmount);
2653 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2654 if ($this->payment_instrument_id
) {
2655 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2656 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2658 // carry paylater, since we did not created billing,
2659 // so need to pull email from primary location, CRM-4395
2660 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2666 * Check whether payment processor supports
2667 * cancellation of contribution subscription
2669 * @param int $contributionId
2672 * @param bool $isNotCancelled
2676 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2677 $cacheKeyString = "$contributionId";
2678 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2680 static $supportsCancel = array();
2682 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2683 $supportsCancel[$cacheKeyString] = FALSE;
2684 $isCancelled = FALSE;
2686 if ($isNotCancelled) {
2687 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2690 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2691 if (!empty($paymentObject)) {
2692 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2695 return $supportsCancel[$cacheKeyString];
2699 * Check whether subscription is already cancelled.
2701 * @param int $contributionId
2705 * contribution status
2707 public static function isSubscriptionCancelled($contributionId) {
2709 SELECT cr.contribution_status_id
2710 FROM civicrm_contribution_recur cr
2711 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2712 WHERE con.id = %1 LIMIT 1";
2713 $params = array(1 => array($contributionId, 'Integer'));
2714 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2715 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2716 if ($status == 'Cancelled') {
2723 * Create all financial accounts entry.
2725 * @param array $params
2726 * Contribution object, line item array and params for trxn.
2729 * @param array $financialTrxnValues
2731 * @return null|object
2733 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2734 $skipRecords = $update = $return = $isRelatedId = FALSE;
2736 $additionalParticipantId = array();
2737 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2739 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2740 $entityId = $params['participant_id'];
2741 $entityTable = 'civicrm_participant';
2742 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2744 elseif (!empty($params['membership_id'])) {
2745 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2746 // are created off one contribution should be handled elsewhere
2747 $entityId = $params['membership_id'];
2748 $entityTable = 'civicrm_membership';
2751 $entityId = $params['contribution']->id
;
2752 $entityTable = 'civicrm_contribution';
2755 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2756 $isRelatedId = TRUE;
2759 $entityID[] = $entityId;
2760 if (!empty($additionalParticipantId)) {
2761 $entityID +
= $additionalParticipantId;
2763 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2764 if (empty($params['prevContribution'])) {
2771 $statusId = $params['contribution']->contribution_status_id
;
2772 // CRM-13964 partial payment
2773 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2774 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2776 $partialAmtPay = $params['partial_amount_pay'];
2777 $partialAmtTotal = $params['partial_payment_total'];
2779 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2780 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2781 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2782 $params['total_amount'] = $partialAmtPay;
2784 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2785 if (empty($balanceTrxnInfo['trxn_id'])) {
2786 // create new balance transaction record
2787 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2788 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2790 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2791 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2792 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2793 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2794 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2795 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2796 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2797 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2798 $balanceTrxnParams['status_id'] = $statusId;
2799 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2800 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2801 if (!empty($params['payment_processor'])) {
2802 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2804 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2808 // build line item array if its not set in $params
2809 if (empty($params['line_item']) ||
$additionalParticipantId) {
2810 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2813 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2814 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2816 $skipRecords = TRUE;
2817 $pendingStatus = array(
2818 array_search('Pending', $contributionStatuses),
2819 array_search('In Progress', $contributionStatuses),
2821 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2822 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2823 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2825 elseif (!empty($params['payment_processor'])) {
2826 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2828 elseif (!empty($params['payment_instrument_id'])) {
2829 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2832 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2833 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2834 $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);
2837 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2838 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2839 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2842 //build financial transaction params
2843 $trxnParams = array(
2844 'contribution_id' => $params['contribution']->id
,
2845 'to_financial_account_id' => $params['to_financial_account_id'],
2846 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2847 'total_amount' => $totalAmount,
2848 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2849 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2850 'currency' => $params['contribution']->currency
,
2851 'trxn_id' => $params['contribution']->trxn_id
,
2852 'status_id' => $statusId,
2853 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2854 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2857 if (!empty($params['payment_processor'])) {
2858 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2861 if (isset($fromFinancialAccountId)) {
2862 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2865 // consider external values passed for recording transaction entry
2866 if (!empty($financialTrxnValues)) {
2867 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2870 $params['trxnParams'] = $trxnParams;
2872 if (!empty($params['prevContribution'])) {
2873 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2874 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2875 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2876 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2877 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2879 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2880 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2881 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2883 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2884 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2887 //if financial type is changed
2888 if (!empty($params['financial_type_id']) &&
2889 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2891 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2892 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2893 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2894 if ($oldFinancialAccount != $newFinancialAccount) {
2895 $params['total_amount'] = 0;
2896 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2897 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2898 $params['prevContribution']->financial_type_id
, $relationTypeId);
2901 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2902 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2903 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2906 self
::updateFinancialAccounts($params, 'changeFinancialType');
2907 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2908 $params['financial_account_id'] = $newFinancialAccount;
2909 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2910 self
::updateFinancialAccounts($params);
2911 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2915 //Update contribution status
2916 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2917 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2918 if (!empty($params['contribution_status_id']) &&
2919 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2921 //Update Financial Records
2922 self
::updateFinancialAccounts($params, 'changedStatus');
2925 // change Payment Instrument for a Completed contribution
2926 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2927 // instrument is null and now new payment instrument is added along with the payment
2928 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2929 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2930 if (array_key_exists('payment_instrument_id', $params)) {
2931 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2932 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2933 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2935 //check if status is changed from Pending to Completed
2936 // do not update payment instrument changes for Pending to Completed
2937 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2938 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2940 // for all other statuses create new financial records
2941 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2942 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2943 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2946 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2947 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2948 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2950 // for any other payment instrument changes create new financial records
2951 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2952 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2953 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2955 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2956 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2958 // another special case when check number is changed, create new financial records
2959 // create financial trxn with negative amount
2960 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2961 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2962 // create financial trxn with positive amount
2963 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2964 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2965 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2969 //if Change contribution amount
2970 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2971 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2972 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2973 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2974 if (isset($totalAmount) &&
2975 $totalAmount != $params['prevContribution']->total_amount
2977 //Update Financial Records
2978 $params['trxnParams']['from_financial_account_id'] = NULL;
2979 self
::updateFinancialAccounts($params, 'changedAmount');
2984 // records finanical trxn and entity financial trxn
2985 // also make it available as return value
2986 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2987 $params['entity_id'] = $financialTxn->id
;
2990 // record line items and financial items
2991 if (empty($params['skipLineItem'])) {
2992 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2995 // create batch entry if batch_id is passed and
2996 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
2997 if (!empty($params['batch_id']) && !empty($financialTxn)) {
2998 $entityParams = array(
2999 'batch_id' => $params['batch_id'],
3000 'entity_table' => 'civicrm_financial_trxn',
3001 'entity_id' => $financialTxn->id
,
3003 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3006 // when a fee is charged
3007 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3008 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3011 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3012 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3014 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3015 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3016 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3018 unset($params['line_item']);
3024 * Update all financial accounts entry.
3026 * @param array $params
3027 * Contribution object, line item array and params for trxn.
3029 * @param string $context
3032 * @param null $skipTrxn
3035 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3036 $itemAmount = $trxnID = NULL;
3037 //get all the statuses
3038 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3039 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3040 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3041 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3042 && $context == 'changePaymentInstrument'
3046 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3047 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3048 && $context == 'changedStatus'
3052 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3053 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3055 if ($context == 'changedStatus') {
3056 //get all the statuses
3057 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3059 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3060 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3061 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3063 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3065 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3066 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3068 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3069 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3070 $params['trxnParams']['to_financial_account_id'] = NULL;
3071 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3073 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3074 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3075 $financialTypeID, $relationTypeId);
3077 $itemAmount = $params['trxnParams']['total_amount'];
3079 elseif ($context == 'changePaymentInstrument') {
3080 if ($params['trxnParams']['total_amount'] < 0) {
3081 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3082 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3083 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3084 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3088 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3089 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3092 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3093 $params['entity_id'] = $trxn->id
;
3095 if ($context == 'changedStatus') {
3096 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3097 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3098 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3100 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3101 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3103 $entityParams = array(
3104 'entity_table' => 'civicrm_financial_item',
3105 'financial_trxn_id' => $trxn->id
,
3107 if (empty($params['line_item'])) {
3109 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3110 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3111 // & this can be removed
3114 foreach ($params['line_item'] as $fieldId => $fields) {
3115 foreach ($fields as $fieldValueId => $fieldValues) {
3117 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3118 2 => array($fieldValues['id'], 'Integer'),
3120 CRM_Core_DAO
::executeQuery($query, $fparams);
3122 1 => array($fieldValues['id'], 'Integer'),
3124 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3125 while ($financialItem->fetch()) {
3126 $entityParams['entity_id'] = $financialItem->id
;
3127 $entityParams['amount'] = $financialItem->amount
;
3128 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3135 if ($context != 'changePaymentInstrument') {
3136 $itemParams['entity_table'] = 'civicrm_line_item';
3137 $trxnIds['id'] = $params['entity_id'];
3138 foreach ($params['line_item'] as $fieldId => $fields) {
3139 foreach ($fields as $fieldValueId => $fieldValues) {
3140 $prevParams['entity_id'] = $fieldValues['id'];
3141 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3143 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3144 if ($params['contribution']->receive_date
) {
3145 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3148 $financialAccount = $prevfinancialItem->financial_account_id
;
3149 if (!empty($params['financial_account_id'])) {
3150 $financialAccount = $params['financial_account_id'];
3153 $currency = $params['prevContribution']->currency
;
3154 if ($params['contribution']->currency
) {
3155 $currency = $params['contribution']->currency
;
3158 if (!empty($params['is_quick_config'])) {
3159 $amount = $itemAmount;
3161 $amount = $params['total_amount'];
3165 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3166 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3170 $amount = $diff * $fieldValues['line_total'];
3173 $itemParams = array(
3174 'transaction_date' => $receiveDate,
3175 'contact_id' => $params['prevContribution']->contact_id
,
3176 'currency' => $currency,
3177 'amount' => $amount,
3178 'description' => $prevfinancialItem->description
,
3179 'status_id' => $prevfinancialItem->status_id
,
3180 'financial_account_id' => $financialAccount,
3181 'entity_table' => 'civicrm_line_item',
3182 'entity_id' => $fieldValues['id'],
3184 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3186 if ($fieldValues['tax_amount']) {
3187 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3188 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3189 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3190 $itemParams['description'] = $taxTerm;
3191 if ($fieldValues['financial_type_id']) {
3192 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3194 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3199 if ($context == 'changeFinancialType') {
3200 $params['skipLineItem'] = FALSE;
3201 foreach ($params['line_item'] as &$lineItems) {
3202 foreach ($lineItems as &$line) {
3203 $line['financial_type_id'] = $params['financial_type_id'];
3210 * Check status validation on update of a contribution.
3212 * @param array $values
3213 * Previous form values before submit.
3215 * @param array $fields
3216 * The input form values.
3218 * @param array $errors
3223 public static function checkStatusValidation($values, &$fields, &$errors) {
3224 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3225 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3226 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3230 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3231 $checkStatus = array(
3232 'Cancelled' => array('Completed', 'Refunded'),
3233 'Completed' => array('Cancelled', 'Refunded'),
3234 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3235 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3236 'Refunded' => array('Cancelled', 'Completed'),
3237 'Partially paid' => array('Completed'),
3240 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3241 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3242 1 => $contributionStatuses[$values['contribution_status_id']],
3243 2 => $contributionStatuses[$fields['contribution_status_id']],
3249 * Delete contribution of contact.
3253 * @param int $contactId
3257 public static function deleteContactContribution($contactId) {
3258 $contribution = new CRM_Contribute_DAO_Contribution();
3259 $contribution->contact_id
= $contactId;
3260 $contribution->find();
3261 while ($contribution->fetch()) {
3262 self
::deleteContribution($contribution->id
);
3267 * Get options for a given contribution field.
3268 * @see CRM_Core_DAO::buildOptions
3270 * @param string $fieldName
3271 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3272 * @param array $props whatever is known about this dao object.
3274 * @return array|bool
3276 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3277 $className = __CLASS__
;
3279 switch ($fieldName) {
3280 // This field is not part of this object but the api supports it
3281 case 'payment_processor':
3282 $className = 'CRM_Contribute_BAO_ContributionPage';
3283 // Filter results by contribution page
3284 if (!empty($props['contribution_page_id'])) {
3285 $page = civicrm_api('contribution_page', 'getsingle', array(
3287 'id' => ($props['contribution_page_id']),
3289 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3290 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3294 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3295 case 'honor_type_id':
3296 $className = 'CRM_Contribute_BAO_ContributionSoft';
3297 $fieldName = 'soft_credit_type_id';
3298 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3301 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3305 * Validate financial type.
3309 * @param int $financialTypeId
3310 * Financial Type id.
3312 * @param string $relationName
3314 * @return array|bool
3316 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3317 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3318 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3320 if (!$financialAccount) {
3321 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3328 * Function to record additional payment for partial and refund contributions.
3330 * @param int $contributionId
3331 * is the invoice contribution id (got created after processing participant payment).
3332 * @param array $trxnsData
3333 * to take user provided input of transaction details.
3334 * @param string $paymentType
3335 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3336 * @param int $participantId
3338 * @return null|object
3340 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3341 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3342 $getInfoOf['id'] = $contributionId;
3343 $defaults = array();
3344 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3346 if ($paymentType == 'owed') {
3347 // build params for recording financial trxn entry
3348 $params['contribution'] = $contributionDAO;
3349 $params = array_merge($defaults, $params);
3350 $params['skipLineItem'] = TRUE;
3351 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3352 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3353 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3354 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3357 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3358 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3359 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3361 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3362 if (!empty($trxnId)) {
3363 $trxnId = $trxnId['trxn_id'];
3365 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3366 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3369 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3370 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3371 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3375 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3376 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3377 FROM civicrm_financial_trxn ft
3378 LEFT JOIN civicrm_entity_financial_trxn eft
3379 ON (ft.id = eft.financial_trxn_id)
3380 WHERE eft.entity_table = 'civicrm_contribution'
3381 AND eft.entity_id = {$contributionId}
3382 AND ft.to_financial_account_id != {$toFinancialAccount}
3383 AND ft.status_id = {$statusId}
3385 $query = CRM_Core_DAO
::executeQuery($sql);
3387 $sumOfPayments = $query->sum_of_payments
;
3390 if ($contributionDAO->total_amount
== $sumOfPayments) {
3391 // update contribution status and
3392 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3393 $contributionDAO->contribution_status_id
= $statusId;
3394 $contributionDAO->cancel_date
= 'null';
3395 $contributionDAO->cancel_reason
= NULL;
3396 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3397 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3398 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3399 $contributionDAO->save();
3401 //Change status of financial record too
3402 $financialTrxn->status_id
= $statusId;
3403 $financialTrxn->save();
3405 // note : not using the self::add method,
3406 // the reason because it performs 'status change' related code execution for financial records
3407 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3408 // are coded below i.e. just updating financial_item status to 'Paid'
3410 if ($participantId) {
3411 // update participant status
3412 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3413 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3414 foreach ($ids as $val) {
3415 $participantUpdate['id'] = $val;
3416 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3417 CRM_Event_BAO_Participant
::add($participantUpdate);
3421 // update financial item statuses
3422 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3423 $paidStatus = array_search('Paid', $financialItemStatus);
3425 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3426 $sqlFinancialItemUpdate = "
3427 UPDATE civicrm_financial_item fi
3428 LEFT JOIN civicrm_entity_financial_trxn eft
3429 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3430 SET status_id = {$paidStatus}
3431 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3433 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3436 elseif ($paymentType == 'refund') {
3437 // build params for recording financial trxn entry
3438 $params['contribution'] = $contributionDAO;
3439 $params = array_merge($defaults, $params);
3440 $params['skipLineItem'] = TRUE;
3441 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3442 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3444 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3445 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3446 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3448 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3450 // note : not using the self::add method,
3451 // the reason because it performs 'status change' related code execution for financial records
3452 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3453 // are coded below i.e. just updating financial_item status to 'Paid'
3454 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3456 // add financial item entry
3457 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3458 $getLine['entity_id'] = $contributionDAO->id
;
3459 $getLine['entity_table'] = 'civicrm_contribution';
3460 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3461 if (!empty($lineItemId->id
)) {
3462 $addFinancialEntry = array(
3463 'transaction_date' => $financialTrxn->trxn_date
,
3464 'contact_id' => $contributionDAO->contact_id
,
3465 'amount' => $financialTrxn->total_amount
,
3466 'status_id' => array_search('Paid', $financialItemStatus),
3467 'entity_id' => $lineItemId->id
,
3468 'entity_table' => 'civicrm_line_item',
3470 $trxnIds['id'] = $financialTrxn->id
;
3471 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3473 if ($participantId) {
3474 // update participant status
3475 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3476 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3477 foreach ($ids as $val) {
3478 $participantUpdate['id'] = $val;
3479 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3480 CRM_Event_BAO_Participant
::add($participantUpdate);
3485 // activity creation
3486 if (!empty($financialTrxn)) {
3487 if ($participantId) {
3488 $inputParams['id'] = $participantId;
3491 $component = 'event';
3492 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3493 $entityObj = $entityObj[$participantId];
3495 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3497 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3499 return $financialTrxn;
3505 * @param $activityType
3507 * @param int $contributionId
3509 * @throws CRM_Core_Exception
3511 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3512 if ($component == 'event') {
3513 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3514 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3515 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3516 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3517 $targetCid = $entityObj->contact_id
;
3518 // source record id would be the contribution id
3519 $srcRecId = $contributionId;
3523 $activityParams = array(
3524 'source_contact_id' => $targetCid,
3525 'source_record_id' => $srcRecId,
3526 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3530 'subject' => $subject,
3531 'activity_date_time' => $date,
3532 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3536 'skipRecentView' => TRUE,
3539 // create activity with target contacts
3540 $session = CRM_Core_Session
::singleton();
3541 $id = $session->get('userID');
3543 $activityParams['source_contact_id'] = $id;
3544 $activityParams['target_contact_id'][] = $targetCid;
3546 CRM_Activity_BAO_Activity
::create($activityParams);
3550 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3554 * @param bool $getTrxnInfo
3555 * @param bool $usingLineTotal
3559 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3560 if ($component == 'event') {
3561 $entity = 'participant';
3562 $entityTable = 'civicrm_participant';
3563 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3565 if (!$contributionId) {
3566 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3567 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3568 $id = $primaryParticipantId;
3570 if (!$contributionId) {
3575 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3576 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3582 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3583 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3586 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3587 // for additional participants
3588 if ($entityTable == 'civicrm_participant') {
3589 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3591 foreach ($ids as $val) {
3592 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3596 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3600 $baseTrxnId = $total['trxn_id'];
3601 $total = $total['total_amount'];
3604 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3605 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3607 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3608 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3609 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3611 if ($paymentBalance == 0 && $contributionIsPayLater) {
3612 $paymentBalance = $total;
3615 $info['total'] = $total;
3616 $info['paid'] = $total - $paymentBalance;
3617 $info['balance'] = $paymentBalance;
3619 $info['component'] = $component;
3620 $info['payLater'] = $contributionIsPayLater;
3622 if ($getTrxnInfo && $baseTrxnId) {
3623 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3625 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3626 FROM civicrm_contribution con
3627 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3628 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3629 WHERE con.id = {$contributionId}
3632 // conditioned WHERE clause
3634 // if balance trxn exists don't include details of it in transaction info
3635 $sql .= " AND ft.id != {$baseTrxnId} ";
3637 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3639 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3640 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3641 while ($resultDAO->fetch()) {
3642 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3643 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3645 'total_amount' => $resultDAO->total_amount
,
3646 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3647 'payment_instrument' => $paidByLabel,
3648 'receive_date' => $resultDAO->trxn_date
,
3649 'trxn_id' => $resultDAO->trxn_id
,
3650 'status' => $statuses[$resultDAO->status_id
],
3652 if ($paidByName == 'Check') {
3653 $val['check_number'] = $resultDAO->check_number
;
3657 $info['transaction'] = $rows;
3663 * Get financial account id has 'Sales Tax Account is'
3664 * account relationship with financial type
3666 * @param int $financialTypeId
3668 * @return FinancialAccountId
3670 public static function getFinancialAccountId($financialTypeId) {
3671 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3672 $searchParams = array(
3673 'entity_table' => 'civicrm_financial_type',
3674 'entity_id' => $financialTypeId,
3675 'account_relationship' => $accountRel,
3678 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3680 return CRM_Utils_Array
::value('financial_account_id', $result);
3686 * @param array $params
3687 * @param bool $isLineItem
3691 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3692 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3694 // Update contribution.
3695 if (!empty($params['id'])) {
3696 $id = $params['id'];
3697 $values = $ids = array();
3698 $contrbutionParams = array('id' => $id);
3699 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3701 // To assign pervious finantial type on update of contribution
3702 if (!isset($params['financial_type_id'])) {
3703 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3705 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3706 // Assisn tax Amount on update of contrbution
3707 if (!empty($prevContributionValue->tax_amount
)) {
3708 $params['tax_amount'] = 'null';
3709 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3710 foreach ($params['line_item'] as $setID => $priceField) {
3711 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3712 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3719 // New Contrbution and update of contribution with tax rate financial type
3720 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3721 empty($params['skipLineItem']) && !$isLineItem
3723 $taxRateParams = $taxRates[$params['financial_type_id']];
3724 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3725 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3727 // Get Line Item on update of contribution
3728 if (isset($params['id'])) {
3729 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3732 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3734 foreach ($params['line_item'] as $setID => $priceField) {
3735 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3736 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3739 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3741 elseif (isset($params['api.line_item.create'])) {
3742 // Update total amount of contribution using lineItem
3743 $taxAmountArray = array();
3744 foreach ($params['api.line_item.create'] as $key => $value) {
3745 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3746 $taxRate = $taxRates[$value['financial_type_id']];
3747 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3748 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3751 $params['tax_amount'] = array_sum($taxAmountArray);
3752 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3755 // update line item of contrbution
3756 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3757 $taxRate = $taxRates[$params['financial_type_id']];
3758 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3759 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3766 * Check financial type validation on update of a contribution.
3768 * @param Integer $financialTypeId
3769 * Value of latest Financial Type.
3771 * @param Integer $contributionId
3774 * @param array $errors
3779 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3780 if (!empty($financialTypeId)) {
3781 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3782 if ($oldFinancialTypeId == $financialTypeId) {
3786 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3788 '1' => array($contributionId, 'Integer'),
3790 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3791 if ($result->N
> 1) {
3792 $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.');
3797 * Update related pledge payment payments.
3799 * This function has been refactored out of the back office contribution form and may
3800 * still overlap with other functions.
3802 * @param string $action
3803 * @param int $pledgePaymentID
3804 * @param int $contributionID
3805 * @param bool $adjustTotalAmount
3806 * @param float $total_amount
3807 * @param float $original_total_amount
3808 * @param int $contribution_status_id
3809 * @param int $original_contribution_status_id
3811 public static function updateRelatedPledge(
3817 $original_total_amount,
3818 $contribution_status_id,
3819 $original_contribution_status_id
3821 if (!$pledgePaymentID ||
$action & CRM_Core_Action
::ADD
&& !$contributionID) {
3825 if ($pledgePaymentID) {
3826 //store contribution id in payment record.
3827 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
3830 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3836 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
3842 $updatePledgePaymentStatus = FALSE;
3844 // If either the status or the amount has changed we update the pledge status.
3845 if ($action & CRM_Core_Action
::ADD
) {
3846 $updatePledgePaymentStatus = TRUE;
3848 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
3849 ($original_total_amount != $total_amount))
3851 $updatePledgePaymentStatus = TRUE;
3854 if ($updatePledgePaymentStatus) {
3855 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
3856 array($pledgePaymentID),
3857 $contribution_status_id,
3866 * Compute the stats values
3868 * @param $stat either 'mode' or 'median'
3870 * @param $alias of civicrm_contribution
3872 public static function computeStats($stat, $sql, $alias = NULL) {
3873 $mode = $median = array();
3876 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
3877 while ($modeDAO->fetch()) {
3878 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
3879 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
3889 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
3890 foreach ($currencies as $currency => $val) {
3891 $where = "AND {$alias}.currency = '{$currency}'";
3892 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
3896 $medianRow = floor($rowCount / 2);
3897 if ($rowCount %
2 == 0 && !empty($medianRow)) {
3903 $medianValue = "SELECT {$alias}.total_amount as median
3905 ORDER BY median LIMIT {$medianRow},{$offset}";
3906 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
3907 while ($medianValDAO->fetch()) {
3909 $midValue = $midValue +
$medianValDAO->median
;
3912 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
3916 $midValue = $midValue / 2;
3917 $median[] = CRM_Utils_Money
::format($midValue, $currency);