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 //set defaults in create mode
139 if (!$contributionID) {
140 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
141 self
::calculateMissingAmountParams($params);
144 if (!empty($params['payment_instrument_id'])) {
145 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
146 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
147 $params['check_number'] = 'null';
151 $setPrevContribution = TRUE;
152 // CRM-13964 partial payment
153 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
154 $partialAmtTotal = $params['partial_payment_total'];
155 $partialAmtPay = $params['partial_amount_pay'];
156 $params['total_amount'] = $partialAmtTotal;
157 if ($partialAmtPay < $partialAmtTotal) {
158 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
159 $params['is_pay_later'] = 0;
160 $setPrevContribution = FALSE;
164 if ($contributionID) {
165 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
168 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
170 $contribution = new CRM_Contribute_BAO_Contribution();
171 $contribution->copyValues($params);
173 $contribution->id
= $contributionID;
175 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
176 $config = CRM_Core_Config
::singleton();
177 $contribution->currency
= $config->defaultCurrency
;
180 if ($contributionID && $setPrevContribution) {
181 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
184 $result = $contribution->save();
186 // Add financial_trxn details as part of fix for CRM-4724
187 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
188 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
190 //add Account details
191 $params['contribution'] = $contribution;
192 self
::recordFinancialAccounts($params);
194 // reset the group contact cache for this group
195 CRM_Contact_BAO_GroupContactCache
::remove();
197 if ($contributionID) {
198 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
201 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
208 * Get defaults for new entity.
211 public static function getDefaults() {
213 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
214 FALSE, FALSE, FALSE, 'AND is_default = 1')
216 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
221 * Given the list of params in the params array, fetch the object
222 * and store the values in the values array
224 * @param array $params
225 * Input parameters to find object.
226 * @param array $values
227 * Output values of the object.
229 * The array that holds all the db ids.
231 * @return CRM_Contribute_BAO_Contribution|null the found object or null
233 public static function &getValues($params, &$values, &$ids) {
234 if (empty($params)) {
237 $contribution = new CRM_Contribute_BAO_Contribution();
239 $contribution->copyValues($params);
241 if ($contribution->find(TRUE)) {
242 $ids['contribution'] = $contribution->id
;
244 CRM_Core_DAO
::storeValues($contribution, $values);
246 return $contribution;
248 $null = NULL; // return by reference
253 * Calculate net_amount & fee_amount if they are not set.
255 * Net amount should be total - fee.
256 * This should only be called for new contributions.
258 * @param array $params
259 * Params for a new contribution before they are saved.
261 public static function calculateMissingAmountParams(&$params) {
262 if (!isset($params['fee_amount'])) {
263 if (isset($params['total_amount']) && isset($params['net_amount'])) {
264 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
267 $params['fee_amount'] = 0;
270 if (!isset($params['net_amount'])) {
271 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
276 * Get the number of terms for this contribution for a given membership type
277 * based on querying the line item table and relevant price field values
278 * Note that any one contribution should only be able to have one line item relating to a particular membership
281 * @param int $membershipTypeID
283 * @param int $contributionID
287 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
288 $numTerms = CRM_Core_DAO
::singleValueQuery("
289 SELECT membership_num_terms FROM civicrm_line_item li
290 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
291 WHERE contribution_id = %1 AND membership_type_id = %2",
292 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
294 // default of 1 is precautionary
295 return empty($numTerms) ?
1 : $numTerms;
299 * Takes an associative array and creates a contribution object.
301 * @param array $params
302 * (reference ) an assoc array of name/value pairs.
304 * The array that holds all the db ids.
306 * @return CRM_Contribute_BAO_Contribution
308 public static function create(&$params, $ids = array()) {
309 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
310 foreach ($dateFields as $df) {
311 if (isset($params[$df])) {
312 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
316 $transaction = new CRM_Core_Transaction();
318 $contribution = self
::add($params, $ids);
320 if (is_a($contribution, 'CRM_Core_Error')) {
321 $transaction->rollback();
322 return $contribution;
325 $params['contribution_id'] = $contribution->id
;
327 if (!empty($params['custom']) &&
328 is_array($params['custom'])
330 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
333 $session = CRM_Core_Session
::singleton();
335 if (!empty($params['note'])) {
337 'entity_table' => 'civicrm_contribution',
338 'note' => $params['note'],
339 'entity_id' => $contribution->id
,
340 'contact_id' => $session->get('userID'),
341 'modified_date' => date('Ymd'),
343 if (!$noteParams['contact_id']) {
344 $noteParams['contact_id'] = $params['contact_id'];
346 CRM_Core_BAO_Note
::add($noteParams);
349 // make entry in batch entity batch table
350 if (!empty($params['batch_id'])) {
351 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
352 $titleFields = array(
358 $retrieveRequired = 0;
359 foreach ($titleFields as $titleField) {
360 if (!isset($contribution->$titleField)) {
361 $retrieveRequired = 1;
365 if ($retrieveRequired == 1) {
366 $contribution->find(TRUE);
370 // Handle soft credit and / or link to personal campaign page
371 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
373 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
375 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
376 $softParams = array();
377 $softParams['id'] = $pcpId ?
$pcpId : NULL;
378 $softParams['contribution_id'] = $contribution->id
;
379 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
380 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
381 $pcp['pcp_made_through_id'], 'contact_id'
383 $softParams['currency'] = $contribution->currency
;
384 $softParams['amount'] = $contribution->total_amount
;
385 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
386 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
387 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
388 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
389 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
390 //Send notification to owner for PCP
391 if ($contributionSoft->pcp_id
&& empty($pcpId)) {
392 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
395 //Delete PCP against this contribution and create new on submitted PCP information
396 elseif (array_key_exists('pcp', $params) && $pcpId) {
397 $deleteParams = array('id' => $pcpId);
398 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
400 if (isset($params['soft_credit'])) {
401 $softParams = $params['soft_credit'];
402 foreach ($softParams as $softParam) {
403 if (!empty($softIDs)) {
404 $key = key($softIDs);
405 $softParam['id'] = $softIDs[$key];
406 unset($softIDs[$key]);
408 $softParam['contribution_id'] = $contribution->id
;
409 $softParam['currency'] = $contribution->currency
;
410 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
411 if (empty($softParam['amount'])) {
412 $softParam['amount'] = $contribution->total_amount
;
414 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
417 if (!empty($softIDs)) {
418 foreach ($softIDs as $softID) {
419 if (!in_array($softID, $params['soft_credit_ids'])) {
420 $deleteParams = array('id' => $softID);
421 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
427 $transaction->commit();
429 // check if activity record exist for this contribution, if
431 $activity = new CRM_Activity_DAO_Activity();
432 $activity->source_record_id
= $contribution->id
;
433 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
437 if (!$activity->find(TRUE)) {
438 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
441 // CRM-13237 : if activity record found, update it with campaign id of contribution
442 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
445 // do not add to recent items for import, CRM-4399
446 if (empty($params['skipRecentView'])) {
447 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
448 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
450 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
451 $titleFields = array(
457 $retrieveRequired = 0;
458 foreach ($titleFields as $titleField) {
459 if (!isset($contribution->$titleField)) {
460 $retrieveRequired = 1;
464 if ($retrieveRequired == 1) {
465 $contribution->find(TRUE);
467 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
468 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
470 $recentOther = array();
471 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
472 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
473 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
477 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
478 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
479 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
483 // add the recently created Contribution
484 CRM_Utils_Recent
::add($title,
488 $contribution->contact_id
,
494 return $contribution;
498 * Get the values for pseudoconstants for name->value and reverse.
500 * @param array $defaults
501 * (reference) the default values, some of which need to be resolved.
502 * @param bool $reverse
503 * True if we want to resolve the values in the reverse direction (value -> name).
507 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
508 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
509 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
510 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
511 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
515 * Convert associative array names to values and vice-versa.
517 * This function is used by both the web form layer and the api. Note that
518 * the api needs the name => value conversion, also the view layer typically
519 * requires value => name conversion
521 * @param array $defaults
522 * @param string $property
523 * @param array $lookup
524 * @param bool $reverse
528 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
529 $id = $property . '_id';
531 $src = $reverse ?
$property : $id;
532 $dst = $reverse ?
$id : $property;
534 if (!array_key_exists($src, $defaults)) {
538 $look = $reverse ?
array_flip($lookup) : $lookup;
540 if (is_array($look)) {
541 if (!array_key_exists($defaults[$src], $look)) {
545 $defaults[$dst] = $look[$defaults[$src]];
550 * Retrieve DB object based on input parameters.
552 * It also stores all the retrieved values in the default array.
554 * @param array $params
555 * (reference ) an assoc array of name/value pairs.
556 * @param array $defaults
557 * (reference ) an assoc array to hold the name / value pairs.
558 * in a hierarchical manner
560 * (reference) the array that holds all the db ids.
562 * @return CRM_Contribute_BAO_Contribution
564 public static function retrieve(&$params, &$defaults, &$ids) {
565 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
566 return $contribution;
570 * Combine all the importable fields from the lower levels object.
572 * The ordering is important, since currently we do not have a weight
573 * scheme. Adding weight is super important and should be done in the
574 * next week or so, before this can be called complete.
576 * @param string $contactType
577 * @param bool $status
580 * array of importable Fields
582 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
583 if (!self
::$_importableFields) {
584 if (!self
::$_importableFields) {
585 self
::$_importableFields = array();
589 $fields = array('' => array('title' => ts('- do not import -')));
592 $fields = array('' => array('title' => ts('- Contribution Fields -')));
595 $note = CRM_Core_DAO_Note
::import();
596 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
597 unset($tmpFields['option_value']);
598 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
599 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
601 // Using new Dedupe rule.
603 'contact_type' => $contactType,
604 'used' => 'Unsupervised',
606 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
607 $tmpContactField = array();
608 if (is_array($fieldsArray)) {
609 foreach ($fieldsArray as $value) {
610 //skip if there is no dupe rule
611 if ($value == 'none') {
614 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
619 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
620 $tmpContactField[trim($value)] = $contactFields[trim($value)];
622 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
625 $title = $tmpContactField[trim($value)]['title'];
627 $tmpContactField[trim($value)]['title'] = $title;
631 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
632 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
633 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
634 $fields = array_merge($fields, $tmpContactField);
635 $fields = array_merge($fields, $tmpFields);
636 $fields = array_merge($fields, $note);
637 $fields = array_merge($fields, $optionFields);
638 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
639 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
640 self
::$_importableFields = $fields;
642 return self
::$_importableFields;
648 public static function &exportableFields() {
649 if (!self
::$_exportableFields) {
650 if (!self
::$_exportableFields) {
651 self
::$_exportableFields = array();
654 $impFields = CRM_Contribute_DAO_Contribution
::export();
655 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
656 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
657 $typeField = CRM_Financial_DAO_FinancialType
::export();
658 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
659 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
660 $contributionStatus = array(
661 'contribution_status' => array(
662 'title' => ts('Contribution Status'),
663 'name' => 'contribution_status',
664 'data_type' => CRM_Utils_Type
::T_STRING
,
668 $contributionPage = array(
669 'contribution_page' => array(
670 'title' => ts('Contribution Page'),
671 'name' => 'contribution_page',
672 'where' => 'civicrm_contribution_page.title',
673 'data_type' => CRM_Utils_Type
::T_STRING
,
677 $contributionNote = array(
678 'contribution_note' => array(
679 'title' => ts('Contribution Note'),
680 'name' => 'contribution_note',
681 'data_type' => CRM_Utils_Type
::T_TEXT
,
685 $contributionRecurId = array(
686 'contribution_recur_id' => array(
687 'title' => ts('Recurring Contributions ID'),
688 'name' => 'contribution_recur_id',
689 'where' => 'civicrm_contribution.contribution_recur_id',
690 'data_type' => CRM_Utils_Type
::T_INT
,
694 $extraFields = array(
695 'contribution_batch' => array(
696 'title' => ts('Batch Name'),
700 $softCreditFields = array(
701 'contribution_soft_credit_name' => array(
702 'name' => 'contribution_soft_credit_name',
703 'title' => 'Soft Credit For',
704 'where' => 'civicrm_contact_d.display_name',
705 'data_type' => CRM_Utils_Type
::T_STRING
,
707 'contribution_soft_credit_amount' => array(
708 'name' => 'contribution_soft_credit_amount',
709 'title' => 'Soft Credit Amount',
710 'where' => 'civicrm_contribution_soft.amount',
711 'data_type' => CRM_Utils_Type
::T_MONEY
,
713 'contribution_soft_credit_type' => array(
714 'name' => 'contribution_soft_credit_type',
715 'title' => 'Soft Credit Type',
716 'where' => 'contribution_softcredit_type.label',
717 'data_type' => CRM_Utils_Type
::T_STRING
,
719 'contribution_soft_credit_contribution_id' => array(
720 'name' => 'contribution_soft_credit_contribution_id',
721 'title' => 'Soft Credit For Contribution ID',
722 'where' => 'civicrm_contribution_soft.contribution_id',
723 'data_type' => CRM_Utils_Type
::T_INT
,
727 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
728 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
729 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
732 self
::$_exportableFields = $fields;
735 return self
::$_exportableFields;
739 * @param null $status
740 * @param null $startDate
741 * @param null $endDate
745 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
749 $where[] = 'contribution_status_id = 1';
753 $where[] = 'contribution_status_id = 3';
758 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
761 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
764 $whereCond = implode(' AND ', $where);
767 SELECT sum( total_amount ) as total_amount,
768 count( civicrm_contribution.id ) as total_count,
770 FROM civicrm_contribution
771 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
773 AND ( is_test = 0 OR is_test IS NULL )
774 AND contact.is_deleted = 0
778 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
781 while ($dao->fetch()) {
782 $count +
= $dao->total_count
;
783 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
787 'amount' => implode(', ', $amount),
795 * Delete the indirect records associated with this contribution first.
800 * $results no of deleted Contribution on success, false otherwise
802 public static function deleteContribution($id) {
803 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
805 $transaction = new CRM_Core_Transaction();
808 //delete activity record
810 'source_record_id' => $id,
811 // activity type id for contribution
812 'activity_type_id' => 6,
815 CRM_Activity_BAO_Activity
::deleteActivity($params);
817 //delete billing address if exists for this contribution.
818 self
::deleteAddress($id);
820 //update pledge and pledge payment, CRM-3961
821 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
823 // remove entry from civicrm_price_set_entity, CRM-5095
824 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
825 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
827 // cleanup line items.
828 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
830 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
831 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
833 if ($participantId) {
834 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
837 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
841 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
842 $noteId = key($note);
844 CRM_Core_BAO_Note
::del($noteId, FALSE);
847 $dao = new CRM_Contribute_DAO_Contribution();
850 $results = $dao->delete();
852 $transaction->commit();
854 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
856 // delete the recently created Contribution
857 $contributionRecent = array(
859 'type' => 'Contribution',
861 CRM_Utils_Recent
::del($contributionRecent);
867 * Check if there is a contribution with the same trxn_id or invoice_id.
869 * @param array $input
870 * An assoc array of name/value pairs.
871 * @param array $duplicates
872 * (reference) store ids of duplicate contribs.
876 * true if duplicate, false otherwise
878 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
880 $id = CRM_Utils_Array
::value('id', $input);
882 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
883 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
889 $clause[] = "trxn_id = %1";
890 $input[1] = array($trxn_id, 'String');
894 $clause[] = "invoice_id = %2";
895 $input[2] = array($invoice_id, 'String');
898 if (empty($clause)) {
902 $clause = implode(' OR ', $clause);
904 $clause = "( $clause ) AND id != %3";
905 $input[3] = array($id, 'Integer');
908 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
909 $dao = CRM_Core_DAO
::executeQuery($query, $input);
911 while ($dao->fetch()) {
912 $duplicates[] = $dao->id
;
919 * Takes an associative array and creates a contribution_product object.
921 * the function extract all the params it needs to initialize the create a
922 * contribution_product object. the params array could contain additional unused name/value
925 * @param array $params
926 * (reference) an assoc array of name/value pairs.
928 * @return CRM_Contribute_DAO_ContributionProduct
930 public static function addPremium(&$params) {
931 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
932 $contributionProduct->copyValues($params);
933 return $contributionProduct->save();
937 * Get list of contribution fields for profile.
938 * For now we only allow custom contribution fields to be in
941 * @param bool $addExtraFields
942 * True if special fields needs to be added.
945 * the list of contribution fields
947 public static function getContributionFields($addExtraFields = TRUE) {
948 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
949 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
951 if ($addExtraFields) {
952 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
955 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
957 foreach ($contributionFields as $key => $var) {
958 if ($key == 'contribution_contact_id') {
961 elseif ($key == 'contribution_campaign_id') {
962 $var['title'] = ts('Campaign');
964 $fields[$key] = $var;
967 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
972 * Add extra fields specific to contribution.
974 public static function getSpecialContributionFields() {
975 $extraFields = array(
976 'contribution_soft_credit_name' => array(
977 'name' => 'contribution_soft_credit_name',
978 'title' => 'Soft Credit Name',
979 'headerPattern' => '/^soft_credit_name$/i',
980 'where' => 'civicrm_contact_d.display_name',
982 'contribution_soft_credit_email' => array(
983 'name' => 'contribution_soft_credit_email',
984 'title' => 'Soft Credit Email',
985 'headerPattern' => '/^soft_credit_email$/i',
986 'where' => 'soft_email.email',
988 'contribution_soft_credit_phone' => array(
989 'name' => 'contribution_soft_credit_phone',
990 'title' => 'Soft Credit Phone',
991 'headerPattern' => '/^soft_credit_phone$/i',
992 'where' => 'soft_phone.phone',
994 'contribution_soft_credit_contact_id' => array(
995 'name' => 'contribution_soft_credit_contact_id',
996 'title' => 'Soft Credit Contact ID',
997 'headerPattern' => '/^soft_credit_contact_id$/i',
998 'where' => 'civicrm_contribution_soft.contact_id',
1002 return $extraFields;
1006 * @param int $pageID
1010 public static function getCurrentandGoalAmount($pageID) {
1012 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1013 FROM civicrm_contribution_page p,
1014 civicrm_contribution c
1015 WHERE p.id = c.contribution_page_id
1017 AND c.cancel_date is null
1021 $config = CRM_Core_Config
::singleton();
1022 $params = array(1 => array($pageID, 'Integer'));
1023 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1025 if ($dao->fetch()) {
1026 return array($dao->goal
, $dao->total
);
1029 return array(NULL, NULL);
1034 * Get list of contribution In Honor of contact Ids.
1036 * @param int $honorId
1037 * In Honor of Contact ID.
1040 * list of contribution fields
1043 public static function getHonorContacts($honorId) {
1045 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1046 $honorDAO->contact_id
= $honorId;
1049 $type = CRM_Contribute_PseudoConstant
::financialType();
1051 while ($honorDAO->fetch()) {
1052 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1053 $contributionDAO->id
= $honorDAO->contribution_id
;
1055 if ($contributionDAO->find(TRUE)) {
1056 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1057 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1058 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1059 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1060 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1061 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1062 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1063 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1064 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1072 * Get the sort name of a contact for a particular contribution.
1075 * Id of the contribution.
1077 * @return null|string
1078 * sort name of the contact if found
1080 public static function sortName($id) {
1081 $id = CRM_Utils_Type
::escape($id, 'Integer');
1084 SELECT civicrm_contact.sort_name
1085 FROM civicrm_contribution, civicrm_contact
1086 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1087 AND civicrm_contribution.id = {$id}
1089 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1093 * @param int $contactID
1097 public static function annual($contactID) {
1098 if (is_array($contactID)) {
1099 $contactIDs = implode(',', $contactID);
1102 $contactIDs = $contactID;
1105 $config = CRM_Core_Config
::singleton();
1106 $startDate = $endDate = NULL;
1108 $currentMonth = date('m');
1109 $currentDay = date('d');
1110 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1111 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1112 (int ) $config->fiscalYearStart
['d'] > $currentDay
1115 $year = date('Y') - 1;
1120 $nextYear = $year +
1;
1122 if ($config->fiscalYearStart
) {
1123 if ($config->fiscalYearStart
['M'] < 10) {
1124 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1126 if ($config->fiscalYearStart
['d'] < 10) {
1127 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1129 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1134 $startDate = "$year$monthDay";
1135 $endDate = "$nextYear$monthDay";
1138 SELECT count(*) as count,
1139 sum(total_amount) as amount,
1140 avg(total_amount) as average,
1142 FROM civicrm_contribution b
1143 WHERE b.contact_id IN ( $contactIDs )
1144 AND b.contribution_status_id = 1
1146 AND b.receive_date >= $startDate
1147 AND b.receive_date < $endDate
1150 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1152 $amount = $average = array();
1153 while ($dao->fetch()) {
1154 if ($dao->count
> 0 && $dao->amount
> 0) {
1155 $count +
= $dao->count
;
1156 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1157 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1163 implode(', ', $amount),
1164 implode(', ', $average),
1167 return array(0, 0, 0);
1171 * Check if there is a contribution with the params passed in.
1172 * Used for trxn_id,invoice_id and contribution_id
1174 * @param array $params
1175 * An assoc array of name/value pairs.
1178 * contribution id if success else NULL
1180 public static function checkDuplicateIds($params) {
1181 $dao = new CRM_Contribute_DAO_Contribution();
1185 foreach ($params as $k => $v) {
1187 $clause[] = "$k = '$v'";
1190 $clause = implode(' AND ', $clause);
1191 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1192 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1194 while ($dao->fetch()) {
1202 * Get the contribution details for component export.
1204 * @param int $exportMode
1206 * @param string $componentIds
1213 public static function getContributionDetails($exportMode, $componentIds) {
1214 $paymentDetails = array();
1215 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1217 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1218 $componentSelect = " civicrm_participant_payment.participant_id id";
1219 $additionalClause = "
1220 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1221 AND civicrm_participant_payment.participant_id {$componentClause} )
1224 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1225 $componentSelect = " civicrm_membership_payment.membership_id id";
1226 $additionalClause = "
1227 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1228 AND civicrm_membership_payment.membership_id {$componentClause} )
1231 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1232 $componentSelect = " civicrm_pledge_payment.id id";
1233 $additionalClause = "
1234 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1235 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1239 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1240 trxn_id, {$componentSelect}
1241 FROM civicrm_contribution
1242 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1243 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1244 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1245 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1246 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1247 AND option_group_contribution_status.id = contribution_status.option_group_id )
1251 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1253 while ($dao->fetch()) {
1254 $paymentDetails[$dao->id
] = array(
1255 'total_amount' => $dao->total_amount
,
1256 'contribution_status' => $dao->status
,
1257 'receive_date' => $dao->receive_date
,
1258 'pay_instru' => $dao->payment_instrument
,
1259 'trxn_id' => $dao->trxn_id
,
1263 return $paymentDetails;
1267 * Create address associated with contribution record.
1269 * @param array $params
1270 * @param int $billingLocationTypeID
1275 public static function createAddress(&$params, $billingLocationTypeID) {
1276 $billingFields = array(
1279 'state_province_id',
1284 //build address array
1285 $addressParams = array();
1286 $addressParams['location_type_id'] = $billingLocationTypeID;
1287 $addressParams['is_billing'] = 1;
1289 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1290 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1291 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1292 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1294 foreach ($billingFields as $value) {
1295 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1298 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1300 return $address->id
;
1304 * Delete billing address record related contribution.
1306 * @param int $contributionId
1307 * @param int $contactId
1310 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1312 $contactJoin = NULL;
1314 if ($contributionId) {
1315 $clauses[] = "cc.id = {$contributionId}";
1319 $clauses[] = "cco.id = {$contactId}";
1320 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1323 if (empty($clauses)) {
1324 CRM_Core_Error
::fatal();
1327 $condition = implode(' OR ', $clauses);
1331 FROM civicrm_address ca
1332 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1336 $dao = CRM_Core_DAO
::executeQuery($query);
1338 while ($dao->fetch()) {
1339 $params = array('id' => $dao->id
);
1340 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1345 * This function check online pending contribution associated w/
1346 * Online Event Registration or Online Membership signup.
1348 * @param int $componentId
1349 * Participant/membership id.
1350 * @param string $componentName
1354 * pending contribution id.
1356 public static function checkOnlinePendingContribution($componentId, $componentName) {
1357 $contributionId = NULL;
1358 if (!$componentId ||
1359 !in_array($componentName, array('Event', 'Membership'))
1361 return $contributionId;
1364 if ($componentName == 'Event') {
1365 $idName = 'participant_id';
1366 $componentTable = 'civicrm_participant';
1367 $paymentTable = 'civicrm_participant_payment';
1368 $source = ts('Online Event Registration');
1371 if ($componentName == 'Membership') {
1372 $idName = 'membership_id';
1373 $componentTable = 'civicrm_membership';
1374 $paymentTable = 'civicrm_membership_payment';
1375 $source = ts('Online Contribution');
1378 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1381 SELECT component.id as {$idName},
1382 componentPayment.contribution_id as contribution_id,
1383 contribution.source source,
1384 contribution.contribution_status_id as contribution_status_id,
1385 contribution.is_pay_later as is_pay_later
1386 FROM $componentTable component
1387 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1388 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1389 WHERE component.id = {$componentId}";
1391 $dao = CRM_Core_DAO
::executeQuery($query);
1393 while ($dao->fetch()) {
1394 if ($dao->contribution_id
&&
1395 $dao->is_pay_later
&&
1396 $dao->contribution_status_id
== $pendingStatusId &&
1397 strpos($dao->source
, $source) !== FALSE
1399 $contributionId = $dao->contribution_id
;
1404 return $contributionId;
1408 * Update contribution as well as related objects.
1410 * @param array $params
1411 * @param bool $processContributionObject
1414 * @throws \Exception
1416 public static function transitionComponents($params, $processContributionObject = FALSE) {
1417 // get minimum required values.
1418 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1419 $componentId = CRM_Utils_Array
::value('component_id', $params);
1420 $componentName = CRM_Utils_Array
::value('componentName', $params);
1421 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1422 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1424 // if we already processed contribution object pass previous status id.
1425 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1427 $updateResult = array();
1429 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1431 // we process only ( Completed, Cancelled, or Failed ) contributions.
1432 if (!$contributionId ||
1433 !in_array($contributionStatusId, array(
1434 array_search('Completed', $contributionStatuses),
1435 array_search('Cancelled', $contributionStatuses),
1436 array_search('Failed', $contributionStatuses),
1439 return $updateResult;
1442 if (!$componentName ||
!$componentId) {
1443 // get the related component details.
1444 $componentDetails = self
::getComponentDetails($contributionId);
1447 $componentDetails['contact_id'] = $contactId;
1448 $componentDetails['component'] = $componentName;
1450 if ($componentName == 'event') {
1451 $componentDetails['participant'] = $componentId;
1454 $componentDetails['membership'] = $componentId;
1458 if (!empty($componentDetails['contact_id'])) {
1459 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1465 // do check for required ids.
1466 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1467 return $updateResult;
1470 //now we are ready w/ required ids, start processing.
1472 $baseIPN = new CRM_Core_Payment_BaseIPN();
1474 $input = $ids = $objects = array();
1476 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1477 $ids['contribution'] = $contributionId;
1478 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1479 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1480 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1481 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1482 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1483 $ids['contributionRecur'] = NULL;
1484 $ids['contributionPage'] = NULL;
1486 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1487 CRM_Core_Error
::fatal();
1490 $memberships = &$objects['membership'];
1491 $participant = &$objects['participant'];
1492 $pledgePayment = &$objects['pledge_payment'];
1493 $contribution = &$objects['contribution'];
1495 if ($pledgePayment) {
1496 $pledgePaymentIDs = array();
1497 foreach ($pledgePayment as $key => $object) {
1498 $pledgePaymentIDs[] = $object->id
;
1500 $pledgeID = $pledgePayment[0]->pledge_id
;
1503 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1506 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1507 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1512 // we might want to process contribution object.
1513 $processContribution = FALSE;
1514 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1515 if (is_array($memberships)) {
1516 foreach ($memberships as $membership) {
1518 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1519 $membership->save();
1521 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1522 if ($processContributionObject) {
1523 $processContribution = TRUE;
1530 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1531 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1533 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1534 if ($processContributionObject) {
1535 $processContribution = TRUE;
1539 if ($pledgePayment) {
1540 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1542 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1543 if ($processContributionObject) {
1544 $processContribution = TRUE;
1548 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1549 if (is_array($memberships)) {
1550 foreach ($memberships as $membership) {
1552 $membership->status_id
= array_search('Expired', $membershipStatuses);
1553 $membership->save();
1555 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1556 if ($processContributionObject) {
1557 $processContribution = TRUE;
1563 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1564 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1566 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1567 if ($processContributionObject) {
1568 $processContribution = TRUE;
1572 if ($pledgePayment) {
1573 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1575 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1576 if ($processContributionObject) {
1577 $processContribution = TRUE;
1581 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1583 // only pending contribution related object processed.
1584 if ($previousContriStatusId &&
1585 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1587 // this is case when we already processed contribution object.
1588 return $updateResult;
1590 elseif (!$previousContriStatusId &&
1591 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1593 // this is case when we are going to process contribution object later.
1594 return $updateResult;
1597 if (is_array($memberships)) {
1598 foreach ($memberships as $membership) {
1603 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1604 $membership->membership_type_id
,
1605 $membership->is_test
, $membership->id
1608 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1609 // this picks up membership type changes during renewals
1611 SELECT membership_type_id
1612 FROM civicrm_membership_log
1613 WHERE membership_id=$membership->id
1616 $dao = new CRM_Core_DAO();
1618 if ($dao->fetch()) {
1619 if (!empty($dao->membership_type_id
)) {
1620 $membership->membership_type_id
= $dao->membership_type_id
;
1621 $membership->save();
1624 // else fall back to using current membership type
1627 // Figure out number of terms
1629 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1630 foreach ($lineitems as $lineitem) {
1631 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1632 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1634 // in case membership_num_terms comes through as null or zero
1635 $numterms = $numterms >= 1 ?
$numterms : 1;
1640 // CRM-15735-to update the membership status as per the contribution receive date
1642 if (!empty($params['receive_date'])) {
1643 $joinDate = $params['receive_date'];
1644 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1645 $membership->end_date
,
1646 $membership->join_date
,
1647 $params['receive_date'],
1649 $membership->membership_type_id
,
1652 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1653 $membership->save();
1656 if ($currentMembership) {
1657 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1658 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1659 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1662 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1665 //get the status for membership.
1666 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1668 $dates['join_date'],
1671 $membership->membership_type_id
,
1675 $formattedParams = array(
1676 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1677 array_search('Current', $membershipStatuses)
1679 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1680 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1681 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1684 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1686 $membership->copyValues($formattedParams);
1687 $membership->save();
1689 //updating the membership log
1690 $membershipLog = array();
1691 $membershipLog = $formattedParams;
1692 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1693 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1695 $membershipLog['start_date'] = $logStartDate;
1696 $membershipLog['membership_id'] = $membership->id
;
1697 $membershipLog['modified_id'] = $membership->contact_id
;
1698 $membershipLog['modified_date'] = date('Ymd');
1699 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1701 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1703 //update related Memberships.
1704 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1706 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1709 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1710 if ($processContributionObject) {
1711 $processContribution = TRUE;
1714 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1720 $updatedStatusId = array_search('Registered', $participantStatuses);
1721 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1723 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1724 if ($processContributionObject) {
1725 $processContribution = TRUE;
1729 if ($pledgePayment) {
1730 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1732 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1733 if ($processContributionObject) {
1734 $processContribution = TRUE;
1739 // process contribution object.
1740 if ($processContribution) {
1741 $contributionParams = array();
1748 'payment_instrument_id',
1751 'financial_type_id',
1752 'contribution_status_id',
1753 'non_deductible_amount',
1757 foreach ($fields as $field) {
1758 if (empty($params[$field])) {
1761 $contributionParams[$field] = $params[$field];
1764 $ids = array('contribution' => $contributionId);
1765 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1768 return $updateResult;
1772 * Returns all contribution related object ids.
1774 * @param $contributionId
1778 public static function getComponentDetails($contributionId) {
1779 $componentDetails = $pledgePayment = array();
1780 if (!$contributionId) {
1781 return $componentDetails;
1785 SELECT c.id as contribution_id,
1786 c.contact_id as contact_id,
1787 c.contribution_recur_id,
1788 mp.membership_id as membership_id,
1789 m.membership_type_id as membership_type_id,
1790 pp.participant_id as participant_id,
1791 p.event_id as event_id,
1792 pgp.id as pledge_payment_id
1793 FROM civicrm_contribution c
1794 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1795 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1796 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1797 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1798 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1799 WHERE c.id = $contributionId";
1801 $dao = CRM_Core_DAO
::executeQuery($query);
1802 $componentDetails = array();
1804 while ($dao->fetch()) {
1805 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1806 $componentDetails['contact_id'] = $dao->contact_id
;
1807 if ($dao->event_id
) {
1808 $componentDetails['event'] = $dao->event_id
;
1810 if ($dao->participant_id
) {
1811 $componentDetails['participant'] = $dao->participant_id
;
1813 if ($dao->membership_id
) {
1814 if (!isset($componentDetails['membership'])) {
1815 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1817 $componentDetails['membership'][] = $dao->membership_id
;
1818 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1820 if ($dao->pledge_payment_id
) {
1821 $pledgePayment[] = $dao->pledge_payment_id
;
1823 if ($dao->contribution_recur_id
) {
1824 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1828 if ($pledgePayment) {
1829 $componentDetails['pledge_payment'] = $pledgePayment;
1832 return $componentDetails;
1836 * @param int $contactId
1837 * @param bool $includeSoftCredit
1839 * @return null|string
1841 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1846 $contactContributionsSQL = "
1847 SELECT contribution.id AS id
1848 FROM civicrm_contribution contribution
1849 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1851 $contactSoftCreditContributionsSQL = "
1852 SELECT contribution.id
1853 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1854 ON ( contribution.id = softContribution.contribution_id )
1855 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1856 $query = "SELECT count( x.id ) count FROM ( ";
1857 $query .= $contactContributionsSQL;
1859 if ($includeSoftCredit) {
1860 $query .= " UNION ";
1861 $query .= $contactSoftCreditContributionsSQL;
1866 return CRM_Core_DAO
::singleValueQuery($query);
1870 * Get individual id for onbehalf contribution.
1872 * @param int $contributionId
1874 * @param int $contributorId
1878 * containing organization id and individual id
1880 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1884 if (!$contributionId) {
1888 // fetch contributor id if null
1889 if (!$contributorId) {
1890 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1891 $contributionId, 'contact_id'
1895 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1896 $activityTypeId = array_search('Contribution', $activityTypeIds);
1898 if ($activityTypeId && $contributorId) {
1900 SELECT civicrm_activity_contact.contact_id
1901 FROM civicrm_activity_contact
1902 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1903 WHERE civicrm_activity.activity_type_id = %1
1904 AND civicrm_activity.source_record_id = %2
1905 AND civicrm_activity_contact.record_type_id = %3
1908 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1909 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1912 1 => array($activityTypeId, 'Integer'),
1913 2 => array($contributionId, 'Integer'),
1914 3 => array($sourceID, 'Integer'),
1917 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1919 // for on behalf contribution source is individual and contributor is organization
1920 if ($sourceContactId && $sourceContactId != $contributorId) {
1921 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1922 // get rel type id for employee of relation
1923 foreach ($relationshipTypeIds as $id => $typeVals) {
1924 if ($typeVals['name_a_b'] == 'Employee of') {
1925 $relationshipTypeId = $id;
1930 $rel = new CRM_Contact_DAO_Relationship();
1931 $rel->relationship_type_id
= $relationshipTypeId;
1932 $rel->contact_id_a
= $sourceContactId;
1933 $rel->contact_id_b
= $contributorId;
1934 if ($rel->find(TRUE)) {
1935 $ids['individual_id'] = $rel->contact_id_a
;
1936 $ids['organization_id'] = $rel->contact_id_b
;
1947 public static function getContributionDates() {
1948 $config = CRM_Core_Config
::singleton();
1949 $currentMonth = date('m');
1950 $currentDay = date('d');
1951 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1952 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1953 (int ) $config->fiscalYearStart
['d'] > $currentDay
1956 $year = date('Y') - 1;
1961 $year = array('Y' => $year);
1962 $yearDate = $config->fiscalYearStart
;
1963 $yearDate = array_merge($year, $yearDate);
1964 $yearDate = CRM_Utils_Date
::format($yearDate);
1966 $monthDate = date('Ym') . '01';
1972 'yearDate' => $yearDate,
1973 'monthDate' => $monthDate,
1978 * Load objects relations to contribution object.
1979 * Objects are stored in the $_relatedObjects property
1980 * In the first instance we are just moving functionality from BASEIpn -
1981 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1983 * Note that the unit test for the BaseIPN class tests this function
1985 * @param array $input
1986 * Input as delivered from Payment Processor.
1988 * Ids as Loaded by Payment Processor.
1989 * @param bool $required
1990 * Is Payment processor / contribution page required.
1991 * @param bool $loadAll
1992 * Load all related objects - even where id not passed in? (allows API to call this).
1997 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1999 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2000 if (empty($ids['contact']) && isset($this->contact_id
)) {
2001 $ids['contact'] = $this->contact_id
;
2004 if (empty($this->_component
)) {
2005 if (!empty($ids['event'])) {
2006 $this->_component
= 'event';
2009 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2012 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2013 $contributionType = new CRM_Financial_BAO_FinancialType();
2014 $contributionType->id
= $this->financial_type_id
;
2015 if (!$contributionType->find(TRUE)) {
2016 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2018 if (!empty($ids['contact'])) {
2019 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2020 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2021 $this->_relatedObjects
['contact']->find(TRUE);
2023 $this->_relatedObjects
['contributionType'] = $contributionType;
2025 if ($this->_component
== 'contribute') {
2026 // retrieve the other optional objects first so
2027 // stuff down the line can use this info and do things
2029 //in any case get the memberships associated with the contribution
2030 //because we now support multiple memberships w/ price set
2031 // see if there are any other memberships to be considered for same contribution.
2033 SELECT membership_id
2034 FROM civicrm_membership_payment
2035 WHERE contribution_id = %1 ";
2036 $params = array(1 => array($this->id
, 'Integer'));
2038 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2039 while ($dao->fetch()) {
2040 if ($dao->membership_id
) {
2041 if (!is_array($ids['membership'])) {
2042 $ids['membership'] = array();
2044 $ids['membership'][] = $dao->membership_id
;
2048 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2049 foreach ($ids['membership'] as $id) {
2051 $membership = new CRM_Member_BAO_Membership();
2052 $membership->id
= $id;
2053 if (!$membership->find(TRUE)) {
2054 throw new Exception("Could not find membership record: $id");
2056 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2057 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2058 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2059 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2060 $membership->free();
2065 if (!empty($ids['pledge_payment'])) {
2067 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2068 if (empty($paymentID)) {
2071 $payment = new CRM_Pledge_BAO_PledgePayment();
2072 $payment->id
= $paymentID;
2073 if (!$payment->find(TRUE)) {
2074 throw new Exception("Could not find pledge payment record: " . $paymentID);
2076 $this->_relatedObjects
['pledge_payment'][] = $payment;
2080 if (!empty($ids['contributionRecur'])) {
2081 $recur = new CRM_Contribute_BAO_ContributionRecur();
2082 $recur->id
= $ids['contributionRecur'];
2083 if (!$recur->find(TRUE)) {
2084 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2086 $this->_relatedObjects
['contributionRecur'] = &$recur;
2087 //get payment processor id from recur object.
2088 $paymentProcessorID = $recur->payment_processor_id
;
2090 //for normal contribution get the payment processor id.
2091 if (!$paymentProcessorID) {
2092 if ($this->contribution_page_id
) {
2093 // get the payment processor id from contribution page
2094 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2095 $this->contribution_page_id
,
2099 //fail to load payment processor id.
2100 elseif (empty($ids['pledge_payment'])) {
2101 $loadObjectSuccess = TRUE;
2103 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2105 return $loadObjectSuccess;
2110 // we are in event mode
2111 // make sure event exists and is valid
2112 $event = new CRM_Event_BAO_Event();
2113 $event->id
= $ids['event'];
2114 if ($ids['event'] &&
2117 throw new Exception("Could not find event: " . $ids['event']);
2120 $this->_relatedObjects
['event'] = &$event;
2122 $participant = new CRM_Event_BAO_Participant();
2123 $participant->id
= $ids['participant'];
2124 if ($ids['participant'] &&
2125 !$participant->find(TRUE)
2127 throw new Exception("Could not find participant: " . $ids['participant']);
2129 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2131 $this->_relatedObjects
['participant'] = &$participant;
2133 if (!$paymentProcessorID) {
2134 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2138 if ($paymentProcessorID) {
2139 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2140 $this->is_test ?
'test' : 'live'
2142 $ids['paymentProcessor'] = $paymentProcessorID;
2143 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2145 elseif ($required) {
2146 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2153 * Create array of message information - ie. return html version, txt version, to field
2155 * @param array $input
2156 * Incoming information.
2157 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2158 * just check presence of recur object but maintaining legacy approach
2161 * IDs of related objects.
2162 * @param array $values
2163 * Any values that may have already been compiled by calling process.
2164 * This is augmented by values 'gathered' by gatherMessageValues
2165 * @param bool $recur
2166 * @param bool $returnMessageText
2167 * Distinguishes between whether to send message or return.
2168 * message text. We are working towards this function ALWAYS returning message text & calling
2169 * function doing emails / pdfs with it
2175 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2176 if (empty($this->_relatedObjects
)) {
2177 $this->loadRelatedObjects($input, $ids);
2179 if (empty($this->_component
)) {
2180 $this->_component
= CRM_Utils_Array
::value('component', $input);
2183 //not really sure what params might be passed in but lets merge em into values
2184 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2185 $template = CRM_Core_Smarty
::singleton();
2186 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2187 //what does recur 'mean here - to do with payment processor return functionality but
2188 // what is the importance
2189 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2190 $paymentObject = &CRM_Core_Payment
::singleton(
2191 $this->is_test ?
'test' : 'live',
2192 $this->_relatedObjects
['paymentProcessor']
2195 $entityID = $entity = NULL;
2196 if (isset($ids['contribution'])) {
2197 $entity = 'contribution';
2198 $entityID = $ids['contribution'];
2200 if (!empty($ids['membership'])) {
2201 //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
2202 // 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
2203 // line having loaded an array
2204 $ids['membership'] = (array) $ids['membership'];
2205 $entity = 'membership';
2206 $entityID = $ids['membership'][0];
2209 $url = $paymentObject->subscriptionURL($entityID, $entity);
2210 $template->assign('cancelSubscriptionUrl', $url);
2212 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2213 $template->assign('updateSubscriptionBillingUrl', $url);
2215 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2216 $template->assign('updateSubscriptionUrl', $url);
2218 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2219 //direct mode showing billing block, so use directIPN for temporary
2220 $template->assign('contributeMode', 'directIPN');
2223 // todo remove strtolower - check consistency
2224 if (strtolower($this->_component
) == 'event') {
2225 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2226 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2230 $values['contribution_id'] = $this->id
;
2231 if (!empty($ids['related_contact'])) {
2232 $values['related_contact'] = $ids['related_contact'];
2233 if (isset($ids['onbehalf_dupe_alert'])) {
2234 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2236 $entityBlock = array(
2237 'contact_id' => $ids['contact'],
2238 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2239 'Home', 'id', 'name'
2242 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2243 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2246 if ($this->is_test
) {
2249 if (!empty($this->_relatedObjects
['membership'])) {
2250 foreach ($this->_relatedObjects
['membership'] as $membership) {
2251 if ($membership->id
) {
2252 $values['isMembership'] = TRUE;
2254 // need to set the membership values here
2255 $template->assign('membership_assign', 1);
2256 $template->assign('membership_name',
2257 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2259 $template->assign('mem_start_date', $membership->start_date
);
2260 $template->assign('mem_join_date', $membership->join_date
);
2261 $template->assign('mem_end_date', $membership->end_date
);
2262 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2263 $template->assign('mem_status', $membership_status);
2264 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2265 $template->assign('is_pay_later', 1);
2268 // if separate payment there are two contributions recorded and the
2269 // admin will need to send a receipt for each of them separately.
2270 // we dont link the two in the db (but can potentially infer it if needed)
2271 $template->assign('is_separate_payment', 0);
2273 if ($recur && $paymentObject) {
2274 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2275 $template->assign('cancelSubscriptionUrl', $url);
2276 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2277 $template->assign('updateSubscriptionBillingUrl', $url);
2278 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2279 $template->assign('updateSubscriptionUrl', $url);
2282 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2285 // otherwise if its about sending emails, continue sending without return, as we
2286 // don't want to exit the loop.
2291 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2297 * Gather values for contribution mail - this function has been created
2298 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2299 * Values related to the contribution in question are gathered
2301 * @param array $input
2302 * Input into function (probably from payment processor).
2303 * @param array $values
2305 * The set of ids related to the input.
2309 public function _gatherMessageValues($input, &$values, $ids = array()) {
2310 // set display address of contributor
2311 if ($this->address_id
) {
2312 $addressParams = array('id' => $this->address_id
);
2313 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2314 $addressDetails = array_values($addressDetails);
2315 $values['address'] = $addressDetails[0]['display'];
2317 if ($this->_component
== 'contribute') {
2318 if (isset($this->contribution_page_id
)) {
2319 CRM_Contribute_BAO_ContributionPage
::setValues(
2320 $this->contribution_page_id
,
2323 if ($this->contribution_page_id
) {
2324 // CRM-8254 - override default currency if applicable
2325 $config = CRM_Core_Config
::singleton();
2326 $config->defaultCurrency
= CRM_Utils_Array
::value(
2329 $config->defaultCurrency
2333 // no contribution page -probably back office
2335 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2336 $values['is_email_receipt'] = 1;
2337 $values['title'] = 'Contribution';
2339 // set lineItem for contribution
2341 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2342 if (!empty($lineItem)) {
2343 $itemId = key($lineItem);
2344 foreach ($lineItem as &$eachItem) {
2345 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2346 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2347 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2348 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2351 $values['lineItem'][0] = $lineItem;
2352 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2356 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2360 // if this is onbehalf of contribution then set related contact
2361 if (!empty($relatedContact['individual_id'])) {
2362 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2367 $eventParams = array(
2368 'id' => $this->_relatedObjects
['event']->id
,
2370 $values['event'] = array();
2372 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2374 //get location details
2375 $locationParams = array(
2376 'entity_id' => $this->_relatedObjects
['event']->id
,
2377 'entity_table' => 'civicrm_event',
2379 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2381 $ufJoinParams = array(
2382 'entity_table' => 'civicrm_event',
2383 'entity_id' => $ids['event'],
2384 'module' => 'CiviEvent',
2387 list($custom_pre_id,
2389 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2391 $values['custom_pre_id'] = $custom_pre_id;
2392 $values['custom_post_id'] = $custom_post_ids;
2394 // set lineItem for event contribution
2396 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2397 if (!empty($participantIds)) {
2398 foreach ($participantIds as $pIDs) {
2399 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2400 if (!CRM_Utils_System
::isNull($lineItem)) {
2401 $values['lineItem'][] = $lineItem;
2412 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2413 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2414 * Note we send directly from this function in some cases because it is only partly refactored
2415 * Don't call this function directly as the signature will change
2419 * @param CRM_Core_SMARTY $template
2420 * @param bool $recur
2421 * @param bool $returnMessageText
2425 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2426 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2427 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2428 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2429 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2430 $template->assign('useForMember', TRUE);
2432 //assign honor information to receipt message
2433 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2435 if (isset($softRecord['soft_credit'])) {
2436 //if id of contribution page is present
2437 if (!empty($values['id'])) {
2438 $values['honor'] = array(
2439 'honor_profile_values' => array(),
2440 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2441 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2443 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2445 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2446 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2449 //offline contribution
2450 $softCreditTypes = $softCredits = array();
2451 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2452 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2453 $softCredits[$key] = array(
2454 'Name' => $softCredit['contact_name'],
2455 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2458 $template->assign('softCreditTypes', $softCreditTypes);
2459 $template->assign('softCredits', $softCredits);
2463 $dao = new CRM_Contribute_DAO_ContributionProduct();
2464 $dao->contribution_id
= $this->id
;
2465 if ($dao->find(TRUE)) {
2466 $premiumId = $dao->product_id
;
2467 $template->assign('option', $dao->product_option
);
2469 $productDAO = new CRM_Contribute_DAO_Product();
2470 $productDAO->id
= $premiumId;
2471 $productDAO->find(TRUE);
2472 $template->assign('selectPremium', TRUE);
2473 $template->assign('product_name', $productDAO->name
);
2474 $template->assign('price', $productDAO->price
);
2475 $template->assign('sku', $productDAO->sku
);
2477 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2478 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2479 if (empty($amount) && isset($this->total_amount
)) {
2480 $amount = $this->total_amount
;
2482 $template->assign('amount', $amount);
2483 // add the new contribution values
2484 if (strtolower($this->_component
) == 'contribute') {
2486 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2487 $softDAO->contribution_id
= $this->id
;
2488 if ($softDAO->find(TRUE)) {
2489 $template->assign('pcpBlock', TRUE);
2490 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2491 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2492 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2494 //assign the pcp page title for email subject
2495 $pcpDAO = new CRM_PCP_DAO_PCP();
2496 $pcpDAO->id
= $softDAO->pcp_id
;
2497 if ($pcpDAO->find(TRUE)) {
2498 $template->assign('title', $pcpDAO->title
);
2503 if ($this->financial_type_id
) {
2504 $values['financial_type_id'] = $this->financial_type_id
;
2507 $template->assign('trxn_id', $this->trxn_id
);
2508 $template->assign('receive_date',
2509 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2511 $template->assign('contributeMode', 'notify');
2512 $template->assign('action', $this->is_test ?
1024 : 1);
2513 $template->assign('receipt_text',
2514 CRM_Utils_Array
::value('receipt_text',
2518 $template->assign('is_monetary', 1);
2519 $template->assign('is_recur', (bool) $recur);
2520 $template->assign('currency', $this->currency
);
2521 $template->assign('address', CRM_Utils_Address
::format($input));
2522 if ($this->_component
== 'event') {
2523 $template->assign('title', $values['event']['title']);
2524 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2525 $viewRoles = array();
2526 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2527 $viewRoles[] = $participantRoles[$v];
2529 $values['event']['participant_role'] = implode(', ', $viewRoles);
2530 $template->assign('event', $values['event']);
2531 $template->assign('location', $values['location']);
2532 $template->assign('customPre', $values['custom_pre_id']);
2533 $template->assign('customPost', $values['custom_post_id']);
2536 if ($this->_relatedObjects
['participant']->is_test
) {
2540 $values['params'] = array();
2541 //to get email of primary participant.
2542 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2543 $primaryAmount[] = array(
2544 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2545 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2547 //build an array of cId/pId of participants
2548 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2549 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2550 //send receipt to additional participant if exists
2551 if (count($additionalIDs)) {
2552 $template->assign('isPrimary', 0);
2553 $template->assign('customProfile', NULL);
2554 //set additionalParticipant true
2555 $values['params']['additionalParticipant'] = TRUE;
2556 foreach ($additionalIDs as $pId => $cId) {
2558 //to change the status pending to completed
2559 $additional = new CRM_Event_DAO_Participant();
2560 $additional->id
= $pId;
2561 $additional->contact_id
= $cId;
2562 $additional->find(TRUE);
2563 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2564 $additional->status_id
= 1;
2565 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2566 //if additional participant dont have email
2568 if (!$additionalParticipantInfo) {
2569 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2571 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2572 $primaryAmount[] = array(
2573 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2574 'amount' => $additional->fee_amount
,
2576 $additional->save();
2577 $additional->free();
2578 $template->assign('amount', $amount);
2579 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2583 //build an array of custom profile and assigning it to template
2584 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2586 if (count($customProfile)) {
2587 $template->assign('customProfile', $customProfile);
2590 // for primary contact
2591 $values['params']['additionalParticipant'] = FALSE;
2592 $template->assign('isPrimary', 1);
2593 $template->assign('amount', $primaryAmount);
2594 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2595 if ($this->payment_instrument_id
) {
2596 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2597 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2599 // carry paylater, since we did not created billing,
2600 // so need to pull email from primary location, CRM-4395
2601 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2607 * Check whether payment processor supports
2608 * cancellation of contribution subscription
2610 * @param int $contributionId
2613 * @param bool $isNotCancelled
2617 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2618 $cacheKeyString = "$contributionId";
2619 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2621 static $supportsCancel = array();
2623 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2624 $supportsCancel[$cacheKeyString] = FALSE;
2625 $isCancelled = FALSE;
2627 if ($isNotCancelled) {
2628 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2631 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2632 if (!empty($paymentObject)) {
2633 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2636 return $supportsCancel[$cacheKeyString];
2640 * Check whether subscription is already cancelled.
2642 * @param int $contributionId
2646 * contribution status
2648 public static function isSubscriptionCancelled($contributionId) {
2650 SELECT cr.contribution_status_id
2651 FROM civicrm_contribution_recur cr
2652 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2653 WHERE con.id = %1 LIMIT 1";
2654 $params = array(1 => array($contributionId, 'Integer'));
2655 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2656 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2657 if ($status == 'Cancelled') {
2664 * Create all financial accounts entry.
2666 * @param array $params
2667 * Contribution object, line item array and params for trxn.
2670 * @param array $financialTrxnValues
2672 * @return null|object
2674 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2675 $skipRecords = $update = $return = $isRelatedId = FALSE;
2677 $additionalParticipantId = array();
2678 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2680 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2681 $entityId = $params['participant_id'];
2682 $entityTable = 'civicrm_participant';
2683 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2685 elseif (!empty($params['membership_id'])) {
2686 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2687 // are created off one contribution should be handled elsewhere
2688 $entityId = $params['membership_id'];
2689 $entityTable = 'civicrm_membership';
2692 $entityId = $params['contribution']->id
;
2693 $entityTable = 'civicrm_contribution';
2696 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2697 $isRelatedId = TRUE;
2700 $entityID[] = $entityId;
2701 if (!empty($additionalParticipantId)) {
2702 $entityID +
= $additionalParticipantId;
2704 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2705 if (empty($params['prevContribution'])) {
2712 $statusId = $params['contribution']->contribution_status_id
;
2713 // CRM-13964 partial payment
2714 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2715 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2717 $partialAmtPay = $params['partial_amount_pay'];
2718 $partialAmtTotal = $params['partial_payment_total'];
2720 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2721 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2722 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2723 $params['total_amount'] = $partialAmtPay;
2725 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2726 if (empty($balanceTrxnInfo['trxn_id'])) {
2727 // create new balance transaction record
2728 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2729 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2731 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2732 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2733 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2734 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2735 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2736 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2737 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2738 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2739 $balanceTrxnParams['status_id'] = $statusId;
2740 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2741 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2742 if (!empty($params['payment_processor'])) {
2743 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2745 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2749 // build line item array if its not set in $params
2750 if (empty($params['line_item']) ||
$additionalParticipantId) {
2751 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2754 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2755 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2757 $skipRecords = TRUE;
2758 $pendingStatus = array(
2759 array_search('Pending', $contributionStatuses),
2760 array_search('In Progress', $contributionStatuses),
2762 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2763 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2764 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2766 elseif (!empty($params['payment_processor'])) {
2767 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2769 elseif (!empty($params['payment_instrument_id'])) {
2770 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2773 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2774 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2775 $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);
2778 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2779 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2780 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2783 //build financial transaction params
2784 $trxnParams = array(
2785 'contribution_id' => $params['contribution']->id
,
2786 'to_financial_account_id' => $params['to_financial_account_id'],
2787 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2788 'total_amount' => $totalAmount,
2789 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2790 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2791 'currency' => $params['contribution']->currency
,
2792 'trxn_id' => $params['contribution']->trxn_id
,
2793 'status_id' => $statusId,
2794 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2795 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2798 if (!empty($params['payment_processor'])) {
2799 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2802 if (isset($fromFinancialAccountId)) {
2803 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2806 // consider external values passed for recording transaction entry
2807 if (!empty($financialTrxnValues)) {
2808 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2811 $params['trxnParams'] = $trxnParams;
2813 if (!empty($params['prevContribution'])) {
2814 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2815 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2816 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2817 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2818 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2820 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2821 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2822 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2824 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2825 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2828 //if financial type is changed
2829 if (!empty($params['financial_type_id']) &&
2830 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2832 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2833 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2834 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2835 if ($oldFinancialAccount != $newFinancialAccount) {
2836 $params['total_amount'] = 0;
2837 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2838 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2839 $params['prevContribution']->financial_type_id
, $relationTypeId);
2842 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2843 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2844 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2847 self
::updateFinancialAccounts($params, 'changeFinancialType');
2848 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2849 $params['financial_account_id'] = $newFinancialAccount;
2850 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2851 self
::updateFinancialAccounts($params);
2852 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2856 //Update contribution status
2857 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2858 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2859 if (!empty($params['contribution_status_id']) &&
2860 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2862 //Update Financial Records
2863 self
::updateFinancialAccounts($params, 'changedStatus');
2866 // change Payment Instrument for a Completed contribution
2867 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2868 // instrument is null and now new payment instrument is added along with the payment
2869 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2870 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2871 if (array_key_exists('payment_instrument_id', $params)) {
2872 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2873 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2874 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2876 //check if status is changed from Pending to Completed
2877 // do not update payment instrument changes for Pending to Completed
2878 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2879 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2881 // for all other statuses create new financial records
2882 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2883 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2884 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2887 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2888 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2889 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2891 // for any other payment instrument changes create new financial records
2892 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2893 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2894 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2896 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2897 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2899 // another special case when check number is changed, create new financial records
2900 // create financial trxn with negative amount
2901 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2902 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2903 // create financial trxn with positive amount
2904 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2905 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2906 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2910 //if Change contribution amount
2911 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2912 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2913 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2914 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2915 if (isset($totalAmount) &&
2916 $totalAmount != $params['prevContribution']->total_amount
2918 //Update Financial Records
2919 $params['trxnParams']['from_financial_account_id'] = NULL;
2920 self
::updateFinancialAccounts($params, 'changedAmount');
2925 // records finanical trxn and entity financial trxn
2926 // also make it available as return value
2927 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2928 $params['entity_id'] = $financialTxn->id
;
2931 // record line items and finacial items
2932 if (empty($params['skipLineItem'])) {
2933 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2936 // create batch entry if batch_id is passed and
2937 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
2938 if (!empty($params['batch_id']) && !empty($financialTxn)) {
2939 $entityParams = array(
2940 'batch_id' => $params['batch_id'],
2941 'entity_table' => 'civicrm_financial_trxn',
2942 'entity_id' => $financialTxn->id
,
2944 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2947 // when a fee is charged
2948 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2949 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2952 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2953 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2955 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2956 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2957 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2959 unset($params['line_item']);
2965 * Update all financial accounts entry.
2967 * @param array $params
2968 * Contribution object, line item array and params for trxn.
2970 * @param string $context
2973 * @param null $skipTrxn
2976 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2977 $itemAmount = $trxnID = NULL;
2978 //get all the statuses
2979 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2980 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2981 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2982 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2983 && $context == 'changePaymentInstrument'
2987 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2988 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2990 if ($context == 'changedStatus') {
2991 //get all the statuses
2992 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2994 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2995 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2996 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2998 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3000 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3001 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3003 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3004 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3005 $params['trxnParams']['to_financial_account_id'] = NULL;
3006 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3008 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3009 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3010 $financialTypeID, $relationTypeId);
3012 $itemAmount = $params['trxnParams']['total_amount'];
3014 elseif ($context == 'changePaymentInstrument') {
3015 if ($params['trxnParams']['total_amount'] < 0) {
3016 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3017 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3018 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3019 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3023 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3024 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3027 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3028 $params['entity_id'] = $trxn->id
;
3030 if ($context == 'changedStatus') {
3031 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3032 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3033 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3035 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3036 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3038 $entityParams = array(
3039 'entity_table' => 'civicrm_financial_item',
3040 'financial_trxn_id' => $trxn->id
,
3042 if (empty($params['line_item'])) {
3044 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3045 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3046 // & this can be removed
3049 foreach ($params['line_item'] as $fieldId => $fields) {
3050 foreach ($fields as $fieldValueId => $fieldValues) {
3052 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3053 2 => array($fieldValues['id'], 'Integer'),
3055 CRM_Core_DAO
::executeQuery($query, $fparams);
3057 1 => array($fieldValues['id'], 'Integer'),
3059 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3060 while ($financialItem->fetch()) {
3061 $entityParams['entity_id'] = $financialItem->id
;
3062 $entityParams['amount'] = $financialItem->amount
;
3063 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3070 if ($context != 'changePaymentInstrument') {
3071 $itemParams['entity_table'] = 'civicrm_line_item';
3072 $trxnIds['id'] = $params['entity_id'];
3073 foreach ($params['line_item'] as $fieldId => $fields) {
3074 foreach ($fields as $fieldValueId => $fieldValues) {
3075 $prevParams['entity_id'] = $fieldValues['id'];
3076 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3078 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3079 if ($params['contribution']->receive_date
) {
3080 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3083 $financialAccount = $prevfinancialItem->financial_account_id
;
3084 if (!empty($params['financial_account_id'])) {
3085 $financialAccount = $params['financial_account_id'];
3088 $currency = $params['prevContribution']->currency
;
3089 if ($params['contribution']->currency
) {
3090 $currency = $params['contribution']->currency
;
3093 if (!empty($params['is_quick_config'])) {
3094 $amount = $itemAmount;
3096 $amount = $params['total_amount'];
3100 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3101 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3105 $amount = $diff * $fieldValues['line_total'];
3108 $itemParams = array(
3109 'transaction_date' => $receiveDate,
3110 'contact_id' => $params['prevContribution']->contact_id
,
3111 'currency' => $currency,
3112 'amount' => $amount,
3113 'description' => $prevfinancialItem->description
,
3114 'status_id' => $prevfinancialItem->status_id
,
3115 'financial_account_id' => $financialAccount,
3116 'entity_table' => 'civicrm_line_item',
3117 'entity_id' => $fieldValues['id'],
3119 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3121 if ($fieldValues['tax_amount']) {
3122 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3123 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3124 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3125 $itemParams['description'] = $taxTerm;
3126 if ($fieldValues['financial_type_id']) {
3127 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3129 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3134 if ($context == 'changeFinancialType') {
3135 $params['skipLineItem'] = FALSE;
3136 foreach ($params['line_item'] as &$lineItems) {
3137 foreach ($lineItems as &$line) {
3138 $line['financial_type_id'] = $params['financial_type_id'];
3145 * Check status validation on update of a contribution.
3147 * @param array $values
3148 * Previous form values before submit.
3150 * @param array $fields
3151 * The input form values.
3153 * @param array $errors
3158 public static function checkStatusValidation($values, &$fields, &$errors) {
3159 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3160 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3161 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3165 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3166 $checkStatus = array(
3167 'Cancelled' => array('Completed', 'Refunded'),
3168 'Completed' => array('Cancelled', 'Refunded'),
3169 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3170 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3171 'Refunded' => array('Cancelled', 'Completed'),
3174 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3175 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3176 1 => $contributionStatuses[$values['contribution_status_id']],
3177 2 => $contributionStatuses[$fields['contribution_status_id']],
3183 * Delete contribution of contact.
3187 * @param int $contactId
3191 public static function deleteContactContribution($contactId) {
3192 $contribution = new CRM_Contribute_DAO_Contribution();
3193 $contribution->contact_id
= $contactId;
3194 $contribution->find();
3195 while ($contribution->fetch()) {
3196 self
::deleteContribution($contribution->id
);
3201 * Get options for a given contribution field.
3202 * @see CRM_Core_DAO::buildOptions
3204 * @param string $fieldName
3205 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3206 * @param array $props whatever is known about this dao object.
3208 * @return array|bool
3210 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3211 $className = __CLASS__
;
3213 switch ($fieldName) {
3214 // This field is not part of this object but the api supports it
3215 case 'payment_processor':
3216 $className = 'CRM_Contribute_BAO_ContributionPage';
3217 // Filter results by contribution page
3218 if (!empty($props['contribution_page_id'])) {
3219 $page = civicrm_api('contribution_page', 'getsingle', array(
3221 'id' => ($props['contribution_page_id']),
3223 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3224 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3228 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3229 case 'honor_type_id':
3230 $className = 'CRM_Contribute_BAO_ContributionSoft';
3231 $fieldName = 'soft_credit_type_id';
3232 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3235 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3239 * Validate financial type.
3243 * @param int $financialTypeId
3244 * Financial Type id.
3246 * @param string $relationName
3248 * @return array|bool
3250 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3251 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3252 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3254 if (!$financialAccount) {
3255 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3262 * Function to record additional payment for partial and refund contributions.
3264 * @param int $contributionId
3265 * is the invoice contribution id (got created after processing participant payment).
3266 * @param array $trxnsData
3267 * to take user provided input of transaction details.
3268 * @param string $paymentType
3269 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3270 * @param int $participantId
3272 * @return null|object
3274 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3275 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3276 $getInfoOf['id'] = $contributionId;
3277 $defaults = array();
3278 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3280 if ($paymentType == 'owed') {
3281 // build params for recording financial trxn entry
3282 $params['contribution'] = $contributionDAO;
3283 $params = array_merge($defaults, $params);
3284 $params['skipLineItem'] = TRUE;
3285 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3286 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3287 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3288 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3291 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3292 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3293 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3295 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3296 if (!empty($trxnId)) {
3297 $trxnId = $trxnId['trxn_id'];
3299 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3300 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3303 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3304 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3305 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3309 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3310 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3311 FROM civicrm_financial_trxn ft
3312 LEFT JOIN civicrm_entity_financial_trxn eft
3313 ON (ft.id = eft.financial_trxn_id)
3314 WHERE eft.entity_table = 'civicrm_contribution'
3315 AND eft.entity_id = {$contributionId}
3316 AND ft.to_financial_account_id != {$toFinancialAccount}
3317 AND ft.status_id = {$statusId}
3319 $query = CRM_Core_DAO
::executeQuery($sql);
3321 $sumOfPayments = $query->sum_of_payments
;
3324 if ($contributionDAO->total_amount
== $sumOfPayments) {
3325 // update contribution status and
3326 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3327 $contributionDAO->contribution_status_id
= $statusId;
3328 $contributionDAO->cancel_date
= 'null';
3329 $contributionDAO->cancel_reason
= NULL;
3330 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3331 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3332 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3333 $contributionDAO->save();
3335 //Change status of financial record too
3336 $financialTrxn->status_id
= $statusId;
3337 $financialTrxn->save();
3339 // note : not using the self::add method,
3340 // the reason because it performs 'status change' related code execution for financial records
3341 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3342 // are coded below i.e. just updating financial_item status to 'Paid'
3344 if ($participantId) {
3345 // update participant status
3346 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3347 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3348 foreach ($ids as $val) {
3349 $participantUpdate['id'] = $val;
3350 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3351 CRM_Event_BAO_Participant
::add($participantUpdate);
3355 // update financial item statuses
3356 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3357 $paidStatus = array_search('Paid', $financialItemStatus);
3359 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3360 $sqlFinancialItemUpdate = "
3361 UPDATE civicrm_financial_item fi
3362 LEFT JOIN civicrm_entity_financial_trxn eft
3363 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3364 SET status_id = {$paidStatus}
3365 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3367 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3370 elseif ($paymentType == 'refund') {
3371 // build params for recording financial trxn entry
3372 $params['contribution'] = $contributionDAO;
3373 $params = array_merge($defaults, $params);
3374 $params['skipLineItem'] = TRUE;
3375 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3376 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3378 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3379 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3380 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3382 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3384 // note : not using the self::add method,
3385 // the reason because it performs 'status change' related code execution for financial records
3386 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3387 // are coded below i.e. just updating financial_item status to 'Paid'
3388 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3390 // add financial item entry
3391 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3392 $getLine['entity_id'] = $contributionDAO->id
;
3393 $getLine['entity_table'] = 'civicrm_contribution';
3394 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3395 if (!empty($lineItemId->id
)) {
3396 $addFinancialEntry = array(
3397 'transaction_date' => $financialTrxn->trxn_date
,
3398 'contact_id' => $contributionDAO->contact_id
,
3399 'amount' => $financialTrxn->total_amount
,
3400 'status_id' => array_search('Paid', $financialItemStatus),
3401 'entity_id' => $lineItemId->id
,
3402 'entity_table' => 'civicrm_line_item',
3404 $trxnIds['id'] = $financialTrxn->id
;
3405 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3407 if ($participantId) {
3408 // update participant status
3409 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3410 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3411 foreach ($ids as $val) {
3412 $participantUpdate['id'] = $val;
3413 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3414 CRM_Event_BAO_Participant
::add($participantUpdate);
3419 // activity creation
3420 if (!empty($financialTrxn)) {
3421 if ($participantId) {
3422 $inputParams['id'] = $participantId;
3425 $component = 'event';
3426 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3427 $entityObj = $entityObj[$participantId];
3429 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3431 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3433 return $financialTrxn;
3439 * @param $activityType
3441 * @param int $contributionId
3443 * @throws CRM_Core_Exception
3445 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3446 if ($component == 'event') {
3447 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3448 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3449 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3450 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3451 $targetCid = $entityObj->contact_id
;
3452 // source record id would be the contribution id
3453 $srcRecId = $contributionId;
3457 $activityParams = array(
3458 'source_contact_id' => $targetCid,
3459 'source_record_id' => $srcRecId,
3460 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3464 'subject' => $subject,
3465 'activity_date_time' => $date,
3466 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3470 'skipRecentView' => TRUE,
3473 // create activity with target contacts
3474 $session = CRM_Core_Session
::singleton();
3475 $id = $session->get('userID');
3477 $activityParams['source_contact_id'] = $id;
3478 $activityParams['target_contact_id'][] = $targetCid;
3480 CRM_Activity_BAO_Activity
::create($activityParams);
3484 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3488 * @param bool $getTrxnInfo
3489 * @param bool $usingLineTotal
3493 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3494 if ($component == 'event') {
3495 $entity = 'participant';
3496 $entityTable = 'civicrm_participant';
3497 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3499 if (!$contributionId) {
3500 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3501 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3502 $id = $primaryParticipantId;
3504 if (!$contributionId) {
3509 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3510 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3516 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3517 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3520 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3521 // for additional participants
3522 if ($entityTable == 'civicrm_participant') {
3523 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3525 foreach ($ids as $val) {
3526 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3530 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3534 $baseTrxnId = $total['trxn_id'];
3535 $total = $total['total_amount'];
3538 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3539 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3541 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3542 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3543 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3545 if ($paymentBalance == 0 && $contributionIsPayLater) {
3546 $paymentBalance = $total;
3549 $info['total'] = $total;
3550 $info['paid'] = $total - $paymentBalance;
3551 $info['balance'] = $paymentBalance;
3553 $info['component'] = $component;
3554 $info['payLater'] = $contributionIsPayLater;
3556 if ($getTrxnInfo && $baseTrxnId) {
3557 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3559 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3560 FROM civicrm_contribution con
3561 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3562 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3563 WHERE con.id = {$contributionId}
3566 // conditioned WHERE clause
3568 // if balance trxn exists don't include details of it in transaction info
3569 $sql .= " AND ft.id != {$baseTrxnId} ";
3571 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3573 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3574 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3575 while ($resultDAO->fetch()) {
3576 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3577 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3579 'total_amount' => $resultDAO->total_amount
,
3580 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3581 'payment_instrument' => $paidByLabel,
3582 'receive_date' => $resultDAO->trxn_date
,
3583 'trxn_id' => $resultDAO->trxn_id
,
3584 'status' => $statuses[$resultDAO->status_id
],
3586 if ($paidByName == 'Check') {
3587 $val['check_number'] = $resultDAO->check_number
;
3591 $info['transaction'] = $rows;
3597 * Get financial account id has 'Sales Tax Account is'
3598 * account relationship with financial type
3600 * @param int $financialTypeId
3602 * @return FinancialAccountId
3604 public static function getFinancialAccountId($financialTypeId) {
3605 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3606 $searchParams = array(
3607 'entity_table' => 'civicrm_financial_type',
3608 'entity_id' => $financialTypeId,
3609 'account_relationship' => $accountRel,
3612 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3614 return CRM_Utils_Array
::value('financial_account_id', $result);
3620 * @param array $params
3621 * @param bool $isLineItem
3625 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3626 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3628 // Update contribution.
3629 if (!empty($params['id'])) {
3630 $id = $params['id'];
3631 $values = $ids = array();
3632 $contrbutionParams = array('id' => $id);
3633 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3635 // To assign pervious finantial type on update of contribution
3636 if (!isset($params['financial_type_id'])) {
3637 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3639 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3640 // Assisn tax Amount on update of contrbution
3641 if (!empty($prevContributionValue->tax_amount
)) {
3642 $params['tax_amount'] = 'null';
3643 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3644 foreach ($params['line_item'] as $setID => $priceField) {
3645 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3646 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3653 // New Contrbution and update of contribution with tax rate financial type
3654 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3655 empty($params['skipLineItem']) && !$isLineItem
3657 $taxRateParams = $taxRates[$params['financial_type_id']];
3658 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3659 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3661 // Get Line Item on update of contribution
3662 if (isset($params['id'])) {
3663 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3666 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3668 foreach ($params['line_item'] as $setID => $priceField) {
3669 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3670 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3673 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3675 elseif (isset($params['api.line_item.create'])) {
3676 // Update total amount of contribution using lineItem
3677 $taxAmountArray = array();
3678 foreach ($params['api.line_item.create'] as $key => $value) {
3679 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3680 $taxRate = $taxRates[$value['financial_type_id']];
3681 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3682 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3685 $params['tax_amount'] = array_sum($taxAmountArray);
3686 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3689 // update line item of contrbution
3690 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3691 $taxRate = $taxRates[$params['financial_type_id']];
3692 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3693 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3700 * Check financial type validation on update of a contribution.
3702 * @param Integer $financialTypeId
3703 * Value of latest Financial Type.
3705 * @param Integer $contributionId
3708 * @param array $errors
3713 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3714 if (!empty($financialTypeId)) {
3715 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3716 if ($oldFinancialTypeId == $financialTypeId) {
3720 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3722 '1' => array($contributionId, 'Integer'),
3724 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3725 if ($result->N
> 1) {
3726 $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.');