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
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * Static field for all the contribution information that we can potentially import
42 static $_importableFields = NULL;
45 * Static field for all the contribution information that we can potentially export
49 static $_exportableFields = NULL;
52 * Field for all the objects related to this contribution
53 * @var array of objects (e.g membership object, participant object)
55 public $_relatedObjects = array();
58 * Field for the component - either 'event' (participant) or 'contribute'
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
63 * @var string component or event
65 public $_component = NULL;
68 * Possibly obsolete variable.
70 * If you use it please explain why it is set in the create function here.
74 public $trxn_result_code;
79 * @return \CRM_Contribute_DAO_Contribution
83 public function __construct() {
84 parent
::__construct();
88 * Takes an associative array and creates a contribution object.
90 * the function extract all the params it needs to initialize the create a
91 * contribution object. the params array could contain additional unused name/value
94 * @param array $params
95 * (reference ) an assoc array of name/value pairs.
97 * The array that holds all the db ids.
99 * @return CRM_Contribute_BAO_Contribution|void
101 public static function add(&$params, $ids = array()) {
102 if (empty($params)) {
105 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
106 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
107 $duplicates = array();
108 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
109 $error = CRM_Core_Error
::singleton();
110 $d = implode(', ', $duplicates);
111 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
114 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
119 // first clean up all the money fields
120 $moneyFields = array(
124 'non_deductible_amount',
127 //if priceset is used, no need to cleanup money
128 if (!empty($params['skipCleanMoney'])) {
129 unset($moneyFields[0]);
132 foreach ($moneyFields as $field) {
133 if (isset($params[$field])) {
134 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
138 //if contribution is created with cancelled or refunded status, add credit note id
139 if (!empty($params['contribution_status_id'])) {
140 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
142 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
143 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
145 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
146 $params['creditnote_id'] = self
::createCreditNoteId();
151 //set defaults in create mode
152 if (!$contributionID) {
153 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
154 self
::calculateMissingAmountParams($params);
157 if (!empty($params['payment_instrument_id'])) {
158 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
159 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
160 $params['check_number'] = 'null';
164 $setPrevContribution = TRUE;
165 // CRM-13964 partial payment
166 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
167 $partialAmtTotal = $params['partial_payment_total'];
168 $partialAmtPay = $params['partial_amount_pay'];
169 $params['total_amount'] = $partialAmtTotal;
170 if ($partialAmtPay < $partialAmtTotal) {
171 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
172 $params['is_pay_later'] = 0;
173 $setPrevContribution = FALSE;
176 if ($contributionID && $setPrevContribution) {
177 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
180 if ($contributionID) {
181 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
184 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
186 $contribution = new CRM_Contribute_BAO_Contribution();
187 $contribution->copyValues($params);
189 $contribution->id
= $contributionID;
191 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
192 $config = CRM_Core_Config
::singleton();
193 $contribution->currency
= $config->defaultCurrency
;
196 $result = $contribution->save();
198 // Add financial_trxn details as part of fix for CRM-4724
199 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
200 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
202 //add Account details
203 $params['contribution'] = $contribution;
204 self
::recordFinancialAccounts($params);
206 // reset the group contact cache for this group
207 CRM_Contact_BAO_GroupContactCache
::remove();
209 if ($contributionID) {
210 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
213 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
220 * Get defaults for new entity.
223 public static function getDefaults() {
225 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
226 FALSE, FALSE, FALSE, 'AND is_default = 1')
228 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
233 * Given the list of params in the params array, fetch the object
234 * and store the values in the values array
236 * @param array $params
237 * Input parameters to find object.
238 * @param array $values
239 * Output values of the object.
241 * The array that holds all the db ids.
243 * @return CRM_Contribute_BAO_Contribution|null the found object or null
245 public static function &getValues($params, &$values, &$ids) {
246 if (empty($params)) {
249 $contribution = new CRM_Contribute_BAO_Contribution();
251 $contribution->copyValues($params);
253 if ($contribution->find(TRUE)) {
254 $ids['contribution'] = $contribution->id
;
256 CRM_Core_DAO
::storeValues($contribution, $values);
258 return $contribution;
260 $null = NULL; // return by reference
265 * Calculate net_amount & fee_amount if they are not set.
267 * Net amount should be total - fee.
268 * This should only be called for new contributions.
270 * @param array $params
271 * Params for a new contribution before they are saved.
273 public static function calculateMissingAmountParams(&$params) {
274 if (!isset($params['fee_amount'])) {
275 if (isset($params['total_amount']) && isset($params['net_amount'])) {
276 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
279 $params['fee_amount'] = 0;
282 if (!isset($params['net_amount'])) {
283 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
288 * Get the number of terms for this contribution for a given membership type
289 * based on querying the line item table and relevant price field values
290 * Note that any one contribution should only be able to have one line item relating to a particular membership
293 * @param int $membershipTypeID
295 * @param int $contributionID
299 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
300 $numTerms = CRM_Core_DAO
::singleValueQuery("
301 SELECT membership_num_terms FROM civicrm_line_item li
302 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
303 WHERE contribution_id = %1 AND membership_type_id = %2",
304 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
306 // default of 1 is precautionary
307 return empty($numTerms) ?
1 : $numTerms;
311 * Takes an associative array and creates a contribution object.
313 * @param array $params
314 * (reference ) an assoc array of name/value pairs.
316 * The array that holds all the db ids.
318 * @return CRM_Contribute_BAO_Contribution
320 public static function create(&$params, $ids = array()) {
321 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
322 foreach ($dateFields as $df) {
323 if (isset($params[$df])) {
324 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
328 //if contribution is created with cancelled or refunded status, add credit note id
329 if (!empty($params['contribution_status_id'])) {
330 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
332 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
333 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
335 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
336 $params['creditnote_id'] = self
::createCreditNoteId();
341 $transaction = new CRM_Core_Transaction();
343 $contribution = self
::add($params, $ids);
345 if (is_a($contribution, 'CRM_Core_Error')) {
346 $transaction->rollback();
347 return $contribution;
350 $params['contribution_id'] = $contribution->id
;
352 if (!empty($params['custom']) &&
353 is_array($params['custom'])
355 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
358 $session = CRM_Core_Session
::singleton();
360 if (!empty($params['note'])) {
362 'entity_table' => 'civicrm_contribution',
363 'note' => $params['note'],
364 'entity_id' => $contribution->id
,
365 'contact_id' => $session->get('userID'),
366 'modified_date' => date('Ymd'),
368 if (!$noteParams['contact_id']) {
369 $noteParams['contact_id'] = $params['contact_id'];
371 CRM_Core_BAO_Note
::add($noteParams);
374 // make entry in batch entity batch table
375 if (!empty($params['batch_id'])) {
376 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
377 $titleFields = array(
383 $retrieveRequired = 0;
384 foreach ($titleFields as $titleField) {
385 if (!isset($contribution->$titleField)) {
386 $retrieveRequired = 1;
390 if ($retrieveRequired == 1) {
391 $contribution->find(TRUE);
395 // Handle soft credit and / or link to personal campaign page
396 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
398 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
400 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
401 $softParams = array();
402 $softParams['id'] = $pcpId ?
$pcpId : NULL;
403 $softParams['contribution_id'] = $contribution->id
;
404 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
405 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
406 $pcp['pcp_made_through_id'], 'contact_id'
408 $softParams['currency'] = $contribution->currency
;
409 $softParams['amount'] = $contribution->total_amount
;
410 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
411 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
412 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
413 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
414 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
415 //Send notification to owner for PCP
416 if ($contributionSoft->pcp_id
&& empty($pcpId)) {
417 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
420 //Delete PCP against this contribution and create new on submitted PCP information
421 elseif (array_key_exists('pcp', $params) && $pcpId) {
422 $deleteParams = array('id' => $pcpId);
423 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
425 if (isset($params['soft_credit'])) {
426 $softParams = $params['soft_credit'];
427 foreach ($softParams as $softParam) {
428 if (!empty($softIDs)) {
429 $key = key($softIDs);
430 $softParam['id'] = $softIDs[$key];
431 unset($softIDs[$key]);
433 $softParam['contribution_id'] = $contribution->id
;
434 $softParam['currency'] = $contribution->currency
;
435 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
436 if (empty($softParam['amount'])) {
437 $softParam['amount'] = $contribution->total_amount
;
439 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
442 if (!empty($softIDs)) {
443 foreach ($softIDs as $softID) {
444 if (!in_array($softID, $params['soft_credit_ids'])) {
445 $deleteParams = array('id' => $softID);
446 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
452 $transaction->commit();
454 // check if activity record exist for this contribution, if
456 $activity = new CRM_Activity_DAO_Activity();
457 $activity->source_record_id
= $contribution->id
;
458 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
462 if (!$activity->find(TRUE)) {
463 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
466 // CRM-13237 : if activity record found, update it with campaign id of contribution
467 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
470 // do not add to recent items for import, CRM-4399
471 if (empty($params['skipRecentView'])) {
472 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
473 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
475 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
476 $titleFields = array(
482 $retrieveRequired = 0;
483 foreach ($titleFields as $titleField) {
484 if (!isset($contribution->$titleField)) {
485 $retrieveRequired = 1;
489 if ($retrieveRequired == 1) {
490 $contribution->find(TRUE);
492 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
493 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
495 $recentOther = array();
496 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
497 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
498 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
502 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
503 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
504 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
508 // add the recently created Contribution
509 CRM_Utils_Recent
::add($title,
513 $contribution->contact_id
,
519 return $contribution;
523 * Get the values for pseudoconstants for name->value and reverse.
525 * @param array $defaults
526 * (reference) the default values, some of which need to be resolved.
527 * @param bool $reverse
528 * True if we want to resolve the values in the reverse direction (value -> name).
532 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
533 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
534 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
535 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
536 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
540 * Convert associative array names to values and vice-versa.
542 * This function is used by both the web form layer and the api. Note that
543 * the api needs the name => value conversion, also the view layer typically
544 * requires value => name conversion
546 * @param array $defaults
547 * @param string $property
548 * @param array $lookup
549 * @param bool $reverse
553 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
554 $id = $property . '_id';
556 $src = $reverse ?
$property : $id;
557 $dst = $reverse ?
$id : $property;
559 if (!array_key_exists($src, $defaults)) {
563 $look = $reverse ?
array_flip($lookup) : $lookup;
565 if (is_array($look)) {
566 if (!array_key_exists($defaults[$src], $look)) {
570 $defaults[$dst] = $look[$defaults[$src]];
575 * Retrieve DB object based on input parameters.
577 * It also stores all the retrieved values in the default array.
579 * @param array $params
580 * (reference ) an assoc array of name/value pairs.
581 * @param array $defaults
582 * (reference ) an assoc array to hold the name / value pairs.
583 * in a hierarchical manner
585 * (reference) the array that holds all the db ids.
587 * @return CRM_Contribute_BAO_Contribution
589 public static function retrieve(&$params, &$defaults, &$ids) {
590 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
591 return $contribution;
595 * Combine all the importable fields from the lower levels object.
597 * The ordering is important, since currently we do not have a weight
598 * scheme. Adding weight is super important and should be done in the
599 * next week or so, before this can be called complete.
601 * @param string $contactType
602 * @param bool $status
605 * array of importable Fields
607 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
608 if (!self
::$_importableFields) {
609 if (!self
::$_importableFields) {
610 self
::$_importableFields = array();
614 $fields = array('' => array('title' => ts('- do not import -')));
617 $fields = array('' => array('title' => ts('- Contribution Fields -')));
620 $note = CRM_Core_DAO_Note
::import();
621 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
622 unset($tmpFields['option_value']);
623 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
624 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
626 // Using new Dedupe rule.
628 'contact_type' => $contactType,
629 'used' => 'Unsupervised',
631 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
632 $tmpContactField = array();
633 if (is_array($fieldsArray)) {
634 foreach ($fieldsArray as $value) {
635 //skip if there is no dupe rule
636 if ($value == 'none') {
639 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
644 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
645 $tmpContactField[trim($value)] = $contactFields[trim($value)];
647 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
650 $title = $tmpContactField[trim($value)]['title'];
652 $tmpContactField[trim($value)]['title'] = $title;
656 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
657 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
658 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
659 $fields = array_merge($fields, $tmpContactField);
660 $fields = array_merge($fields, $tmpFields);
661 $fields = array_merge($fields, $note);
662 $fields = array_merge($fields, $optionFields);
663 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
664 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
665 self
::$_importableFields = $fields;
667 return self
::$_importableFields;
673 public static function &exportableFields() {
674 if (!self
::$_exportableFields) {
675 if (!self
::$_exportableFields) {
676 self
::$_exportableFields = array();
679 $impFields = CRM_Contribute_DAO_Contribution
::export();
680 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
681 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
682 $typeField = CRM_Financial_DAO_FinancialType
::export();
683 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
684 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
685 $contributionStatus = array(
686 'contribution_status' => array(
687 'title' => ts('Contribution Status'),
688 'name' => 'contribution_status',
689 'data_type' => CRM_Utils_Type
::T_STRING
,
693 $contributionPage = array(
694 'contribution_page' => array(
695 'title' => ts('Contribution Page'),
696 'name' => 'contribution_page',
697 'where' => 'civicrm_contribution_page.title',
698 'data_type' => CRM_Utils_Type
::T_STRING
,
702 $contributionNote = array(
703 'contribution_note' => array(
704 'title' => ts('Contribution Note'),
705 'name' => 'contribution_note',
706 'data_type' => CRM_Utils_Type
::T_TEXT
,
710 $contributionRecurId = array(
711 'contribution_recur_id' => array(
712 'title' => ts('Recurring Contributions ID'),
713 'name' => 'contribution_recur_id',
714 'where' => 'civicrm_contribution.contribution_recur_id',
715 'data_type' => CRM_Utils_Type
::T_INT
,
719 $extraFields = array(
720 'contribution_batch' => array(
721 'title' => ts('Batch Name'),
725 $softCreditFields = array(
726 'contribution_soft_credit_name' => array(
727 'name' => 'contribution_soft_credit_name',
728 'title' => 'Soft Credit For',
729 'where' => 'civicrm_contact_d.display_name',
730 'data_type' => CRM_Utils_Type
::T_STRING
,
732 'contribution_soft_credit_amount' => array(
733 'name' => 'contribution_soft_credit_amount',
734 'title' => 'Soft Credit Amount',
735 'where' => 'civicrm_contribution_soft.amount',
736 'data_type' => CRM_Utils_Type
::T_MONEY
,
738 'contribution_soft_credit_type' => array(
739 'name' => 'contribution_soft_credit_type',
740 'title' => 'Soft Credit Type',
741 'where' => 'contribution_softcredit_type.label',
742 'data_type' => CRM_Utils_Type
::T_STRING
,
744 'contribution_soft_credit_contribution_id' => array(
745 'name' => 'contribution_soft_credit_contribution_id',
746 'title' => 'Soft Credit For Contribution ID',
747 'where' => 'civicrm_contribution_soft.contribution_id',
748 'data_type' => CRM_Utils_Type
::T_INT
,
752 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
753 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
754 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
757 self
::$_exportableFields = $fields;
760 return self
::$_exportableFields;
764 * @param null $status
765 * @param null $startDate
766 * @param null $endDate
770 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
774 $where[] = 'contribution_status_id = 1';
778 $where[] = 'contribution_status_id = 3';
783 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
786 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
789 $whereCond = implode(' AND ', $where);
792 SELECT sum( total_amount ) as total_amount,
793 count( civicrm_contribution.id ) as total_count,
795 FROM civicrm_contribution
796 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
798 AND ( is_test = 0 OR is_test IS NULL )
799 AND contact.is_deleted = 0
803 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
806 while ($dao->fetch()) {
807 $count +
= $dao->total_count
;
808 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
812 'amount' => implode(', ', $amount),
820 * Delete the indirect records associated with this contribution first.
825 * $results no of deleted Contribution on success, false otherwise
827 public static function deleteContribution($id) {
828 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
830 $transaction = new CRM_Core_Transaction();
833 //delete activity record
835 'source_record_id' => $id,
836 // activity type id for contribution
837 'activity_type_id' => 6,
840 CRM_Activity_BAO_Activity
::deleteActivity($params);
842 //delete billing address if exists for this contribution.
843 self
::deleteAddress($id);
845 //update pledge and pledge payment, CRM-3961
846 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
848 // remove entry from civicrm_price_set_entity, CRM-5095
849 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
850 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
852 // cleanup line items.
853 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
855 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
856 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
858 if ($participantId) {
859 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
862 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
866 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
867 $noteId = key($note);
869 CRM_Core_BAO_Note
::del($noteId, FALSE);
872 $dao = new CRM_Contribute_DAO_Contribution();
875 $results = $dao->delete();
877 $transaction->commit();
879 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
881 // delete the recently created Contribution
882 $contributionRecent = array(
884 'type' => 'Contribution',
886 CRM_Utils_Recent
::del($contributionRecent);
892 * Check if there is a contribution with the same trxn_id or invoice_id.
894 * @param array $input
895 * An assoc array of name/value pairs.
896 * @param array $duplicates
897 * (reference) store ids of duplicate contribs.
901 * true if duplicate, false otherwise
903 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
905 $id = CRM_Utils_Array
::value('id', $input);
907 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
908 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
914 $clause[] = "trxn_id = %1";
915 $input[1] = array($trxn_id, 'String');
919 $clause[] = "invoice_id = %2";
920 $input[2] = array($invoice_id, 'String');
923 if (empty($clause)) {
927 $clause = implode(' OR ', $clause);
929 $clause = "( $clause ) AND id != %3";
930 $input[3] = array($id, 'Integer');
933 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
934 $dao = CRM_Core_DAO
::executeQuery($query, $input);
936 while ($dao->fetch()) {
937 $duplicates[] = $dao->id
;
944 * Takes an associative array and creates a contribution_product object.
946 * the function extract all the params it needs to initialize the create a
947 * contribution_product object. the params array could contain additional unused name/value
950 * @param array $params
951 * (reference) an assoc array of name/value pairs.
953 * @return CRM_Contribute_DAO_ContributionProduct
955 public static function addPremium(&$params) {
956 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
957 $contributionProduct->copyValues($params);
958 return $contributionProduct->save();
962 * Get list of contribution fields for profile.
963 * For now we only allow custom contribution fields to be in
966 * @param bool $addExtraFields
967 * True if special fields needs to be added.
970 * the list of contribution fields
972 public static function getContributionFields($addExtraFields = TRUE) {
973 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
974 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
976 if ($addExtraFields) {
977 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
980 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
982 foreach ($contributionFields as $key => $var) {
983 if ($key == 'contribution_contact_id') {
986 elseif ($key == 'contribution_campaign_id') {
987 $var['title'] = ts('Campaign');
989 $fields[$key] = $var;
992 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
997 * Add extra fields specific to contribution.
999 public static function getSpecialContributionFields() {
1000 $extraFields = array(
1001 'contribution_soft_credit_name' => array(
1002 'name' => 'contribution_soft_credit_name',
1003 'title' => 'Soft Credit Name',
1004 'headerPattern' => '/^soft_credit_name$/i',
1005 'where' => 'civicrm_contact_d.display_name',
1007 'contribution_soft_credit_email' => array(
1008 'name' => 'contribution_soft_credit_email',
1009 'title' => 'Soft Credit Email',
1010 'headerPattern' => '/^soft_credit_email$/i',
1011 'where' => 'soft_email.email',
1013 'contribution_soft_credit_phone' => array(
1014 'name' => 'contribution_soft_credit_phone',
1015 'title' => 'Soft Credit Phone',
1016 'headerPattern' => '/^soft_credit_phone$/i',
1017 'where' => 'soft_phone.phone',
1019 'contribution_soft_credit_contact_id' => array(
1020 'name' => 'contribution_soft_credit_contact_id',
1021 'title' => 'Soft Credit Contact ID',
1022 'headerPattern' => '/^soft_credit_contact_id$/i',
1023 'where' => 'civicrm_contribution_soft.contact_id',
1027 return $extraFields;
1031 * @param int $pageID
1035 public static function getCurrentandGoalAmount($pageID) {
1037 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1038 FROM civicrm_contribution_page p,
1039 civicrm_contribution c
1040 WHERE p.id = c.contribution_page_id
1042 AND c.cancel_date is null
1046 $config = CRM_Core_Config
::singleton();
1047 $params = array(1 => array($pageID, 'Integer'));
1048 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1050 if ($dao->fetch()) {
1051 return array($dao->goal
, $dao->total
);
1054 return array(NULL, NULL);
1059 * Get list of contribution In Honor of contact Ids.
1061 * @param int $honorId
1062 * In Honor of Contact ID.
1065 * list of contribution fields
1068 public static function getHonorContacts($honorId) {
1070 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1071 $honorDAO->contact_id
= $honorId;
1074 $type = CRM_Contribute_PseudoConstant
::financialType();
1076 while ($honorDAO->fetch()) {
1077 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1078 $contributionDAO->id
= $honorDAO->contribution_id
;
1080 if ($contributionDAO->find(TRUE)) {
1081 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1082 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1083 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1084 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1085 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1086 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1087 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1088 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1089 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1097 * Get the sort name of a contact for a particular contribution.
1100 * Id of the contribution.
1102 * @return null|string
1103 * sort name of the contact if found
1105 public static function sortName($id) {
1106 $id = CRM_Utils_Type
::escape($id, 'Integer');
1109 SELECT civicrm_contact.sort_name
1110 FROM civicrm_contribution, civicrm_contact
1111 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1112 AND civicrm_contribution.id = {$id}
1114 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1118 * @param int $contactID
1122 public static function annual($contactID) {
1123 if (is_array($contactID)) {
1124 $contactIDs = implode(',', $contactID);
1127 $contactIDs = $contactID;
1130 $config = CRM_Core_Config
::singleton();
1131 $startDate = $endDate = NULL;
1133 $currentMonth = date('m');
1134 $currentDay = date('d');
1135 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1136 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1137 (int ) $config->fiscalYearStart
['d'] > $currentDay
1140 $year = date('Y') - 1;
1145 $nextYear = $year +
1;
1147 if ($config->fiscalYearStart
) {
1148 if ($config->fiscalYearStart
['M'] < 10) {
1149 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1151 if ($config->fiscalYearStart
['d'] < 10) {
1152 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1154 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1159 $startDate = "$year$monthDay";
1160 $endDate = "$nextYear$monthDay";
1163 SELECT count(*) as count,
1164 sum(total_amount) as amount,
1165 avg(total_amount) as average,
1167 FROM civicrm_contribution b
1168 WHERE b.contact_id IN ( $contactIDs )
1169 AND b.contribution_status_id = 1
1171 AND b.receive_date >= $startDate
1172 AND b.receive_date < $endDate
1175 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1177 $amount = $average = array();
1178 while ($dao->fetch()) {
1179 if ($dao->count
> 0 && $dao->amount
> 0) {
1180 $count +
= $dao->count
;
1181 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1182 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1188 implode(', ', $amount),
1189 implode(', ', $average),
1192 return array(0, 0, 0);
1196 * Check if there is a contribution with the params passed in.
1197 * Used for trxn_id,invoice_id and contribution_id
1199 * @param array $params
1200 * An assoc array of name/value pairs.
1203 * contribution id if success else NULL
1205 public static function checkDuplicateIds($params) {
1206 $dao = new CRM_Contribute_DAO_Contribution();
1210 foreach ($params as $k => $v) {
1212 $clause[] = "$k = '$v'";
1215 $clause = implode(' AND ', $clause);
1216 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1217 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1219 while ($dao->fetch()) {
1227 * Get the contribution details for component export.
1229 * @param int $exportMode
1231 * @param string $componentIds
1238 public static function getContributionDetails($exportMode, $componentIds) {
1239 $paymentDetails = array();
1240 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1242 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1243 $componentSelect = " civicrm_participant_payment.participant_id id";
1244 $additionalClause = "
1245 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1246 AND civicrm_participant_payment.participant_id {$componentClause} )
1249 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1250 $componentSelect = " civicrm_membership_payment.membership_id id";
1251 $additionalClause = "
1252 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1253 AND civicrm_membership_payment.membership_id {$componentClause} )
1256 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1257 $componentSelect = " civicrm_pledge_payment.id id";
1258 $additionalClause = "
1259 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1260 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1264 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1265 trxn_id, {$componentSelect}
1266 FROM civicrm_contribution
1267 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1268 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1269 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1270 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1271 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1272 AND option_group_contribution_status.id = contribution_status.option_group_id )
1276 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1278 while ($dao->fetch()) {
1279 $paymentDetails[$dao->id
] = array(
1280 'total_amount' => $dao->total_amount
,
1281 'contribution_status' => $dao->status
,
1282 'receive_date' => $dao->receive_date
,
1283 'pay_instru' => $dao->payment_instrument
,
1284 'trxn_id' => $dao->trxn_id
,
1288 return $paymentDetails;
1292 * Create address associated with contribution record.
1294 * @param array $params
1295 * @param int $billingLocationTypeID
1300 public static function createAddress(&$params, $billingLocationTypeID) {
1301 $billingFields = array(
1304 'state_province_id',
1309 //build address array
1310 $addressParams = array();
1311 $addressParams['location_type_id'] = $billingLocationTypeID;
1312 $addressParams['is_billing'] = 1;
1314 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1315 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1316 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1317 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1319 foreach ($billingFields as $value) {
1320 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1323 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1325 return $address->id
;
1329 * Delete billing address record related contribution.
1331 * @param int $contributionId
1332 * @param int $contactId
1335 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1337 $contactJoin = NULL;
1339 if ($contributionId) {
1340 $clauses[] = "cc.id = {$contributionId}";
1344 $clauses[] = "cco.id = {$contactId}";
1345 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1348 if (empty($clauses)) {
1349 CRM_Core_Error
::fatal();
1352 $condition = implode(' OR ', $clauses);
1356 FROM civicrm_address ca
1357 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1361 $dao = CRM_Core_DAO
::executeQuery($query);
1363 while ($dao->fetch()) {
1364 $params = array('id' => $dao->id
);
1365 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1370 * This function check online pending contribution associated w/
1371 * Online Event Registration or Online Membership signup.
1373 * @param int $componentId
1374 * Participant/membership id.
1375 * @param string $componentName
1379 * pending contribution id.
1381 public static function checkOnlinePendingContribution($componentId, $componentName) {
1382 $contributionId = NULL;
1383 if (!$componentId ||
1384 !in_array($componentName, array('Event', 'Membership'))
1386 return $contributionId;
1389 if ($componentName == 'Event') {
1390 $idName = 'participant_id';
1391 $componentTable = 'civicrm_participant';
1392 $paymentTable = 'civicrm_participant_payment';
1393 $source = ts('Online Event Registration');
1396 if ($componentName == 'Membership') {
1397 $idName = 'membership_id';
1398 $componentTable = 'civicrm_membership';
1399 $paymentTable = 'civicrm_membership_payment';
1400 $source = ts('Online Contribution');
1403 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1406 SELECT component.id as {$idName},
1407 componentPayment.contribution_id as contribution_id,
1408 contribution.source source,
1409 contribution.contribution_status_id as contribution_status_id,
1410 contribution.is_pay_later as is_pay_later
1411 FROM $componentTable component
1412 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1413 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1414 WHERE component.id = {$componentId}";
1416 $dao = CRM_Core_DAO
::executeQuery($query);
1418 while ($dao->fetch()) {
1419 if ($dao->contribution_id
&&
1420 $dao->is_pay_later
&&
1421 $dao->contribution_status_id
== $pendingStatusId &&
1422 strpos($dao->source
, $source) !== FALSE
1424 $contributionId = $dao->contribution_id
;
1429 return $contributionId;
1433 * Update contribution as well as related objects.
1435 * @param array $params
1436 * @param bool $processContributionObject
1439 * @throws \Exception
1441 public static function transitionComponents($params, $processContributionObject = FALSE) {
1442 // get minimum required values.
1443 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1444 $componentId = CRM_Utils_Array
::value('component_id', $params);
1445 $componentName = CRM_Utils_Array
::value('componentName', $params);
1446 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1447 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1449 // if we already processed contribution object pass previous status id.
1450 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1452 $updateResult = array();
1454 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1456 // we process only ( Completed, Cancelled, or Failed ) contributions.
1457 if (!$contributionId ||
1458 !in_array($contributionStatusId, array(
1459 array_search('Completed', $contributionStatuses),
1460 array_search('Cancelled', $contributionStatuses),
1461 array_search('Failed', $contributionStatuses),
1464 return $updateResult;
1467 if (!$componentName ||
!$componentId) {
1468 // get the related component details.
1469 $componentDetails = self
::getComponentDetails($contributionId);
1472 $componentDetails['contact_id'] = $contactId;
1473 $componentDetails['component'] = $componentName;
1475 if ($componentName == 'event') {
1476 $componentDetails['participant'] = $componentId;
1479 $componentDetails['membership'] = $componentId;
1483 if (!empty($componentDetails['contact_id'])) {
1484 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1490 // do check for required ids.
1491 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1492 return $updateResult;
1495 //now we are ready w/ required ids, start processing.
1497 $baseIPN = new CRM_Core_Payment_BaseIPN();
1499 $input = $ids = $objects = array();
1501 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1502 $ids['contribution'] = $contributionId;
1503 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1504 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1505 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1506 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1507 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1508 $ids['contributionRecur'] = NULL;
1509 $ids['contributionPage'] = NULL;
1511 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1512 CRM_Core_Error
::fatal();
1515 $memberships = &$objects['membership'];
1516 $participant = &$objects['participant'];
1517 $pledgePayment = &$objects['pledge_payment'];
1518 $contribution = &$objects['contribution'];
1520 if ($pledgePayment) {
1521 $pledgePaymentIDs = array();
1522 foreach ($pledgePayment as $key => $object) {
1523 $pledgePaymentIDs[] = $object->id
;
1525 $pledgeID = $pledgePayment[0]->pledge_id
;
1528 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1531 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1532 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1537 // we might want to process contribution object.
1538 $processContribution = FALSE;
1539 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1540 if (is_array($memberships)) {
1541 foreach ($memberships as $membership) {
1543 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1544 $membership->save();
1546 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1547 if ($processContributionObject) {
1548 $processContribution = TRUE;
1555 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1556 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1558 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1559 if ($processContributionObject) {
1560 $processContribution = TRUE;
1564 if ($pledgePayment) {
1565 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1567 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1568 if ($processContributionObject) {
1569 $processContribution = TRUE;
1573 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1574 if (is_array($memberships)) {
1575 foreach ($memberships as $membership) {
1577 $membership->status_id
= array_search('Expired', $membershipStatuses);
1578 $membership->save();
1580 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1581 if ($processContributionObject) {
1582 $processContribution = TRUE;
1588 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1589 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1591 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1592 if ($processContributionObject) {
1593 $processContribution = TRUE;
1597 if ($pledgePayment) {
1598 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1600 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1601 if ($processContributionObject) {
1602 $processContribution = TRUE;
1606 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1608 // only pending contribution related object processed.
1609 if ($previousContriStatusId &&
1610 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1612 // this is case when we already processed contribution object.
1613 return $updateResult;
1615 elseif (!$previousContriStatusId &&
1616 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1618 // this is case when we are going to process contribution object later.
1619 return $updateResult;
1622 if (is_array($memberships)) {
1623 foreach ($memberships as $membership) {
1628 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1629 $membership->membership_type_id
,
1630 $membership->is_test
, $membership->id
1633 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1634 // this picks up membership type changes during renewals
1636 SELECT membership_type_id
1637 FROM civicrm_membership_log
1638 WHERE membership_id=$membership->id
1641 $dao = new CRM_Core_DAO();
1643 if ($dao->fetch()) {
1644 if (!empty($dao->membership_type_id
)) {
1645 $membership->membership_type_id
= $dao->membership_type_id
;
1646 $membership->save();
1649 // else fall back to using current membership type
1652 // Figure out number of terms
1654 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1655 foreach ($lineitems as $lineitem) {
1656 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1657 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1659 // in case membership_num_terms comes through as null or zero
1660 $numterms = $numterms >= 1 ?
$numterms : 1;
1665 // CRM-15735-to update the membership status as per the contribution receive date
1667 if (!empty($params['receive_date'])) {
1668 $joinDate = $params['receive_date'];
1669 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1670 $membership->end_date
,
1671 $membership->join_date
,
1672 $params['receive_date'],
1674 $membership->membership_type_id
,
1677 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1678 $membership->save();
1681 if ($currentMembership) {
1682 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1683 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1684 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1687 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1690 //get the status for membership.
1691 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1693 $dates['join_date'],
1696 $membership->membership_type_id
,
1700 $formattedParams = array(
1701 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1702 array_search('Current', $membershipStatuses)
1704 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1705 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1706 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1709 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1711 $membership->copyValues($formattedParams);
1712 $membership->save();
1714 //updating the membership log
1715 $membershipLog = array();
1716 $membershipLog = $formattedParams;
1717 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1718 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1720 $membershipLog['start_date'] = $logStartDate;
1721 $membershipLog['membership_id'] = $membership->id
;
1722 $membershipLog['modified_id'] = $membership->contact_id
;
1723 $membershipLog['modified_date'] = date('Ymd');
1724 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1726 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1728 //update related Memberships.
1729 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1731 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1734 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1735 if ($processContributionObject) {
1736 $processContribution = TRUE;
1739 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1745 $updatedStatusId = array_search('Registered', $participantStatuses);
1746 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1748 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1749 if ($processContributionObject) {
1750 $processContribution = TRUE;
1754 if ($pledgePayment) {
1755 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1757 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1758 if ($processContributionObject) {
1759 $processContribution = TRUE;
1764 // process contribution object.
1765 if ($processContribution) {
1766 $contributionParams = array();
1773 'payment_instrument_id',
1776 'financial_type_id',
1777 'contribution_status_id',
1778 'non_deductible_amount',
1782 foreach ($fields as $field) {
1783 if (empty($params[$field])) {
1786 $contributionParams[$field] = $params[$field];
1789 $ids = array('contribution' => $contributionId);
1790 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1793 return $updateResult;
1797 * Returns all contribution related object ids.
1799 * @param $contributionId
1803 public static function getComponentDetails($contributionId) {
1804 $componentDetails = $pledgePayment = array();
1805 if (!$contributionId) {
1806 return $componentDetails;
1810 SELECT c.id as contribution_id,
1811 c.contact_id as contact_id,
1812 c.contribution_recur_id,
1813 mp.membership_id as membership_id,
1814 m.membership_type_id as membership_type_id,
1815 pp.participant_id as participant_id,
1816 p.event_id as event_id,
1817 pgp.id as pledge_payment_id
1818 FROM civicrm_contribution c
1819 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1820 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1821 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1822 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1823 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1824 WHERE c.id = $contributionId";
1826 $dao = CRM_Core_DAO
::executeQuery($query);
1827 $componentDetails = array();
1829 while ($dao->fetch()) {
1830 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1831 $componentDetails['contact_id'] = $dao->contact_id
;
1832 if ($dao->event_id
) {
1833 $componentDetails['event'] = $dao->event_id
;
1835 if ($dao->participant_id
) {
1836 $componentDetails['participant'] = $dao->participant_id
;
1838 if ($dao->membership_id
) {
1839 if (!isset($componentDetails['membership'])) {
1840 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1842 $componentDetails['membership'][] = $dao->membership_id
;
1843 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1845 if ($dao->pledge_payment_id
) {
1846 $pledgePayment[] = $dao->pledge_payment_id
;
1848 if ($dao->contribution_recur_id
) {
1849 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1853 if ($pledgePayment) {
1854 $componentDetails['pledge_payment'] = $pledgePayment;
1857 return $componentDetails;
1861 * @param int $contactId
1862 * @param bool $includeSoftCredit
1864 * @return null|string
1866 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1871 $contactContributionsSQL = "
1872 SELECT contribution.id AS id
1873 FROM civicrm_contribution contribution
1874 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1876 $contactSoftCreditContributionsSQL = "
1877 SELECT contribution.id
1878 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1879 ON ( contribution.id = softContribution.contribution_id )
1880 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1881 $query = "SELECT count( x.id ) count FROM ( ";
1882 $query .= $contactContributionsSQL;
1884 if ($includeSoftCredit) {
1885 $query .= " UNION ";
1886 $query .= $contactSoftCreditContributionsSQL;
1891 return CRM_Core_DAO
::singleValueQuery($query);
1895 * Get individual id for onbehalf contribution.
1897 * @param int $contributionId
1899 * @param int $contributorId
1903 * containing organization id and individual id
1905 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1909 if (!$contributionId) {
1913 // fetch contributor id if null
1914 if (!$contributorId) {
1915 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1916 $contributionId, 'contact_id'
1920 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1921 $activityTypeId = array_search('Contribution', $activityTypeIds);
1923 if ($activityTypeId && $contributorId) {
1925 SELECT civicrm_activity_contact.contact_id
1926 FROM civicrm_activity_contact
1927 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1928 WHERE civicrm_activity.activity_type_id = %1
1929 AND civicrm_activity.source_record_id = %2
1930 AND civicrm_activity_contact.record_type_id = %3
1933 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1934 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1937 1 => array($activityTypeId, 'Integer'),
1938 2 => array($contributionId, 'Integer'),
1939 3 => array($sourceID, 'Integer'),
1942 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1944 // for on behalf contribution source is individual and contributor is organization
1945 if ($sourceContactId && $sourceContactId != $contributorId) {
1946 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1947 // get rel type id for employee of relation
1948 foreach ($relationshipTypeIds as $id => $typeVals) {
1949 if ($typeVals['name_a_b'] == 'Employee of') {
1950 $relationshipTypeId = $id;
1955 $rel = new CRM_Contact_DAO_Relationship();
1956 $rel->relationship_type_id
= $relationshipTypeId;
1957 $rel->contact_id_a
= $sourceContactId;
1958 $rel->contact_id_b
= $contributorId;
1959 if ($rel->find(TRUE)) {
1960 $ids['individual_id'] = $rel->contact_id_a
;
1961 $ids['organization_id'] = $rel->contact_id_b
;
1972 public static function getContributionDates() {
1973 $config = CRM_Core_Config
::singleton();
1974 $currentMonth = date('m');
1975 $currentDay = date('d');
1976 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1977 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1978 (int ) $config->fiscalYearStart
['d'] > $currentDay
1981 $year = date('Y') - 1;
1986 $year = array('Y' => $year);
1987 $yearDate = $config->fiscalYearStart
;
1988 $yearDate = array_merge($year, $yearDate);
1989 $yearDate = CRM_Utils_Date
::format($yearDate);
1991 $monthDate = date('Ym') . '01';
1997 'yearDate' => $yearDate,
1998 'monthDate' => $monthDate,
2003 * Load objects relations to contribution object.
2004 * Objects are stored in the $_relatedObjects property
2005 * In the first instance we are just moving functionality from BASEIpn -
2006 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2008 * Note that the unit test for the BaseIPN class tests this function
2010 * @param array $input
2011 * Input as delivered from Payment Processor.
2013 * Ids as Loaded by Payment Processor.
2014 * @param bool $required
2015 * Is Payment processor / contribution page required.
2016 * @param bool $loadAll
2017 * Load all related objects - even where id not passed in? (allows API to call this).
2022 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
2024 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2025 if (empty($ids['contact']) && isset($this->contact_id
)) {
2026 $ids['contact'] = $this->contact_id
;
2029 if (empty($this->_component
)) {
2030 if (!empty($ids['event'])) {
2031 $this->_component
= 'event';
2034 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2037 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2038 $contributionType = new CRM_Financial_BAO_FinancialType();
2039 $contributionType->id
= $this->financial_type_id
;
2040 if (!$contributionType->find(TRUE)) {
2041 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2043 if (!empty($ids['contact'])) {
2044 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2045 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2046 $this->_relatedObjects
['contact']->find(TRUE);
2048 $this->_relatedObjects
['contributionType'] = $contributionType;
2050 if ($this->_component
== 'contribute') {
2051 // retrieve the other optional objects first so
2052 // stuff down the line can use this info and do things
2054 //in any case get the memberships associated with the contribution
2055 //because we now support multiple memberships w/ price set
2056 // see if there are any other memberships to be considered for same contribution.
2058 SELECT membership_id
2059 FROM civicrm_membership_payment
2060 WHERE contribution_id = %1 ";
2061 $params = array(1 => array($this->id
, 'Integer'));
2063 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2064 while ($dao->fetch()) {
2065 if ($dao->membership_id
) {
2066 if (!is_array($ids['membership'])) {
2067 $ids['membership'] = array();
2069 $ids['membership'][] = $dao->membership_id
;
2073 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2074 foreach ($ids['membership'] as $id) {
2076 $membership = new CRM_Member_BAO_Membership();
2077 $membership->id
= $id;
2078 if (!$membership->find(TRUE)) {
2079 throw new Exception("Could not find membership record: $id");
2081 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2082 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2083 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2084 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2085 $membership->free();
2090 if (!empty($ids['pledge_payment'])) {
2092 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2093 if (empty($paymentID)) {
2096 $payment = new CRM_Pledge_BAO_PledgePayment();
2097 $payment->id
= $paymentID;
2098 if (!$payment->find(TRUE)) {
2099 throw new Exception("Could not find pledge payment record: " . $paymentID);
2101 $this->_relatedObjects
['pledge_payment'][] = $payment;
2105 if (!empty($ids['contributionRecur'])) {
2106 $recur = new CRM_Contribute_BAO_ContributionRecur();
2107 $recur->id
= $ids['contributionRecur'];
2108 if (!$recur->find(TRUE)) {
2109 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2111 $this->_relatedObjects
['contributionRecur'] = &$recur;
2112 //get payment processor id from recur object.
2113 $paymentProcessorID = $recur->payment_processor_id
;
2115 //for normal contribution get the payment processor id.
2116 if (!$paymentProcessorID) {
2117 if ($this->contribution_page_id
) {
2118 // get the payment processor id from contribution page
2119 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2120 $this->contribution_page_id
,
2124 //fail to load payment processor id.
2125 elseif (empty($ids['pledge_payment'])) {
2126 $loadObjectSuccess = TRUE;
2128 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2130 return $loadObjectSuccess;
2135 // we are in event mode
2136 // make sure event exists and is valid
2137 $event = new CRM_Event_BAO_Event();
2138 $event->id
= $ids['event'];
2139 if ($ids['event'] &&
2142 throw new Exception("Could not find event: " . $ids['event']);
2145 $this->_relatedObjects
['event'] = &$event;
2147 $participant = new CRM_Event_BAO_Participant();
2148 $participant->id
= $ids['participant'];
2149 if ($ids['participant'] &&
2150 !$participant->find(TRUE)
2152 throw new Exception("Could not find participant: " . $ids['participant']);
2154 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2156 $this->_relatedObjects
['participant'] = &$participant;
2158 if (!$paymentProcessorID) {
2159 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2163 if ($paymentProcessorID) {
2164 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2165 $this->is_test ?
'test' : 'live'
2167 $ids['paymentProcessor'] = $paymentProcessorID;
2168 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2170 elseif ($required) {
2171 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2178 * Create array of message information - ie. return html version, txt version, to field
2180 * @param array $input
2181 * Incoming information.
2182 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2183 * just check presence of recur object but maintaining legacy approach
2186 * IDs of related objects.
2187 * @param array $values
2188 * Any values that may have already been compiled by calling process.
2189 * This is augmented by values 'gathered' by gatherMessageValues
2190 * @param bool $recur
2191 * @param bool $returnMessageText
2192 * Distinguishes between whether to send message or return.
2193 * message text. We are working towards this function ALWAYS returning message text & calling
2194 * function doing emails / pdfs with it
2200 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2201 if (empty($this->_relatedObjects
)) {
2202 $this->loadRelatedObjects($input, $ids);
2204 if (empty($this->_component
)) {
2205 $this->_component
= CRM_Utils_Array
::value('component', $input);
2208 //not really sure what params might be passed in but lets merge em into values
2209 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2210 $template = CRM_Core_Smarty
::singleton();
2211 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2212 //what does recur 'mean here - to do with payment processor return functionality but
2213 // what is the importance
2214 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2215 $paymentObject = &CRM_Core_Payment
::singleton(
2216 $this->is_test ?
'test' : 'live',
2217 $this->_relatedObjects
['paymentProcessor']
2220 $entityID = $entity = NULL;
2221 if (isset($ids['contribution'])) {
2222 $entity = 'contribution';
2223 $entityID = $ids['contribution'];
2225 if (!empty($ids['membership'])) {
2226 //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
2227 // 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
2228 // line having loaded an array
2229 $ids['membership'] = (array) $ids['membership'];
2230 $entity = 'membership';
2231 $entityID = $ids['membership'][0];
2234 $url = $paymentObject->subscriptionURL($entityID, $entity);
2235 $template->assign('cancelSubscriptionUrl', $url);
2237 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2238 $template->assign('updateSubscriptionBillingUrl', $url);
2240 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2241 $template->assign('updateSubscriptionUrl', $url);
2243 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2244 //direct mode showing billing block, so use directIPN for temporary
2245 $template->assign('contributeMode', 'directIPN');
2248 // todo remove strtolower - check consistency
2249 if (strtolower($this->_component
) == 'event') {
2250 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2251 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2255 $values['contribution_id'] = $this->id
;
2256 if (!empty($ids['related_contact'])) {
2257 $values['related_contact'] = $ids['related_contact'];
2258 if (isset($ids['onbehalf_dupe_alert'])) {
2259 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2261 $entityBlock = array(
2262 'contact_id' => $ids['contact'],
2263 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2264 'Home', 'id', 'name'
2267 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2268 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2271 if ($this->is_test
) {
2274 if (!empty($this->_relatedObjects
['membership'])) {
2275 foreach ($this->_relatedObjects
['membership'] as $membership) {
2276 if ($membership->id
) {
2277 $values['isMembership'] = TRUE;
2279 // need to set the membership values here
2280 $template->assign('membership_assign', 1);
2281 $template->assign('membership_name',
2282 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2284 $template->assign('mem_start_date', $membership->start_date
);
2285 $template->assign('mem_join_date', $membership->join_date
);
2286 $template->assign('mem_end_date', $membership->end_date
);
2287 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2288 $template->assign('mem_status', $membership_status);
2289 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2290 $template->assign('is_pay_later', 1);
2293 // if separate payment there are two contributions recorded and the
2294 // admin will need to send a receipt for each of them separately.
2295 // we dont link the two in the db (but can potentially infer it if needed)
2296 $template->assign('is_separate_payment', 0);
2298 if ($recur && $paymentObject) {
2299 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2300 $template->assign('cancelSubscriptionUrl', $url);
2301 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2302 $template->assign('updateSubscriptionBillingUrl', $url);
2303 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2304 $template->assign('updateSubscriptionUrl', $url);
2307 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2310 // otherwise if its about sending emails, continue sending without return, as we
2311 // don't want to exit the loop.
2316 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2322 * Gather values for contribution mail - this function has been created
2323 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2324 * Values related to the contribution in question are gathered
2326 * @param array $input
2327 * Input into function (probably from payment processor).
2328 * @param array $values
2330 * The set of ids related to the input.
2334 public function _gatherMessageValues($input, &$values, $ids = array()) {
2335 // set display address of contributor
2336 if ($this->address_id
) {
2337 $addressParams = array('id' => $this->address_id
);
2338 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2339 $addressDetails = array_values($addressDetails);
2340 $values['address'] = $addressDetails[0]['display'];
2342 if ($this->_component
== 'contribute') {
2343 if (isset($this->contribution_page_id
)) {
2344 CRM_Contribute_BAO_ContributionPage
::setValues(
2345 $this->contribution_page_id
,
2348 if ($this->contribution_page_id
) {
2349 // CRM-8254 - override default currency if applicable
2350 $config = CRM_Core_Config
::singleton();
2351 $config->defaultCurrency
= CRM_Utils_Array
::value(
2354 $config->defaultCurrency
2358 // no contribution page -probably back office
2360 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2361 $values['is_email_receipt'] = 1;
2362 $values['title'] = 'Contribution';
2364 // set lineItem for contribution
2366 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2367 if (!empty($lineItem)) {
2368 $itemId = key($lineItem);
2369 foreach ($lineItem as &$eachItem) {
2370 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2371 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2372 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2373 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2376 $values['lineItem'][0] = $lineItem;
2377 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2381 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2385 // if this is onbehalf of contribution then set related contact
2386 if (!empty($relatedContact['individual_id'])) {
2387 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2392 $eventParams = array(
2393 'id' => $this->_relatedObjects
['event']->id
,
2395 $values['event'] = array();
2397 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2399 //get location details
2400 $locationParams = array(
2401 'entity_id' => $this->_relatedObjects
['event']->id
,
2402 'entity_table' => 'civicrm_event',
2404 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2406 $ufJoinParams = array(
2407 'entity_table' => 'civicrm_event',
2408 'entity_id' => $ids['event'],
2409 'module' => 'CiviEvent',
2412 list($custom_pre_id,
2414 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2416 $values['custom_pre_id'] = $custom_pre_id;
2417 $values['custom_post_id'] = $custom_post_ids;
2419 // set lineItem for event contribution
2421 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2422 if (!empty($participantIds)) {
2423 foreach ($participantIds as $pIDs) {
2424 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2425 if (!CRM_Utils_System
::isNull($lineItem)) {
2426 $values['lineItem'][] = $lineItem;
2437 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2438 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2439 * Note we send directly from this function in some cases because it is only partly refactored
2440 * Don't call this function directly as the signature will change
2444 * @param CRM_Core_SMARTY $template
2445 * @param bool $recur
2446 * @param bool $returnMessageText
2450 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2451 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2452 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2453 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2454 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2455 $template->assign('useForMember', TRUE);
2457 //assign honor information to receipt message
2458 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2460 if (isset($softRecord['soft_credit'])) {
2461 //if id of contribution page is present
2462 if (!empty($values['id'])) {
2463 $values['honor'] = array(
2464 'honor_profile_values' => array(),
2465 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2466 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2468 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2470 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2471 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2474 //offline contribution
2475 $softCreditTypes = $softCredits = array();
2476 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2477 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2478 $softCredits[$key] = array(
2479 'Name' => $softCredit['contact_name'],
2480 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2483 $template->assign('softCreditTypes', $softCreditTypes);
2484 $template->assign('softCredits', $softCredits);
2488 $dao = new CRM_Contribute_DAO_ContributionProduct();
2489 $dao->contribution_id
= $this->id
;
2490 if ($dao->find(TRUE)) {
2491 $premiumId = $dao->product_id
;
2492 $template->assign('option', $dao->product_option
);
2494 $productDAO = new CRM_Contribute_DAO_Product();
2495 $productDAO->id
= $premiumId;
2496 $productDAO->find(TRUE);
2497 $template->assign('selectPremium', TRUE);
2498 $template->assign('product_name', $productDAO->name
);
2499 $template->assign('price', $productDAO->price
);
2500 $template->assign('sku', $productDAO->sku
);
2502 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2503 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2504 if (empty($amount) && isset($this->total_amount
)) {
2505 $amount = $this->total_amount
;
2507 $template->assign('amount', $amount);
2508 // add the new contribution values
2509 if (strtolower($this->_component
) == 'contribute') {
2511 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2512 $softDAO->contribution_id
= $this->id
;
2513 if ($softDAO->find(TRUE)) {
2514 $template->assign('pcpBlock', TRUE);
2515 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2516 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2517 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2519 //assign the pcp page title for email subject
2520 $pcpDAO = new CRM_PCP_DAO_PCP();
2521 $pcpDAO->id
= $softDAO->pcp_id
;
2522 if ($pcpDAO->find(TRUE)) {
2523 $template->assign('title', $pcpDAO->title
);
2528 if ($this->financial_type_id
) {
2529 $values['financial_type_id'] = $this->financial_type_id
;
2532 $template->assign('trxn_id', $this->trxn_id
);
2533 $template->assign('receive_date',
2534 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2536 $template->assign('contributeMode', 'notify');
2537 $template->assign('action', $this->is_test ?
1024 : 1);
2538 $template->assign('receipt_text',
2539 CRM_Utils_Array
::value('receipt_text',
2543 $template->assign('is_monetary', 1);
2544 $template->assign('is_recur', (bool) $recur);
2545 $template->assign('currency', $this->currency
);
2546 $template->assign('address', CRM_Utils_Address
::format($input));
2547 if ($this->_component
== 'event') {
2548 $template->assign('title', $values['event']['title']);
2549 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2550 $viewRoles = array();
2551 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2552 $viewRoles[] = $participantRoles[$v];
2554 $values['event']['participant_role'] = implode(', ', $viewRoles);
2555 $template->assign('event', $values['event']);
2556 $template->assign('location', $values['location']);
2557 $template->assign('customPre', $values['custom_pre_id']);
2558 $template->assign('customPost', $values['custom_post_id']);
2561 if ($this->_relatedObjects
['participant']->is_test
) {
2565 $values['params'] = array();
2566 //to get email of primary participant.
2567 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2568 $primaryAmount[] = array(
2569 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2570 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2572 //build an array of cId/pId of participants
2573 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2574 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2575 //send receipt to additional participant if exists
2576 if (count($additionalIDs)) {
2577 $template->assign('isPrimary', 0);
2578 $template->assign('customProfile', NULL);
2579 //set additionalParticipant true
2580 $values['params']['additionalParticipant'] = TRUE;
2581 foreach ($additionalIDs as $pId => $cId) {
2583 //to change the status pending to completed
2584 $additional = new CRM_Event_DAO_Participant();
2585 $additional->id
= $pId;
2586 $additional->contact_id
= $cId;
2587 $additional->find(TRUE);
2588 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2589 $additional->status_id
= 1;
2590 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2591 //if additional participant dont have email
2593 if (!$additionalParticipantInfo) {
2594 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2596 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2597 $primaryAmount[] = array(
2598 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2599 'amount' => $additional->fee_amount
,
2601 $additional->save();
2602 $additional->free();
2603 $template->assign('amount', $amount);
2604 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2608 //build an array of custom profile and assigning it to template
2609 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2611 if (count($customProfile)) {
2612 $template->assign('customProfile', $customProfile);
2615 // for primary contact
2616 $values['params']['additionalParticipant'] = FALSE;
2617 $template->assign('isPrimary', 1);
2618 $template->assign('amount', $primaryAmount);
2619 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2620 if ($this->payment_instrument_id
) {
2621 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2622 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2624 // carry paylater, since we did not created billing,
2625 // so need to pull email from primary location, CRM-4395
2626 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2632 * Check whether payment processor supports
2633 * cancellation of contribution subscription
2635 * @param int $contributionId
2638 * @param bool $isNotCancelled
2642 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2643 $cacheKeyString = "$contributionId";
2644 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2646 static $supportsCancel = array();
2648 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2649 $supportsCancel[$cacheKeyString] = FALSE;
2650 $isCancelled = FALSE;
2652 if ($isNotCancelled) {
2653 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2656 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2657 if (!empty($paymentObject)) {
2658 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2661 return $supportsCancel[$cacheKeyString];
2665 * Check whether subscription is already cancelled.
2667 * @param int $contributionId
2671 * contribution status
2673 public static function isSubscriptionCancelled($contributionId) {
2675 SELECT cr.contribution_status_id
2676 FROM civicrm_contribution_recur cr
2677 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2678 WHERE con.id = %1 LIMIT 1";
2679 $params = array(1 => array($contributionId, 'Integer'));
2680 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2681 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2682 if ($status == 'Cancelled') {
2689 * Create all financial accounts entry.
2691 * @param array $params
2692 * Contribution object, line item array and params for trxn.
2695 * @param array $financialTrxnValues
2697 * @return null|object
2699 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2700 $skipRecords = $update = $return = $isRelatedId = FALSE;
2702 $additionalParticipantId = array();
2703 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2705 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2706 $entityId = $params['participant_id'];
2707 $entityTable = 'civicrm_participant';
2708 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2710 elseif (!empty($params['membership_id'])) {
2711 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2712 // are created off one contribution should be handled elsewhere
2713 $entityId = $params['membership_id'];
2714 $entityTable = 'civicrm_membership';
2717 $entityId = $params['contribution']->id
;
2718 $entityTable = 'civicrm_contribution';
2721 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2722 $isRelatedId = TRUE;
2725 $entityID[] = $entityId;
2726 if (!empty($additionalParticipantId)) {
2727 $entityID +
= $additionalParticipantId;
2729 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2730 if (empty($params['prevContribution'])) {
2737 $statusId = $params['contribution']->contribution_status_id
;
2738 // CRM-13964 partial payment
2739 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2740 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2742 $partialAmtPay = $params['partial_amount_pay'];
2743 $partialAmtTotal = $params['partial_payment_total'];
2745 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2746 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2747 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2748 $params['total_amount'] = $partialAmtPay;
2750 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2751 if (empty($balanceTrxnInfo['trxn_id'])) {
2752 // create new balance transaction record
2753 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2754 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2756 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2757 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2758 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2759 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2760 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2761 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2762 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2763 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2764 $balanceTrxnParams['status_id'] = $statusId;
2765 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2766 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2767 if (!empty($params['payment_processor'])) {
2768 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2770 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2774 // build line item array if its not set in $params
2775 if (empty($params['line_item']) ||
$additionalParticipantId) {
2776 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2779 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2780 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2782 $skipRecords = TRUE;
2783 $pendingStatus = array(
2784 array_search('Pending', $contributionStatuses),
2785 array_search('In Progress', $contributionStatuses),
2787 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2788 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2789 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2791 elseif (!empty($params['payment_processor'])) {
2792 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2794 elseif (!empty($params['payment_instrument_id'])) {
2795 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2798 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2799 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2800 $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);
2803 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2804 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2805 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2808 //build financial transaction params
2809 $trxnParams = array(
2810 'contribution_id' => $params['contribution']->id
,
2811 'to_financial_account_id' => $params['to_financial_account_id'],
2812 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2813 'total_amount' => $totalAmount,
2814 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2815 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2816 'currency' => $params['contribution']->currency
,
2817 'trxn_id' => $params['contribution']->trxn_id
,
2818 'status_id' => $statusId,
2819 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2820 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2823 if (!empty($params['payment_processor'])) {
2824 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2827 if (isset($fromFinancialAccountId)) {
2828 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2831 // consider external values passed for recording transaction entry
2832 if (!empty($financialTrxnValues)) {
2833 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2836 $params['trxnParams'] = $trxnParams;
2838 if (!empty($params['prevContribution'])) {
2839 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2840 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2841 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2842 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2843 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2845 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2846 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2847 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2849 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2850 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2853 //if financial type is changed
2854 if (!empty($params['financial_type_id']) &&
2855 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2857 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2858 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2859 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2860 if ($oldFinancialAccount != $newFinancialAccount) {
2861 $params['total_amount'] = 0;
2862 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2863 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2864 $params['prevContribution']->financial_type_id
, $relationTypeId);
2867 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2868 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2869 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2872 self
::updateFinancialAccounts($params, 'changeFinancialType');
2873 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2874 $params['financial_account_id'] = $newFinancialAccount;
2875 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2876 self
::updateFinancialAccounts($params);
2877 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2881 //Update contribution status
2882 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2883 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2884 if (!empty($params['contribution_status_id']) &&
2885 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2887 //Update Financial Records
2888 self
::updateFinancialAccounts($params, 'changedStatus');
2891 // change Payment Instrument for a Completed contribution
2892 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2893 // instrument is null and now new payment instrument is added along with the payment
2894 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2895 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2896 if (array_key_exists('payment_instrument_id', $params)) {
2897 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2898 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2899 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2901 //check if status is changed from Pending to Completed
2902 // do not update payment instrument changes for Pending to Completed
2903 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2904 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2906 // for all other statuses create new financial records
2907 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2908 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2909 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2912 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2913 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2914 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2916 // for any other payment instrument changes create new financial records
2917 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2918 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2919 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2921 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2922 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2924 // another special case when check number is changed, create new financial records
2925 // create financial trxn with negative amount
2926 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2927 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2928 // create financial trxn with positive amount
2929 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2930 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2931 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2935 //if Change contribution amount
2936 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2937 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2938 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2939 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2940 if (isset($totalAmount) &&
2941 $totalAmount != $params['prevContribution']->total_amount
2943 //Update Financial Records
2944 $params['trxnParams']['from_financial_account_id'] = NULL;
2945 self
::updateFinancialAccounts($params, 'changedAmount');
2950 // records finanical trxn and entity financial trxn
2951 // also make it available as return value
2952 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2953 $params['entity_id'] = $financialTxn->id
;
2956 // record line items and finacial items
2957 if (empty($params['skipLineItem'])) {
2958 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2961 // create batch entry if batch_id is passed and
2962 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
2963 if (!empty($params['batch_id']) && !empty($financialTxn)) {
2964 $entityParams = array(
2965 'batch_id' => $params['batch_id'],
2966 'entity_table' => 'civicrm_financial_trxn',
2967 'entity_id' => $financialTxn->id
,
2969 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2972 // when a fee is charged
2973 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2974 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2977 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2978 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2980 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2981 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2982 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2984 unset($params['line_item']);
2990 * Update all financial accounts entry.
2992 * @param array $params
2993 * Contribution object, line item array and params for trxn.
2995 * @param string $context
2998 * @param null $skipTrxn
3001 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3002 $itemAmount = $trxnID = NULL;
3003 //get all the statuses
3004 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3005 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3006 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3007 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3008 && $context == 'changePaymentInstrument'
3012 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3013 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3015 if ($context == 'changedStatus') {
3016 //get all the statuses
3017 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3019 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3020 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3021 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3023 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3024 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3025 $creditNoteId = self
::createCreditNoteId();
3026 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3029 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3030 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3032 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3033 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3034 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3036 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3037 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3038 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3039 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3040 $creditNoteId = self
::createCreditNoteId();
3041 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3045 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3048 $itemAmount = $params['trxnParams']['total_amount'];
3050 elseif ($context == 'changePaymentInstrument') {
3051 if ($params['trxnParams']['total_amount'] < 0) {
3052 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3053 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3054 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3055 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3059 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3060 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3063 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3064 $params['entity_id'] = $trxn->id
;
3066 if ($context == 'changedStatus') {
3067 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3068 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3069 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3071 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3072 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3074 $entityParams = array(
3075 'entity_table' => 'civicrm_financial_item',
3076 'financial_trxn_id' => $trxn->id
,
3078 if (empty($params['line_item'])) {
3080 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3081 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3082 // & this can be removed
3085 foreach ($params['line_item'] as $fieldId => $fields) {
3086 foreach ($fields as $fieldValueId => $fieldValues) {
3088 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3089 2 => array($fieldValues['id'], 'Integer'),
3091 CRM_Core_DAO
::executeQuery($query, $fparams);
3093 1 => array($fieldValues['id'], 'Integer'),
3095 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3096 while ($financialItem->fetch()) {
3097 $entityParams['entity_id'] = $financialItem->id
;
3098 $entityParams['amount'] = $financialItem->amount
;
3099 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3106 if ($context != 'changePaymentInstrument') {
3107 $itemParams['entity_table'] = 'civicrm_line_item';
3108 $trxnIds['id'] = $params['entity_id'];
3109 foreach ($params['line_item'] as $fieldId => $fields) {
3110 foreach ($fields as $fieldValueId => $fieldValues) {
3111 $prevParams['entity_id'] = $fieldValues['id'];
3112 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3114 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3115 if ($params['contribution']->receive_date
) {
3116 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3119 $financialAccount = $prevfinancialItem->financial_account_id
;
3120 if (!empty($params['financial_account_id'])) {
3121 $financialAccount = $params['financial_account_id'];
3124 $currency = $params['prevContribution']->currency
;
3125 if ($params['contribution']->currency
) {
3126 $currency = $params['contribution']->currency
;
3129 if (!empty($params['is_quick_config'])) {
3130 $amount = $itemAmount;
3132 $amount = $params['total_amount'];
3136 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3137 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3141 $amount = $diff * $fieldValues['line_total'];
3144 $itemParams = array(
3145 'transaction_date' => $receiveDate,
3146 'contact_id' => $params['prevContribution']->contact_id
,
3147 'currency' => $currency,
3148 'amount' => $amount,
3149 'description' => $prevfinancialItem->description
,
3150 'status_id' => $prevfinancialItem->status_id
,
3151 'financial_account_id' => $financialAccount,
3152 'entity_table' => 'civicrm_line_item',
3153 'entity_id' => $fieldValues['id'],
3155 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3157 if ($fieldValues['tax_amount']) {
3158 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3159 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3160 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3161 $itemParams['description'] = $taxTerm;
3162 if ($fieldValues['financial_type_id']) {
3163 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3165 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3170 if ($context == 'changeFinancialType') {
3171 $params['skipLineItem'] = FALSE;
3172 foreach ($params['line_item'] as &$lineItems) {
3173 foreach ($lineItems as &$line) {
3174 $line['financial_type_id'] = $params['financial_type_id'];
3181 * Check status validation on update of a contribution.
3183 * @param array $values
3184 * Previous form values before submit.
3186 * @param array $fields
3187 * The input form values.
3189 * @param array $errors
3194 public static function checkStatusValidation($values, &$fields, &$errors) {
3195 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3196 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3197 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3201 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3202 $checkStatus = array(
3203 'Cancelled' => array('Completed', 'Refunded'),
3204 'Completed' => array('Cancelled', 'Refunded'),
3205 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3206 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3207 'Refunded' => array('Cancelled', 'Completed'),
3210 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3211 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3212 1 => $contributionStatuses[$values['contribution_status_id']],
3213 2 => $contributionStatuses[$fields['contribution_status_id']],
3219 * Delete contribution of contact.
3223 * @param int $contactId
3227 public static function deleteContactContribution($contactId) {
3228 $contribution = new CRM_Contribute_DAO_Contribution();
3229 $contribution->contact_id
= $contactId;
3230 $contribution->find();
3231 while ($contribution->fetch()) {
3232 self
::deleteContribution($contribution->id
);
3237 * Get options for a given contribution field.
3238 * @see CRM_Core_DAO::buildOptions
3240 * @param string $fieldName
3241 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3242 * @param array $props whatever is known about this dao object.
3244 * @return array|bool
3246 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3247 $className = __CLASS__
;
3249 switch ($fieldName) {
3250 // This field is not part of this object but the api supports it
3251 case 'payment_processor':
3252 $className = 'CRM_Contribute_BAO_ContributionPage';
3253 // Filter results by contribution page
3254 if (!empty($props['contribution_page_id'])) {
3255 $page = civicrm_api('contribution_page', 'getsingle', array(
3257 'id' => ($props['contribution_page_id']),
3259 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3260 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3264 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3265 case 'honor_type_id':
3266 $className = 'CRM_Contribute_BAO_ContributionSoft';
3267 $fieldName = 'soft_credit_type_id';
3268 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3271 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3275 * Validate financial type.
3279 * @param int $financialTypeId
3280 * Financial Type id.
3282 * @param string $relationName
3284 * @return array|bool
3286 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3287 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3288 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3290 if (!$financialAccount) {
3291 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3298 * Function to record additional payment for partial and refund contributions.
3300 * @param int $contributionId
3301 * is the invoice contribution id (got created after processing participant payment).
3302 * @param array $trxnsData
3303 * to take user provided input of transaction details.
3304 * @param string $paymentType
3305 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3306 * @param int $participantId
3308 * @return null|object
3310 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3311 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3312 $getInfoOf['id'] = $contributionId;
3313 $defaults = array();
3314 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3316 if ($paymentType == 'owed') {
3317 // build params for recording financial trxn entry
3318 $params['contribution'] = $contributionDAO;
3319 $params = array_merge($defaults, $params);
3320 $params['skipLineItem'] = TRUE;
3321 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3322 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3323 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3324 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3327 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3328 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3329 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3331 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3332 if (!empty($trxnId)) {
3333 $trxnId = $trxnId['trxn_id'];
3335 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3336 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3339 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3340 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3341 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3345 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3346 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3347 FROM civicrm_financial_trxn ft
3348 LEFT JOIN civicrm_entity_financial_trxn eft
3349 ON (ft.id = eft.financial_trxn_id)
3350 WHERE eft.entity_table = 'civicrm_contribution'
3351 AND eft.entity_id = {$contributionId}
3352 AND ft.to_financial_account_id != {$toFinancialAccount}
3353 AND ft.status_id = {$statusId}
3355 $query = CRM_Core_DAO
::executeQuery($sql);
3357 $sumOfPayments = $query->sum_of_payments
;
3360 if ($contributionDAO->total_amount
== $sumOfPayments) {
3361 // update contribution status and
3362 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3363 $contributionDAO->contribution_status_id
= $statusId;
3364 $contributionDAO->cancel_date
= 'null';
3365 $contributionDAO->cancel_reason
= NULL;
3366 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3367 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3368 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3369 $contributionDAO->save();
3371 //Change status of financial record too
3372 $financialTrxn->status_id
= $statusId;
3373 $financialTrxn->save();
3375 // note : not using the self::add method,
3376 // the reason because it performs 'status change' related code execution for financial records
3377 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3378 // are coded below i.e. just updating financial_item status to 'Paid'
3380 if ($participantId) {
3381 // update participant status
3382 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3383 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3384 foreach ($ids as $val) {
3385 $participantUpdate['id'] = $val;
3386 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3387 CRM_Event_BAO_Participant
::add($participantUpdate);
3391 // update financial item statuses
3392 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3393 $paidStatus = array_search('Paid', $financialItemStatus);
3395 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3396 $sqlFinancialItemUpdate = "
3397 UPDATE civicrm_financial_item fi
3398 LEFT JOIN civicrm_entity_financial_trxn eft
3399 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3400 SET status_id = {$paidStatus}
3401 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3403 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3406 elseif ($paymentType == 'refund') {
3407 // build params for recording financial trxn entry
3408 $params['contribution'] = $contributionDAO;
3409 $params = array_merge($defaults, $params);
3410 $params['skipLineItem'] = TRUE;
3411 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3412 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3414 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3415 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3416 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3418 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3420 // note : not using the self::add method,
3421 // the reason because it performs 'status change' related code execution for financial records
3422 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3423 // are coded below i.e. just updating financial_item status to 'Paid'
3424 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3426 // add financial item entry
3427 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3428 $getLine['entity_id'] = $contributionDAO->id
;
3429 $getLine['entity_table'] = 'civicrm_contribution';
3430 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3431 if (!empty($lineItemId->id
)) {
3432 $addFinancialEntry = array(
3433 'transaction_date' => $financialTrxn->trxn_date
,
3434 'contact_id' => $contributionDAO->contact_id
,
3435 'amount' => $financialTrxn->total_amount
,
3436 'status_id' => array_search('Paid', $financialItemStatus),
3437 'entity_id' => $lineItemId->id
,
3438 'entity_table' => 'civicrm_line_item',
3440 $trxnIds['id'] = $financialTrxn->id
;
3441 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3443 if ($participantId) {
3444 // update participant status
3445 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3446 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3447 foreach ($ids as $val) {
3448 $participantUpdate['id'] = $val;
3449 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3450 CRM_Event_BAO_Participant
::add($participantUpdate);
3455 // activity creation
3456 if (!empty($financialTrxn)) {
3457 if ($participantId) {
3458 $inputParams['id'] = $participantId;
3461 $component = 'event';
3462 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3463 $entityObj = $entityObj[$participantId];
3465 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3467 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3469 return $financialTrxn;
3475 * @param $activityType
3477 * @param int $contributionId
3479 * @throws CRM_Core_Exception
3481 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3482 if ($component == 'event') {
3483 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3484 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3485 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3486 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3487 $targetCid = $entityObj->contact_id
;
3488 // source record id would be the contribution id
3489 $srcRecId = $contributionId;
3493 $activityParams = array(
3494 'source_contact_id' => $targetCid,
3495 'source_record_id' => $srcRecId,
3496 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3500 'subject' => $subject,
3501 'activity_date_time' => $date,
3502 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3506 'skipRecentView' => TRUE,
3509 // create activity with target contacts
3510 $session = CRM_Core_Session
::singleton();
3511 $id = $session->get('userID');
3513 $activityParams['source_contact_id'] = $id;
3514 $activityParams['target_contact_id'][] = $targetCid;
3516 CRM_Activity_BAO_Activity
::create($activityParams);
3520 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3524 * @param bool $getTrxnInfo
3525 * @param bool $usingLineTotal
3529 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3530 if ($component == 'event') {
3531 $entity = 'participant';
3532 $entityTable = 'civicrm_participant';
3533 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3535 if (!$contributionId) {
3536 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3537 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3538 $id = $primaryParticipantId;
3540 if (!$contributionId) {
3545 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3546 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3552 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3553 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3556 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3557 // for additional participants
3558 if ($entityTable == 'civicrm_participant') {
3559 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3561 foreach ($ids as $val) {
3562 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3566 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3570 $baseTrxnId = $total['trxn_id'];
3571 $total = $total['total_amount'];
3574 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3575 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3577 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3578 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3579 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3581 if ($paymentBalance == 0 && $contributionIsPayLater) {
3582 $paymentBalance = $total;
3585 $info['total'] = $total;
3586 $info['paid'] = $total - $paymentBalance;
3587 $info['balance'] = $paymentBalance;
3589 $info['component'] = $component;
3590 $info['payLater'] = $contributionIsPayLater;
3592 if ($getTrxnInfo && $baseTrxnId) {
3593 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3595 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3596 FROM civicrm_contribution con
3597 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3598 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3599 WHERE con.id = {$contributionId}
3602 // conditioned WHERE clause
3604 // if balance trxn exists don't include details of it in transaction info
3605 $sql .= " AND ft.id != {$baseTrxnId} ";
3607 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3609 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3610 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3611 while ($resultDAO->fetch()) {
3612 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3613 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3615 'total_amount' => $resultDAO->total_amount
,
3616 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3617 'payment_instrument' => $paidByLabel,
3618 'receive_date' => $resultDAO->trxn_date
,
3619 'trxn_id' => $resultDAO->trxn_id
,
3620 'status' => $statuses[$resultDAO->status_id
],
3622 if ($paidByName == 'Check') {
3623 $val['check_number'] = $resultDAO->check_number
;
3627 $info['transaction'] = $rows;
3633 * Get financial account id has 'Sales Tax Account is'
3634 * account relationship with financial type
3636 * @param int $financialTypeId
3638 * @return FinancialAccountId
3640 public static function getFinancialAccountId($financialTypeId) {
3641 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3642 $searchParams = array(
3643 'entity_table' => 'civicrm_financial_type',
3644 'entity_id' => $financialTypeId,
3645 'account_relationship' => $accountRel,
3648 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3650 return CRM_Utils_Array
::value('financial_account_id', $result);
3656 * @param array $params
3657 * @param bool $isLineItem
3661 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3662 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3664 // Update contribution.
3665 if (!empty($params['id'])) {
3666 $id = $params['id'];
3667 $values = $ids = array();
3668 $contrbutionParams = array('id' => $id);
3669 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3671 // To assign pervious finantial type on update of contribution
3672 if (!isset($params['financial_type_id'])) {
3673 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3675 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3676 // Assisn tax Amount on update of contrbution
3677 if (!empty($prevContributionValue->tax_amount
)) {
3678 $params['tax_amount'] = 'null';
3679 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3680 foreach ($params['line_item'] as $setID => $priceField) {
3681 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3682 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3689 // New Contrbution and update of contribution with tax rate financial type
3690 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3691 empty($params['skipLineItem']) && !$isLineItem
3693 $taxRateParams = $taxRates[$params['financial_type_id']];
3694 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3695 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3697 // Get Line Item on update of contribution
3698 if (isset($params['id'])) {
3699 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3702 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3704 foreach ($params['line_item'] as $setID => $priceField) {
3705 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3706 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3709 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3711 elseif (isset($params['api.line_item.create'])) {
3712 // Update total amount of contribution using lineItem
3713 $taxAmountArray = array();
3714 foreach ($params['api.line_item.create'] as $key => $value) {
3715 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3716 $taxRate = $taxRates[$value['financial_type_id']];
3717 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3718 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3721 $params['tax_amount'] = array_sum($taxAmountArray);
3722 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3725 // update line item of contrbution
3726 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3727 $taxRate = $taxRates[$params['financial_type_id']];
3728 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3729 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3736 * Check financial type validation on update of a contribution.
3738 * @param Integer $financialTypeId
3739 * Value of latest Financial Type.
3741 * @param Integer $contributionId
3744 * @param array $errors
3749 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3750 if (!empty($financialTypeId)) {
3751 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3752 if ($oldFinancialTypeId == $financialTypeId) {
3756 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3758 '1' => array($contributionId, 'Integer'),
3760 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3761 if ($result->N
> 1) {
3762 $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.');
3767 * Generate credit note id with next avaible number
3772 public static function createCreditNoteId() {
3773 $prefixValue = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3775 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
3776 $creditNoteId = NULL;
3780 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
3781 $result = civicrm_api3('Contribution', 'getcount', array(
3783 'creditnote_id' => $creditNoteId,
3785 } while ($result > 0);
3787 return $creditNoteId;