3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * Static field for all the contribution information that we can potentially import
43 static $_importableFields = NULL;
46 * Static field for all the contribution information that we can potentially export
51 static $_exportableFields = NULL;
54 * Field for all the objects related to this contribution
55 * @var array of objects (e.g membership object, participant object)
57 public $_relatedObjects = array();
60 * Field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
65 * @var string component or event
67 public $_component = NULL;
75 * @return \CRM_Contribute_DAO_Contribution
80 public function __construct() {
81 parent
::__construct();
85 * Takes an associative array and creates a contribution object
87 * the function extract all the params it needs to initialize the create a
88 * contribution object. the params array could contain additional unused name/value
91 * @param array $params (reference ) an assoc array of name/value pairs
92 * @param array $ids the array that holds all the db ids
94 * @return CRM_Contribute_BAO_Contribution object
97 public static function add(&$params, $ids = array()) {
101 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
102 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
103 $duplicates = array();
104 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
105 $error = CRM_Core_Error
::singleton();
106 $d = implode(', ', $duplicates);
107 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
110 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
115 // first clean up all the money fields
116 $moneyFields = array(
120 'non_deductible_amount',
123 //if priceset is used, no need to cleanup money
124 if (!empty($params['skipCleanMoney'])) {
125 unset($moneyFields[0]);
128 foreach ($moneyFields as $field) {
129 if (isset($params[$field])) {
130 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
134 //set defaults in create mode
135 if (!$contributionID) {
136 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
137 self
::calculateMissingAmountParams($params);
140 if (!empty($params['payment_instrument_id'])) {
141 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
142 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
143 $params['check_number'] = 'null';
147 $setPrevContribution = TRUE;
148 // CRM-13964 partial payment
149 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
150 $partialAmtTotal = $params['partial_payment_total'];
151 $partialAmtPay = $params['partial_amount_pay'];
152 $params['total_amount'] = $partialAmtTotal;
153 if ($partialAmtPay < $partialAmtTotal) {
154 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
155 $params['is_pay_later'] = 0;
156 $setPrevContribution = FALSE;
160 if ($contributionID) {
161 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
164 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
166 $contribution = new CRM_Contribute_BAO_Contribution();
167 $contribution->copyValues($params);
169 $contribution->id
= $contributionID;
171 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
172 $config = CRM_Core_Config
::singleton();
173 $contribution->currency
= $config->defaultCurrency
;
176 if ($contributionID && $setPrevContribution) {
177 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
180 $result = $contribution->save();
182 // Add financial_trxn details as part of fix for CRM-4724
183 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
184 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
186 //add Account details
187 $params['contribution'] = $contribution;
188 self
::recordFinancialAccounts($params);
190 // reset the group contact cache for this group
191 CRM_Contact_BAO_GroupContactCache
::remove();
193 if ($contributionID) {
194 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
197 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
204 * Get defaults for new entity
207 public static function getDefaults() {
209 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
210 FALSE, FALSE, FALSE, 'AND is_default = 1')
212 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
217 * Given the list of params in the params array, fetch the object
218 * and store the values in the values array
220 * @param array $params input parameters to find object
221 * @param array $values output values of the object
222 * @param array $ids the array that holds all the db ids
224 * @return CRM_Contribute_BAO_Contribution|null the found object or null
227 public static function &getValues($params, &$values, &$ids) {
228 if (empty($params)) {
231 $contribution = new CRM_Contribute_BAO_Contribution();
233 $contribution->copyValues($params);
235 if ($contribution->find(TRUE)) {
236 $ids['contribution'] = $contribution->id
;
238 CRM_Core_DAO
::storeValues($contribution, $values);
240 return $contribution;
242 $null = NULL; // return by reference
247 * @param array $params
251 public static function calculateMissingAmountParams(&$params) {
252 if (!isset($params['fee_amount'])) {
253 if (isset($params['total_amount']) && isset($params['net_amount'])) {
254 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
257 $params['fee_amount'] = 0;
260 if (!isset($params['net_amount'])) {
261 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
266 * Get the number of terms for this contribution for a given membership type
267 * based on querying the line item table and relevant price field values
268 * Note that any one contribution should only be able to have one line item relating to a particular membership
271 * @param int $membershipTypeID
273 * @param int $contributionID
277 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
278 $numTerms = CRM_Core_DAO
::singleValueQuery("
279 SELECT membership_num_terms FROM civicrm_line_item li
280 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
281 WHERE contribution_id = %1 AND membership_type_id = %2",
282 array(1 => array($contributionID, 'Integer') , 2 => array($membershipTypeID, 'Integer'))
284 // default of 1 is precautionary
285 return empty($numTerms) ?
1 : $numTerms;
289 * Takes an associative array and creates a contribution object
291 * @param array $params (reference ) an assoc array of name/value pairs
292 * @param array $ids the array that holds all the db ids
294 * @return CRM_Contribute_BAO_Contribution object
297 public static function create(&$params, $ids = array()) {
298 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
299 foreach ($dateFields as $df) {
300 if (isset($params[$df])) {
301 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
305 $transaction = new CRM_Core_Transaction();
307 $contribution = self
::add($params, $ids);
309 if (is_a($contribution, 'CRM_Core_Error')) {
310 $transaction->rollback();
311 return $contribution;
314 $params['contribution_id'] = $contribution->id
;
316 if (!empty($params['custom']) &&
317 is_array($params['custom'])
319 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
322 $session = CRM_Core_Session
::singleton();
324 if (!empty($params['note'])) {
326 'entity_table' => 'civicrm_contribution',
327 'note' => $params['note'],
328 'entity_id' => $contribution->id
,
329 'contact_id' => $session->get('userID'),
330 'modified_date' => date('Ymd'),
332 if (!$noteParams['contact_id']) {
333 $noteParams['contact_id'] = $params['contact_id'];
335 CRM_Core_BAO_Note
::add($noteParams);
338 // make entry in batch entity batch table
339 if (!empty($params['batch_id'])) {
340 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
341 $titleFields = array(
347 $retrieveRequired = 0;
348 foreach ($titleFields as $titleField) {
349 if(!isset($contribution->$titleField)){
350 $retrieveRequired = 1;
354 if ($retrieveRequired == 1) {
355 $contribution->find(TRUE);
359 // check if activity record exist for this contribution, if
361 $activity = new CRM_Activity_DAO_Activity();
362 $activity->source_record_id
= $contribution->id
;
363 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
367 if (!$activity->find(TRUE)) {
368 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
371 // CRM-13237 : if activity record found, update it with campaign id of contribution
372 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
375 // Handle soft credit and / or link to personal campaign page
376 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
378 //Delete PCP against this contribution and create new on submitted PCP information
379 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
381 $deleteParams = array('id' => $pcpId);
382 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
384 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
385 $softParams = array();
386 $softParams['contribution_id'] = $contribution->id
;
387 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
388 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
389 $pcp['pcp_made_through_id'], 'contact_id'
391 $softParams['currency'] = $contribution->currency
;
392 $softParams['amount'] = $contribution->total_amount
;
393 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
394 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
395 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
396 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
397 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
399 if (isset($params['soft_credit'])) {
400 $softParams = $params['soft_credit'];
402 if (!empty($softIDs)) {
403 foreach ( $softIDs as $softID) {
404 if (!in_array($softID, $params['soft_credit_ids'])) {
405 $deleteParams = array('id' => $softID);
406 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
411 foreach ($softParams as $softParam) {
412 $softParam['contribution_id'] = $contribution->id
;
413 $softParam['currency'] = $contribution->currency
;
414 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
415 if (empty($softParam['amount'])) {
416 $softParam['amount'] = $contribution->total_amount
;
418 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
422 $transaction->commit();
424 // do not add to recent items for import, CRM-4399
425 if (empty($params['skipRecentView'])) {
426 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
427 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
429 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
430 $titleFields = array(
436 $retrieveRequired = 0;
437 foreach ($titleFields as $titleField) {
438 if(!isset($contribution->$titleField)){
439 $retrieveRequired = 1;
443 if($retrieveRequired == 1){
444 $contribution->find(TRUE);
446 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
447 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
449 $recentOther = array();
450 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
451 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
452 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
456 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
457 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
458 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
462 // add the recently created Contribution
463 CRM_Utils_Recent
::add($title,
467 $contribution->contact_id
,
473 return $contribution;
477 * Get the values for pseudoconstants for name->value and reverse.
479 * @param array $defaults (reference) the default values, some of which need to be resolved.
480 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
485 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
486 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
487 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
488 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
489 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
493 * This function is used to convert associative array names to values
496 * This function is used by both the web form layer and the api. Note that
497 * the api needs the name => value conversion, also the view layer typically
498 * requires value => name conversion
500 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
501 $id = $property . '_id';
503 $src = $reverse ?
$property : $id;
504 $dst = $reverse ?
$id : $property;
506 if (!array_key_exists($src, $defaults)) {
510 $look = $reverse ?
array_flip($lookup) : $lookup;
512 if (is_array($look)) {
513 if (!array_key_exists($defaults[$src], $look)) {
517 $defaults[$dst] = $look[$defaults[$src]];
522 * Takes a bunch of params that are needed to match certain criteria and
523 * retrieves the relevant objects. We'll tweak this function to be more
524 * full featured over a period of time. This is the inverse function of
525 * create. It also stores all the retrieved values in the default array
527 * @param array $params (reference ) an assoc array of name/value pairs
528 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
529 * in a hierarchical manner
530 * @param array $ids (reference) the array that holds all the db ids
532 * @return CRM_Contribute_BAO_Contribution object
535 public static function retrieve(&$params, &$defaults, &$ids) {
536 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
537 return $contribution;
541 * Combine all the importable fields from the lower levels object
543 * The ordering is important, since currently we do not have a weight
544 * scheme. Adding weight is super important and should be done in the
545 * next week or so, before this can be called complete.
547 * @param string $contactType
548 * @param bool $status
550 * @return array array of importable Fields
553 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
554 if (!self
::$_importableFields) {
555 if (!self
::$_importableFields) {
556 self
::$_importableFields = array();
560 $fields = array('' => array('title' => ts('- do not import -')));
563 $fields = array('' => array('title' => ts('- Contribution Fields -')));
566 $note = CRM_Core_DAO_Note
::import();
567 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
568 unset($tmpFields['option_value']);
569 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
570 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
572 // Using new Dedupe rule.
574 'contact_type' => $contactType,
575 'used' => 'Unsupervised',
577 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
578 $tmpContactField = array();
579 if (is_array($fieldsArray)) {
580 foreach ($fieldsArray as $value) {
581 //skip if there is no dupe rule
582 if ($value == 'none') {
585 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
590 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
591 $tmpContactField[trim($value)] = $contactFields[trim($value)];
593 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
596 $title = $tmpContactField[trim($value)]['title'];
598 $tmpContactField[trim($value)]['title'] = $title;
602 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
603 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
604 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
605 $fields = array_merge($fields, $tmpContactField);
606 $fields = array_merge($fields, $tmpFields);
607 $fields = array_merge($fields, $note);
608 $fields = array_merge($fields, $optionFields);
609 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
610 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
611 self
::$_importableFields = $fields;
613 return self
::$_importableFields;
619 public static function &exportableFields() {
620 if (!self
::$_exportableFields) {
621 if (!self
::$_exportableFields) {
622 self
::$_exportableFields = array();
625 $impFields = CRM_Contribute_DAO_Contribution
::export();
626 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
627 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
628 $typeField = CRM_Financial_DAO_FinancialType
::export();
629 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
630 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
631 $contributionStatus = array(
632 'contribution_status' => array(
633 'title' => ts('Contribution Status'),
634 'name' => 'contribution_status',
635 'data_type' => CRM_Utils_Type
::T_STRING
638 $contributionNote = array(
639 'contribution_note' =>
641 'title' => ts('Contribution Note'),
642 'name' => 'contribution_note',
643 'data_type' => CRM_Utils_Type
::T_TEXT
647 $contributionRecurId = array(
648 'contribution_recur_id' => array(
649 'title' => ts('Recurring Contributions ID'),
650 'name' => 'contribution_recur_id',
651 'where' => 'civicrm_contribution.contribution_recur_id',
652 'data_type' => CRM_Utils_Type
::T_INT
655 $extraFields = array(
656 'contribution_batch' => array(
657 'title' => ts('Batch Name')
661 $softCreditFields = array(
662 'contribution_soft_credit_name' => array(
663 'name' => 'contribution_soft_credit_name',
664 'title' => 'Soft Credit For',
665 'where' => 'civicrm_contact_d.display_name',
666 'data_type' => CRM_Utils_Type
::T_STRING
668 'contribution_soft_credit_amount' => array(
669 'name' => 'contribution_soft_credit_amount',
670 'title' => 'Soft Credit Amount',
671 'where' => 'civicrm_contribution_soft.amount',
672 'data_type' => CRM_Utils_Type
::T_MONEY
674 'contribution_soft_credit_type' => array(
675 'name' => 'contribution_soft_credit_type',
676 'title' => 'Soft Credit Type',
677 'where' => 'contribution_softcredit_type.label',
678 'data_type' => CRM_Utils_Type
::T_STRING
680 'contribution_soft_credit_contribution_id' => array(
681 'name' => 'contribution_soft_credit_contribution_id',
682 'title' => 'Soft Credit For Contribution ID',
683 'where' => 'civicrm_contribution_soft.contribution_id',
684 'data_type' => CRM_Utils_Type
::T_INT
688 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
689 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
690 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
693 self
::$_exportableFields = $fields;
696 return self
::$_exportableFields;
700 * @param null $status
701 * @param null $startDate
702 * @param null $endDate
706 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
710 $where[] = 'contribution_status_id = 1';
714 $where[] = 'contribution_status_id = 3';
719 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
722 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
725 $whereCond = implode(' AND ', $where);
728 SELECT sum( total_amount ) as total_amount,
729 count( civicrm_contribution.id ) as total_count,
731 FROM civicrm_contribution
732 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
734 AND ( is_test = 0 OR is_test IS NULL )
735 AND contact.is_deleted = 0
739 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
742 while ($dao->fetch()) {
743 $count +
= $dao->total_count
;
744 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
747 return array('amount' => implode(', ', $amount),
755 * Delete the indirect records associated with this contribution first
759 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
762 public static function deleteContribution($id) {
763 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
765 $transaction = new CRM_Core_Transaction();
768 //delete activity record
770 'source_record_id' => $id,
771 // activity type id for contribution
772 'activity_type_id' => 6,
775 CRM_Activity_BAO_Activity
::deleteActivity($params);
777 //delete billing address if exists for this contribution.
778 self
::deleteAddress($id);
780 //update pledge and pledge payment, CRM-3961
781 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
783 // remove entry from civicrm_price_set_entity, CRM-5095
784 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
785 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
787 // cleanup line items.
788 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
790 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
791 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
793 if ($participantId) {
794 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
797 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
801 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
802 $noteId = key($note);
804 CRM_Core_BAO_Note
::del($noteId, FALSE);
807 $dao = new CRM_Contribute_DAO_Contribution();
810 $results = $dao->delete();
812 $transaction->commit();
814 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
816 // delete the recently created Contribution
817 $contributionRecent = array(
819 'type' => 'Contribution',
821 CRM_Utils_Recent
::del($contributionRecent);
827 * Check if there is a contribution with the same trxn_id or invoice_id
829 * @param array $input an assoc array of name/value pairs
830 * @param array $duplicates (reference ) store ids of duplicate contribs
834 * @return boolean true if duplicate, false otherwise
837 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
839 $id = CRM_Utils_Array
::value('id', $input);
841 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
842 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
848 $clause[] = "trxn_id = %1";
849 $input[1] = array($trxn_id, 'String');
853 $clause[] = "invoice_id = %2";
854 $input[2] = array($invoice_id, 'String');
857 if (empty($clause)) {
861 $clause = implode(' OR ', $clause);
863 $clause = "( $clause ) AND id != %3";
864 $input[3] = array($id, 'Integer');
867 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
868 $dao = CRM_Core_DAO
::executeQuery($query, $input);
870 while ($dao->fetch()) {
871 $duplicates[] = $dao->id
;
878 * Takes an associative array and creates a contribution_product object
880 * the function extract all the params it needs to initialize the create a
881 * contribution_product object. the params array could contain additional unused name/value
884 * @param array $params (reference ) an assoc array of name/value pairs
886 * @return CRM_Contribute_BAO_ContributionProduct object
889 public static function addPremium(&$params) {
890 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
891 $contributionProduct->copyValues($params);
892 return $contributionProduct->save();
896 * Get list of contribution fields for profile
897 * For now we only allow custom contribution fields to be in
900 * @param boolean $addExtraFields true if special fields needs to be added
902 * @return array the list of contribution fields
905 public static function getContributionFields($addExtraFields = TRUE) {
906 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
907 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
909 if ($addExtraFields) {
910 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
913 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
915 foreach ($contributionFields as $key => $var) {
916 if ($key == 'contribution_contact_id') {
919 elseif ($key == 'contribution_campaign_id') {
920 $var['title'] = ts('Campaign');
922 $fields[$key] = $var;
925 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
930 * Add extra fields specific to contribtion
934 public static function getSpecialContributionFields() {
935 $extraFields = array(
936 'contribution_soft_credit_name' => array(
937 'name' => 'contribution_soft_credit_name',
938 'title' => 'Soft Credit Name',
939 'headerPattern' => '/^soft_credit_name$/i',
940 'where' => 'civicrm_contact_d.display_name',
942 'contribution_soft_credit_email' => array(
943 'name' => 'contribution_soft_credit_email',
944 'title' => 'Soft Credit Email',
945 'headerPattern' => '/^soft_credit_email$/i',
946 'where' => 'soft_email.email',
948 'contribution_soft_credit_phone' => array(
949 'name' => 'contribution_soft_credit_phone',
950 'title' => 'Soft Credit Phone',
951 'headerPattern' => '/^soft_credit_phone$/i',
952 'where' => 'soft_phone.phone',
954 'contribution_soft_credit_contact_id' => array(
955 'name' => 'contribution_soft_credit_contact_id',
956 'title' => 'Soft Credit Contact ID',
957 'headerPattern' => '/^soft_credit_contact_id$/i',
958 'where' => 'civicrm_contribution_soft.contact_id',
970 public static function getCurrentandGoalAmount($pageID) {
972 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
973 FROM civicrm_contribution_page p,
974 civicrm_contribution c
975 WHERE p.id = c.contribution_page_id
977 AND c.cancel_date is null
981 $config = CRM_Core_Config
::singleton();
982 $params = array(1 => array($pageID, 'Integer'));
983 $dao = CRM_Core_DAO
::executeQuery($query, $params);
986 return array($dao->goal
, $dao->total
);
989 return array(NULL, NULL);
994 * Get list of contribution In Honor of contact Ids
996 * @param int $honorId In Honor of Contact ID
998 * @return return the list of contribution fields
1002 public static function getHonorContacts($honorId) {
1004 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1005 $honorDAO->contact_id
= $honorId;
1008 $type = CRM_Contribute_PseudoConstant
::financialType();
1010 while ($honorDAO->fetch()) {
1011 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1012 $contributionDAO->id
= $honorDAO->contribution_id
;
1014 if ($contributionDAO->find(TRUE)) {
1015 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1016 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1017 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1018 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1019 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1020 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1021 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1022 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1023 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1031 * Get the sort name of a contact for a particular contribution
1033 * @param int $id id of the contribution
1035 * @return null|string sort name of the contact if found
1038 public static function sortName($id) {
1039 $id = CRM_Utils_Type
::escape($id, 'Integer');
1042 SELECT civicrm_contact.sort_name
1043 FROM civicrm_contribution, civicrm_contact
1044 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1045 AND civicrm_contribution.id = {$id}
1047 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1051 * @param int $contactID
1055 public static function annual($contactID) {
1056 if (is_array($contactID)) {
1057 $contactIDs = implode(',', $contactID);
1060 $contactIDs = $contactID;
1063 $config = CRM_Core_Config
::singleton();
1064 $startDate = $endDate = NULL;
1066 $currentMonth = date('m');
1067 $currentDay = date('d');
1068 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1069 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1070 (int ) $config->fiscalYearStart
['d'] > $currentDay
1073 $year = date('Y') - 1;
1078 $nextYear = $year +
1;
1080 if ($config->fiscalYearStart
) {
1081 if ($config->fiscalYearStart
['M'] < 10) {
1082 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1084 if ($config->fiscalYearStart
['d'] < 10) {
1085 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1087 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1092 $startDate = "$year$monthDay";
1093 $endDate = "$nextYear$monthDay";
1096 SELECT count(*) as count,
1097 sum(total_amount) as amount,
1098 avg(total_amount) as average,
1100 FROM civicrm_contribution b
1101 WHERE b.contact_id IN ( $contactIDs )
1102 AND b.contribution_status_id = 1
1104 AND b.receive_date >= $startDate
1105 AND b.receive_date < $endDate
1108 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1110 $amount = $average = array();
1111 while ($dao->fetch()) {
1112 if ($dao->count
> 0 && $dao->amount
> 0) {
1113 $count +
= $dao->count
;
1114 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1115 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1121 implode(', ', $amount),
1122 implode(', ', $average),
1125 return array(0, 0, 0);
1129 * Check if there is a contribution with the params passed in.
1130 * Used for trxn_id,invoice_id and contribution_id
1132 * @param array $params an assoc array of name/value pairs
1134 * @return array contribution id if success else NULL
1137 public static function checkDuplicateIds($params) {
1138 $dao = new CRM_Contribute_DAO_Contribution();
1142 foreach ($params as $k => $v) {
1144 $clause[] = "$k = '$v'";
1147 $clause = implode(' AND ', $clause);
1148 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1149 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1151 while ($dao->fetch()) {
1159 * Get the contribution details for component export
1161 * @param int $exportMode export mode
1162 * @param string $componentIds component ids
1164 * @return array associated array
1168 public static function getContributionDetails($exportMode, $componentIds) {
1169 $paymentDetails = array();
1170 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1172 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1173 $componentSelect = " civicrm_participant_payment.participant_id id";
1174 $additionalClause = "
1175 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1176 AND civicrm_participant_payment.participant_id {$componentClause} )
1179 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1180 $componentSelect = " civicrm_membership_payment.membership_id id";
1181 $additionalClause = "
1182 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1183 AND civicrm_membership_payment.membership_id {$componentClause} )
1186 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1187 $componentSelect = " civicrm_pledge_payment.id id";
1188 $additionalClause = "
1189 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1190 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1194 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1195 trxn_id, {$componentSelect}
1196 FROM civicrm_contribution
1197 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1198 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1199 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1200 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1201 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1202 AND option_group_contribution_status.id = contribution_status.option_group_id )
1206 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1208 while ($dao->fetch()) {
1209 $paymentDetails[$dao->id
] = array(
1210 'total_amount' => $dao->total_amount
,
1211 'contribution_status' => $dao->status
,
1212 'receive_date' => $dao->receive_date
,
1213 'pay_instru' => $dao->payment_instrument
,
1214 'trxn_id' => $dao->trxn_id
,
1218 return $paymentDetails;
1222 * Create address associated with contribution record.
1224 * @param array $params an associated array
1225 * @param int $billingLocationTypeID
1227 * @return address id
1230 public static function createAddress(&$params, $billingLocationTypeID) {
1231 $billingFields = array(
1234 'state_province_id',
1239 //build address array
1240 $addressParams = array();
1241 $addressParams['location_type_id'] = $billingLocationTypeID;
1242 $addressParams['is_billing'] = 1;
1244 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1245 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1246 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1247 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1249 foreach ($billingFields as $value) {
1250 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1253 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1255 return $address->id
;
1259 * Delete billing address record related contribution
1261 * @param int $contributionId
1262 * @param int $contactId
1266 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1268 $contactJoin = NULL;
1270 if ($contributionId) {
1271 $clauses[] = "cc.id = {$contributionId}";
1275 $clauses[] = "cco.id = {$contactId}";
1276 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1279 if (empty($clauses)) {
1280 CRM_Core_Error
::fatal();
1283 $condition = implode(' OR ', $clauses);
1287 FROM civicrm_address ca
1288 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1292 $dao = CRM_Core_DAO
::executeQuery($query);
1294 while ($dao->fetch()) {
1295 $params = array('id' => $dao->id
);
1296 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1301 * This function check online pending contribution associated w/
1302 * Online Event Registration or Online Membership signup.
1304 * @param int $componentId participant/membership id.
1305 * @param string $componentName Event/Membership.
1307 * @return $contributionId pending contribution id.
1310 public static function checkOnlinePendingContribution($componentId, $componentName) {
1311 $contributionId = NULL;
1312 if (!$componentId ||
1313 !in_array($componentName, array('Event', 'Membership'))
1315 return $contributionId;
1318 if ($componentName == 'Event') {
1319 $idName = 'participant_id';
1320 $componentTable = 'civicrm_participant';
1321 $paymentTable = 'civicrm_participant_payment';
1322 $source = ts('Online Event Registration');
1325 if ($componentName == 'Membership') {
1326 $idName = 'membership_id';
1327 $componentTable = 'civicrm_membership';
1328 $paymentTable = 'civicrm_membership_payment';
1329 $source = ts('Online Contribution');
1332 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1335 SELECT component.id as {$idName},
1336 componentPayment.contribution_id as contribution_id,
1337 contribution.source source,
1338 contribution.contribution_status_id as contribution_status_id,
1339 contribution.is_pay_later as is_pay_later
1340 FROM $componentTable component
1341 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1342 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1343 WHERE component.id = {$componentId}";
1345 $dao = CRM_Core_DAO
::executeQuery($query);
1347 while ($dao->fetch()) {
1348 if ($dao->contribution_id
&&
1349 $dao->is_pay_later
&&
1350 $dao->contribution_status_id
== $pendingStatusId &&
1351 strpos($dao->source
, $source) !== FALSE
1353 $contributionId = $dao->contribution_id
;
1358 return $contributionId;
1362 * This function update contribution as well as related objects.
1364 public static function transitionComponents($params, $processContributionObject = FALSE) {
1365 // get minimum required values.
1366 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1367 $componentId = CRM_Utils_Array
::value('component_id', $params);
1368 $componentName = CRM_Utils_Array
::value('componentName', $params);
1369 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1370 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1372 // if we already processed contribution object pass previous status id.
1373 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1375 $updateResult = array();
1377 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1379 // we process only ( Completed, Cancelled, or Failed ) contributions.
1380 if (!$contributionId ||
1381 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1382 array_search('Cancelled', $contributionStatuses),
1383 array_search('Failed', $contributionStatuses),
1386 return $updateResult;
1389 if (!$componentName ||
!$componentId) {
1390 // get the related component details.
1391 $componentDetails = self
::getComponentDetails($contributionId);
1394 $componentDetails['contact_id'] = $contactId;
1395 $componentDetails['component'] = $componentName;
1397 if ($componentName == 'event') {
1398 $componentDetails['participant'] = $componentId;
1401 $componentDetails['membership'] = $componentId;
1405 if (!empty($componentDetails['contact_id'])) {
1406 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1412 // do check for required ids.
1413 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1414 return $updateResult;
1417 //now we are ready w/ required ids, start processing.
1419 $baseIPN = new CRM_Core_Payment_BaseIPN();
1421 $input = $ids = $objects = array();
1423 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1424 $ids['contribution'] = $contributionId;
1425 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1426 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1427 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1428 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1429 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1430 $ids['contributionRecur'] = NULL;
1431 $ids['contributionPage'] = NULL;
1433 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1434 CRM_Core_Error
::fatal();
1437 $memberships = &$objects['membership'];
1438 $participant = &$objects['participant'];
1439 $pledgePayment = &$objects['pledge_payment'];
1440 $contribution = &$objects['contribution'];
1442 if ($pledgePayment) {
1443 $pledgePaymentIDs = array();
1444 foreach ($pledgePayment as $key => $object) {
1445 $pledgePaymentIDs[] = $object->id
;
1447 $pledgeID = $pledgePayment[0]->pledge_id
;
1450 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1453 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1454 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1459 // we might want to process contribution object.
1460 $processContribution = FALSE;
1461 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1462 if (is_array($memberships)) {
1463 foreach ($memberships as $membership) {
1465 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1466 $membership->save();
1468 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1469 if ($processContributionObject) {
1470 $processContribution = TRUE;
1477 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1478 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1480 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1481 if ($processContributionObject) {
1482 $processContribution = TRUE;
1486 if ($pledgePayment) {
1487 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1489 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1490 if ($processContributionObject) {
1491 $processContribution = TRUE;
1495 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1496 if (is_array($memberships)) {
1497 foreach ($memberships as $membership) {
1499 $membership->status_id
= array_search('Expired', $membershipStatuses);
1500 $membership->save();
1502 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1503 if ($processContributionObject) {
1504 $processContribution = TRUE;
1510 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1511 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1513 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1514 if ($processContributionObject) {
1515 $processContribution = TRUE;
1519 if ($pledgePayment) {
1520 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1522 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1523 if ($processContributionObject) {
1524 $processContribution = TRUE;
1528 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1530 // only pending contribution related object processed.
1531 if ($previousContriStatusId &&
1532 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1534 // this is case when we already processed contribution object.
1535 return $updateResult;
1537 elseif (!$previousContriStatusId &&
1538 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1540 // this is case when we are going to process contribution object later.
1541 return $updateResult;
1544 if (is_array($memberships)) {
1545 foreach ($memberships as $membership) {
1550 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1551 $membership->membership_type_id
,
1552 $membership->is_test
, $membership->id
1555 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1556 // this picks up membership type changes during renewals
1558 SELECT membership_type_id
1559 FROM civicrm_membership_log
1560 WHERE membership_id=$membership->id
1563 $dao = new CRM_Core_DAO
;
1565 if ($dao->fetch()) {
1566 if (!empty($dao->membership_type_id
)) {
1567 $membership->membership_type_id
= $dao->membership_type_id
;
1568 $membership->save();
1571 // else fall back to using current membership type
1574 // Figure out number of terms
1576 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1577 foreach ($lineitems as $lineitem) {
1578 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1579 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1581 // in case membership_num_terms comes through as null or zero
1582 $numterms = $numterms >= 1 ?
$numterms : 1;
1587 // CRM-15735-to update the membership status as per the contribution receive date
1588 if (!empty($params['receive_date'])) {
1589 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1590 $membership->end_date
,
1591 $membership->join_date
,
1592 $params['receive_date'],
1594 $membership->membership_type_id
,
1597 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1598 $membership->save();
1601 if ($currentMembership) {
1602 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1603 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1604 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1607 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1610 //get the status for membership.
1611 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1613 $dates['join_date'],
1616 $membership->membership_type_id
,
1620 $formattedParams = array(
1621 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1622 array_search('Current', $membershipStatuses)
1624 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1625 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1626 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1629 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1631 $membership->copyValues($formattedParams);
1632 $membership->save();
1634 //updating the membership log
1635 $membershipLog = array();
1636 $membershipLog = $formattedParams;
1637 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1638 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1640 $membershipLog['start_date'] = $logStartDate;
1641 $membershipLog['membership_id'] = $membership->id
;
1642 $membershipLog['modified_id'] = $membership->contact_id
;
1643 $membershipLog['modified_date'] = date('Ymd');
1644 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1646 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1648 //update related Memberships.
1649 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1651 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1654 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1655 if ($processContributionObject) {
1656 $processContribution = TRUE;
1659 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1665 $updatedStatusId = array_search('Registered', $participantStatuses);
1666 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1668 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1669 if ($processContributionObject) {
1670 $processContribution = TRUE;
1674 if ($pledgePayment) {
1675 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1677 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1678 if ($processContributionObject) {
1679 $processContribution = TRUE;
1684 // process contribution object.
1685 if ($processContribution) {
1686 $contributionParams = array();
1688 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1689 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1690 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1692 foreach ($fields as $field) {
1693 if (empty($params[$field])) {
1696 $contributionParams[$field] = $params[$field];
1699 $ids = array('contribution' => $contributionId);
1700 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1703 return $updateResult;
1707 * This function returns all contribution related object ids.
1709 public static function getComponentDetails($contributionId) {
1710 $componentDetails = $pledgePayment = array();
1711 if (!$contributionId) {
1712 return $componentDetails;
1716 SELECT c.id as contribution_id,
1717 c.contact_id as contact_id,
1718 mp.membership_id as membership_id,
1719 m.membership_type_id as membership_type_id,
1720 pp.participant_id as participant_id,
1721 p.event_id as event_id,
1722 pgp.id as pledge_payment_id
1723 FROM civicrm_contribution c
1724 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1725 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1726 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1727 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1728 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1729 WHERE c.id = $contributionId";
1731 $dao = CRM_Core_DAO
::executeQuery($query);
1732 $componentDetails = array();
1734 while ($dao->fetch()) {
1735 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1736 $componentDetails['contact_id'] = $dao->contact_id
;
1737 if ($dao->event_id
) {
1738 $componentDetails['event'] = $dao->event_id
;
1740 if ($dao->participant_id
) {
1741 $componentDetails['participant'] = $dao->participant_id
;
1743 if ($dao->membership_id
) {
1744 if (!isset($componentDetails['membership'])) {
1745 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1747 $componentDetails['membership'][] = $dao->membership_id
;
1748 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1750 if ($dao->pledge_payment_id
) {
1751 $pledgePayment[] = $dao->pledge_payment_id
;
1755 if ($pledgePayment) {
1756 $componentDetails['pledge_payment'] = $pledgePayment;
1759 return $componentDetails;
1763 * @param int $contactId
1764 * @param bool $includeSoftCredit
1766 * @return null|string
1768 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1773 $contactContributionsSQL = "
1774 SELECT contribution.id AS id
1775 FROM civicrm_contribution contribution
1776 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1778 $contactSoftCreditContributionsSQL = "
1779 SELECT contribution.id
1780 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1781 ON ( contribution.id = softContribution.contribution_id )
1782 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1783 $query = "SELECT count( x.id ) count FROM ( ";
1784 $query .= $contactContributionsSQL;
1786 if ($includeSoftCredit) {
1787 $query .= " UNION ";
1788 $query .= $contactSoftCreditContributionsSQL;
1793 return CRM_Core_DAO
::singleValueQuery($query);
1797 * Get individual id for onbehalf contribution
1799 * @param int $contributionId contribution id
1800 * @param int $contributorId contributor id
1802 * @return array $ids containing organization id and individual id
1804 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1808 if (!$contributionId) {
1812 // fetch contributor id if null
1813 if (!$contributorId) {
1814 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1815 $contributionId, 'contact_id'
1819 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1820 $activityTypeId = array_search('Contribution', $activityTypeIds);
1822 if ($activityTypeId && $contributorId) {
1824 SELECT civicrm_activity_contact.contact_id
1825 FROM civicrm_activity_contact
1826 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1827 WHERE civicrm_activity.activity_type_id = %1
1828 AND civicrm_activity.source_record_id = %2
1829 AND civicrm_activity_contact.record_type_id = %3
1832 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1833 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1836 1 => array($activityTypeId, 'Integer'),
1837 2 => array($contributionId, 'Integer'),
1838 3 => array($sourceID, 'Integer'),
1841 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1843 // for on behalf contribution source is individual and contributor is organization
1844 if ($sourceContactId && $sourceContactId != $contributorId) {
1845 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1846 // get rel type id for employee of relation
1847 foreach ($relationshipTypeIds as $id => $typeVals) {
1848 if ($typeVals['name_a_b'] == 'Employee of') {
1849 $relationshipTypeId = $id;
1854 $rel = new CRM_Contact_DAO_Relationship();
1855 $rel->relationship_type_id
= $relationshipTypeId;
1856 $rel->contact_id_a
= $sourceContactId;
1857 $rel->contact_id_b
= $contributorId;
1858 if ($rel->find(TRUE)) {
1859 $ids['individual_id'] = $rel->contact_id_a
;
1860 $ids['organization_id'] = $rel->contact_id_b
;
1872 public static function getContributionDates() {
1873 $config = CRM_Core_Config
::singleton();
1874 $currentMonth = date('m');
1875 $currentDay = date('d');
1876 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1877 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1878 (int ) $config->fiscalYearStart
['d'] > $currentDay
1881 $year = date('Y') - 1;
1886 $year = array('Y' => $year);
1887 $yearDate = $config->fiscalYearStart
;
1888 $yearDate = array_merge($year, $yearDate);
1889 $yearDate = CRM_Utils_Date
::format($yearDate);
1891 $monthDate = date('Ym') . '01';
1897 'yearDate' => $yearDate,
1898 'monthDate' => $monthDate,
1903 * Load objects relations to contribution object
1904 * Objects are stored in the $_relatedObjects property
1905 * In the first instance we are just moving functionality from BASEIpn -
1906 * see http://issues.civicrm.org/jira/browse/CRM-9996
1908 * @param array $input Input as delivered from Payment Processor
1909 * @param array $ids Ids as Loaded by Payment Processor
1910 * @param boolean $required Is Payment processor / contribution page required
1911 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1912 * Note that the unit test for the BaseIPN class tests this function
1917 * @param bool $required
1918 * @param bool $loadAll
1923 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1925 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1926 if(empty($ids['contact']) && isset($this->contact_id
)){
1927 $ids['contact'] = $this->contact_id
;
1930 if (empty($this->_component
)) {
1931 if (! empty($ids['event'])) {
1932 $this->_component
= 'event';
1935 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1938 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1939 $contributionType = new CRM_Financial_BAO_FinancialType();
1940 $contributionType->id
= $this->financial_type_id
;
1941 if (!$contributionType->find(TRUE)) {
1942 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1944 if (!empty($ids['contact'])) {
1945 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1946 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1947 $this->_relatedObjects
['contact']->find(TRUE);
1949 $this->_relatedObjects
['contributionType'] = $contributionType;
1951 if ($this->_component
== 'contribute') {
1952 // retrieve the other optional objects first so
1953 // stuff down the line can use this info and do things
1955 //in any case get the memberships associated with the contribution
1956 //because we now support multiple memberships w/ price set
1957 // see if there are any other memberships to be considered for same contribution.
1959 SELECT membership_id
1960 FROM civicrm_membership_payment
1961 WHERE contribution_id = %1 ";
1962 $params = array(1 => array($this->id
, 'Integer'));
1964 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1965 while ($dao->fetch()) {
1966 if ($dao->membership_id
) {
1967 if (!is_array($ids['membership'])) {
1968 $ids['membership'] = array();
1970 $ids['membership'][] = $dao->membership_id
;
1974 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1975 foreach ($ids['membership'] as $id) {
1977 $membership = new CRM_Member_BAO_Membership();
1978 $membership->id
= $id;
1979 if (!$membership->find(TRUE)) {
1980 throw new Exception("Could not find membership record: $id");
1982 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1983 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1984 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1985 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1986 $membership->free();
1991 if (!empty($ids['pledge_payment'])) {
1993 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1994 if (empty($paymentID)) {
1997 $payment = new CRM_Pledge_BAO_PledgePayment();
1998 $payment->id
= $paymentID;
1999 if (!$payment->find(TRUE)) {
2000 throw new Exception("Could not find pledge payment record: " . $paymentID);
2002 $this->_relatedObjects
['pledge_payment'][] = $payment;
2006 if (!empty($ids['contributionRecur'])) {
2007 $recur = new CRM_Contribute_BAO_ContributionRecur();
2008 $recur->id
= $ids['contributionRecur'];
2009 if (!$recur->find(TRUE)) {
2010 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2012 $this->_relatedObjects
['contributionRecur'] = &$recur;
2013 //get payment processor id from recur object.
2014 $paymentProcessorID = $recur->payment_processor_id
;
2016 //for normal contribution get the payment processor id.
2017 if (!$paymentProcessorID) {
2018 if ($this->contribution_page_id
) {
2019 // get the payment processor id from contribution page
2020 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2021 $this->contribution_page_id
,
2025 //fail to load payment processor id.
2026 elseif (empty($ids['pledge_payment'])) {
2027 $loadObjectSuccess = TRUE;
2029 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2031 return $loadObjectSuccess;
2036 // we are in event mode
2037 // make sure event exists and is valid
2038 $event = new CRM_Event_BAO_Event();
2039 $event->id
= $ids['event'];
2040 if ($ids['event'] &&
2043 throw new Exception("Could not find event: " . $ids['event']);
2046 $this->_relatedObjects
['event'] = &$event;
2048 $participant = new CRM_Event_BAO_Participant();
2049 $participant->id
= $ids['participant'];
2050 if ($ids['participant'] &&
2051 !$participant->find(TRUE)
2053 throw new Exception("Could not find participant: " . $ids['participant']);
2055 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2057 $this->_relatedObjects
['participant'] = &$participant;
2059 if (!$paymentProcessorID) {
2060 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2064 if ($paymentProcessorID) {
2065 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2066 $this->is_test ?
'test' : 'live'
2068 $ids['paymentProcessor'] = $paymentProcessorID;
2069 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2071 elseif ($required) {
2072 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2079 * Create array of message information - ie. return html version, txt version, to field
2081 * @param array $input incoming information
2082 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2083 * just check presence of recur object but maintaining legacy approach
2085 * @param array $ids IDs of related objects
2086 * @param array $values any values that may have already been compiled by calling process
2087 * This is augmented by values 'gathered' by gatherMessageValues
2088 * @param bool $returnMessageText distinguishes between whether to send message or return
2089 * message text. We are working towards this function ALWAYS returning message text & calling
2090 * function doing emails / pdfs with it
2091 * @return array $messageArray - messages
2097 * @param bool $recur
2098 * @param bool $returnMessageText
2102 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2103 if (empty($this->_relatedObjects
)) {
2104 $this->loadRelatedObjects($input, $ids);
2106 if (empty($this->_component
)) {
2107 $this->_component
= CRM_Utils_Array
::value('component', $input);
2110 //not really sure what params might be passed in but lets merge em into values
2111 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2112 $template = CRM_Core_Smarty
::singleton();
2113 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2114 //what does recur 'mean here - to do with payment processor return functionality but
2115 // what is the importance
2116 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2117 $paymentObject = &CRM_Core_Payment
::singleton(
2118 $this->is_test ?
'test' : 'live',
2119 $this->_relatedObjects
['paymentProcessor']
2122 $entityID = $entity = NULL;
2123 if (isset($ids['contribution'])) {
2124 $entity = 'contribution';
2125 $entityID = $ids['contribution'];
2127 if (!empty($ids['membership'])) {
2128 //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
2129 // 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
2130 // line having loaded an array
2131 $ids['membership'] = (array) $ids['membership'];
2132 $entity = 'membership';
2133 $entityID = $ids['membership'][0];
2136 $url = $paymentObject->subscriptionURL($entityID, $entity);
2137 $template->assign('cancelSubscriptionUrl', $url);
2139 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2140 $template->assign('updateSubscriptionBillingUrl', $url);
2142 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2143 $template->assign('updateSubscriptionUrl', $url);
2145 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2146 //direct mode showing billing block, so use directIPN for temporary
2147 $template->assign('contributeMode', 'directIPN');
2150 // todo remove strtolower - check consistency
2151 if (strtolower($this->_component
) == 'event') {
2152 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2153 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2157 $values['contribution_id'] = $this->id
;
2158 if (!empty($ids['related_contact'])) {
2159 $values['related_contact'] = $ids['related_contact'];
2160 if (isset($ids['onbehalf_dupe_alert'])) {
2161 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2163 $entityBlock = array(
2164 'contact_id' => $ids['contact'],
2165 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2166 'Home', 'id', 'name'
2169 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2170 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2173 if ($this->is_test
) {
2176 if (!empty($this->_relatedObjects
['membership'])) {
2177 foreach ($this->_relatedObjects
['membership'] as $membership) {
2178 if ($membership->id
) {
2179 $values['isMembership'] = TRUE;
2181 // need to set the membership values here
2182 $template->assign('membership_assign', 1);
2183 $template->assign('membership_name',
2184 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2186 $template->assign('mem_start_date', $membership->start_date
);
2187 $template->assign('mem_join_date', $membership->join_date
);
2188 $template->assign('mem_end_date', $membership->end_date
);
2189 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2190 $template->assign('mem_status', $membership_status);
2191 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2192 $template->assign('is_pay_later', 1);
2195 // if separate payment there are two contributions recorded and the
2196 // admin will need to send a receipt for each of them separately.
2197 // we dont link the two in the db (but can potentially infer it if needed)
2198 $template->assign('is_separate_payment', 0);
2200 if ($recur && $paymentObject) {
2201 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2202 $template->assign('cancelSubscriptionUrl', $url);
2203 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2204 $template->assign('updateSubscriptionBillingUrl', $url);
2205 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2206 $template->assign('updateSubscriptionUrl', $url);
2209 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2212 // otherwise if its about sending emails, continue sending without return, as we
2213 // don't want to exit the loop.
2218 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2224 * Gather values for contribution mail - this function has been created
2225 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2226 * Values related to the contribution in question are gathered
2228 * @param array $input input into function (probably from payment processor)
2229 * @param array $ids the set of ids related to the inpurt
2231 * @return array $values
2233 * NB don't add direct calls to the function as we intend to change the signature
2242 public function _gatherMessageValues($input, &$values, $ids = array()) {
2243 // set display address of contributor
2244 if ($this->address_id
) {
2245 $addressParams = array('id' => $this->address_id
);
2246 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2247 $addressDetails = array_values($addressDetails);
2248 $values['address'] = $addressDetails[0]['display'];
2250 if ($this->_component
== 'contribute') {
2251 if (isset($this->contribution_page_id
)) {
2252 CRM_Contribute_BAO_ContributionPage
::setValues(
2253 $this->contribution_page_id
,
2256 if ($this->contribution_page_id
) {
2257 // CRM-8254 - override default currency if applicable
2258 $config = CRM_Core_Config
::singleton();
2259 $config->defaultCurrency
= CRM_Utils_Array
::value(
2262 $config->defaultCurrency
2266 // no contribution page -probably back office
2268 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2269 $values['is_email_receipt'] = 1;
2270 $values['title'] = 'Contribution';
2272 // set lineItem for contribution
2274 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2275 if (!empty($lineItem)) {
2276 $itemId = key($lineItem);
2277 foreach ($lineItem as &$eachItem) {
2278 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2279 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2280 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2281 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2284 $values['lineItem'][0] = $lineItem;
2285 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2289 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2293 // if this is onbehalf of contribution then set related contact
2294 if (!empty($relatedContact['individual_id'])) {
2295 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2300 $eventParams = array(
2301 'id' => $this->_relatedObjects
['event']->id
,
2303 $values['event'] = array();
2305 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2307 //get location details
2308 $locationParams = array(
2309 'entity_id' => $this->_relatedObjects
['event']->id
,
2310 'entity_table' => 'civicrm_event',
2312 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2314 $ufJoinParams = array(
2315 'entity_table' => 'civicrm_event',
2316 'entity_id' => $ids['event'],
2317 'module' => 'CiviEvent',
2320 list($custom_pre_id,
2322 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2324 $values['custom_pre_id'] = $custom_pre_id;
2325 $values['custom_post_id'] = $custom_post_ids;
2327 // set lineItem for event contribution
2329 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2330 if (!empty($participantIds)) {
2331 foreach ($participantIds as $pIDs) {
2332 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2333 if (!CRM_Utils_System
::isNull($lineItem)) {
2334 $values['lineItem'][] = $lineItem;
2345 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2346 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2347 * Note we send directly from this function in some cases because it is only partly refactored
2348 * Don't call this function directly as the signature will change
2352 * @param $template CRM_Core_SMARTY
2353 * @param bool $recur
2354 * @param bool $returnMessageText
2358 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2359 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2360 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2361 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2362 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2363 $template->assign('useForMember', true);
2365 //assign honor information to receipt message
2366 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2368 if (isset($softRecord['soft_credit'])) {
2369 //if id of contribution page is present
2370 if (!empty($values['id'])) {
2371 $values['honor'] = array(
2372 'honor_profile_values' => array(),
2373 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2374 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2376 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2378 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2379 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2382 //offline contribution
2383 $softCreditTypes = $softCredits = array();
2384 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2385 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2386 $softCredits[$key] = array(
2387 'Name' => $softCredit['contact_name'],
2388 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2391 $template->assign('softCreditTypes', $softCreditTypes);
2392 $template->assign('softCredits', $softCredits);
2396 $dao = new CRM_Contribute_DAO_ContributionProduct();
2397 $dao->contribution_id
= $this->id
;
2398 if ($dao->find(TRUE)) {
2399 $premiumId = $dao->product_id
;
2400 $template->assign('option', $dao->product_option
);
2402 $productDAO = new CRM_Contribute_DAO_Product();
2403 $productDAO->id
= $premiumId;
2404 $productDAO->find(TRUE);
2405 $template->assign('selectPremium', TRUE);
2406 $template->assign('product_name', $productDAO->name
);
2407 $template->assign('price', $productDAO->price
);
2408 $template->assign('sku', $productDAO->sku
);
2410 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2411 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2412 if(empty($amount) && isset($this->total_amount
)){
2413 $amount = $this->total_amount
;
2415 $template->assign('amount', $amount);
2416 // add the new contribution values
2417 if (strtolower($this->_component
) == 'contribute') {
2419 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2420 $softDAO->contribution_id
= $this->id
;
2421 if ($softDAO->find(TRUE)) {
2422 $template->assign('pcpBlock', TRUE);
2423 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2424 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2425 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2427 //assign the pcp page title for email subject
2428 $pcpDAO = new CRM_PCP_DAO_PCP();
2429 $pcpDAO->id
= $softDAO->pcp_id
;
2430 if ($pcpDAO->find(TRUE)) {
2431 $template->assign('title', $pcpDAO->title
);
2436 if ($this->financial_type_id
) {
2437 $values['financial_type_id'] = $this->financial_type_id
;
2441 $template->assign('trxn_id', $this->trxn_id
);
2442 $template->assign('receive_date',
2443 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2445 $template->assign('contributeMode', 'notify');
2446 $template->assign('action', $this->is_test ?
1024 : 1);
2447 $template->assign('receipt_text',
2448 CRM_Utils_Array
::value('receipt_text',
2452 $template->assign('is_monetary', 1);
2453 $template->assign('is_recur', (bool) $recur);
2454 $template->assign('currency', $this->currency
);
2455 $template->assign('address', CRM_Utils_Address
::format($input));
2456 if ($this->_component
== 'event') {
2457 $template->assign('title', $values['event']['title']);
2458 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2459 $viewRoles = array();
2460 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2461 $viewRoles[] = $participantRoles[$v];
2463 $values['event']['participant_role'] = implode(', ', $viewRoles);
2464 $template->assign('event', $values['event']);
2465 $template->assign('location', $values['location']);
2466 $template->assign('customPre', $values['custom_pre_id']);
2467 $template->assign('customPost', $values['custom_post_id']);
2470 if ($this->_relatedObjects
['participant']->is_test
) {
2474 $values['params'] = array();
2475 //to get email of primary participant.
2476 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2477 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2478 //build an array of cId/pId of participants
2479 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2480 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2481 //send receipt to additional participant if exists
2482 if (count($additionalIDs)) {
2483 $template->assign('isPrimary', 0);
2484 $template->assign('customProfile', NULL);
2485 //set additionalParticipant true
2486 $values['params']['additionalParticipant'] = TRUE;
2487 foreach ($additionalIDs as $pId => $cId) {
2489 //to change the status pending to completed
2490 $additional = new CRM_Event_DAO_Participant();
2491 $additional->id
= $pId;
2492 $additional->contact_id
= $cId;
2493 $additional->find(TRUE);
2494 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2495 $additional->status_id
= 1;
2496 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2497 //if additional participant dont have email
2499 if (!$additionalParticipantInfo) {
2500 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2502 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2503 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2504 $additional->save();
2505 $additional->free();
2506 $template->assign('amount', $amount);
2507 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2511 //build an array of custom profile and assigning it to template
2512 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2514 if (count($customProfile)) {
2515 $template->assign('customProfile', $customProfile);
2518 // for primary contact
2519 $values['params']['additionalParticipant'] = FALSE;
2520 $template->assign('isPrimary', 1);
2521 $template->assign('amount', $primaryAmount);
2522 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2523 if ($this->payment_instrument_id
) {
2524 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2525 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2527 // carry paylater, since we did not created billing,
2528 // so need to pull email from primary location, CRM-4395
2529 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2535 * Check whether payment processor supports
2536 * cancellation of contribution subscription
2538 * @param int $contributionId contribution id
2540 * @param bool $isNotCancelled
2545 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2546 $cacheKeyString = "$contributionId";
2547 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2549 static $supportsCancel = array();
2551 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2552 $supportsCancel[$cacheKeyString] = FALSE;
2553 $isCancelled = FALSE;
2555 if ($isNotCancelled) {
2556 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2559 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2560 if (!empty($paymentObject)) {
2561 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2564 return $supportsCancel[$cacheKeyString];
2568 * Check whether subscription is already cancelled
2570 * @param int $contributionId contribution id
2572 * @return string $status contribution status
2575 public static function isSubscriptionCancelled($contributionId) {
2577 SELECT cr.contribution_status_id
2578 FROM civicrm_contribution_recur cr
2579 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2580 WHERE con.id = %1 LIMIT 1";
2581 $params = array(1 => array($contributionId, 'Integer'));
2582 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2583 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2584 if ($status == 'Cancelled') {
2591 * Create all financial accounts entry
2593 * @param array $params contribution object, line item array and params for trxn
2596 * @param array $financialTrxnValues
2598 * @return null|object
2601 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2602 $skipRecords = $update = $return = $isRelatedId = FALSE;
2604 $additionalParticipantId = array();
2605 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2607 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2608 $entityId = $params['participant_id'];
2609 $entityTable = 'civicrm_participant';
2610 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2612 elseif (!empty($params['membership_id'])) {
2613 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2614 // are created off one contribution should be handled elsewhere
2615 $entityId = $params['membership_id'];
2616 $entityTable = 'civicrm_membership';
2619 $entityId = $params['contribution']->id
;
2620 $entityTable = 'civicrm_contribution';
2623 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2624 $isRelatedId = TRUE;
2627 $entityID[] = $entityId;
2628 if (!empty($additionalParticipantId)) {
2629 $entityID +
= $additionalParticipantId;
2631 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2632 if (empty($params['prevContribution'])) {
2639 $statusId = $params['contribution']->contribution_status_id
;
2640 // CRM-13964 partial payment
2641 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2642 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2643 $partialAmtPay = $params['partial_amount_pay'];
2644 $partialAmtTotal = $params['partial_payment_total'];
2646 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2647 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2648 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2649 $params['total_amount'] = $partialAmtPay;
2651 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2652 if (empty($balanceTrxnInfo['trxn_id'])) {
2653 // create new balance transaction record
2654 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2655 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2657 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2658 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2659 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2660 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2661 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2662 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2663 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2664 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2665 $balanceTrxnParams['status_id'] = $statusId;
2666 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2667 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2668 if (!empty($params['payment_processor'])) {
2669 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2671 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2675 // build line item array if its not set in $params
2676 if (empty($params['line_item']) ||
$additionalParticipantId) {
2677 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2680 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2681 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2682 $skipRecords = TRUE;
2683 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2684 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2685 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2686 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2688 elseif (!empty($params['payment_processor'])) {
2689 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2691 elseif (!empty($params['payment_instrument_id'])) {
2692 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2695 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2696 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2697 $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);
2700 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2701 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2702 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2705 //build financial transaction params
2706 $trxnParams = array(
2707 'contribution_id' => $params['contribution']->id
,
2708 'to_financial_account_id' => $params['to_financial_account_id'],
2709 'trxn_date' => date('YmdHis'),
2710 'total_amount' => $totalAmount,
2711 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2712 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2713 'currency' => $params['contribution']->currency
,
2714 'trxn_id' => $params['contribution']->trxn_id
,
2715 'status_id' => $statusId,
2716 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2717 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2720 if (!empty($params['payment_processor'])) {
2721 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2724 if (isset($fromFinancialAccountId)) {
2725 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2728 // consider external values passed for recording transaction entry
2729 if (!empty($financialTrxnValues)) {
2730 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2733 $params['trxnParams'] = $trxnParams;
2735 if (!empty($params['prevContribution'])) {
2736 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2737 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2738 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2739 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2740 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2743 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2744 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2745 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))) {
2746 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2747 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2750 //if financial type is changed
2751 if (!empty($params['financial_type_id']) &&
2752 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2753 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2754 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2755 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2756 if ($oldFinancialAccount != $newFinancialAccount) {
2757 $params['total_amount'] = 0;
2758 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2759 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2760 $params['prevContribution']->financial_type_id
, $relationTypeId);
2763 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2764 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2765 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2768 self
::updateFinancialAccounts($params, 'changeFinancialType');
2769 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2770 $params['financial_account_id'] = $newFinancialAccount;
2771 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2772 self
::updateFinancialAccounts($params);
2773 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2777 //Update contribution status
2778 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2779 if (!empty($params['contribution_status_id']) &&
2780 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2781 //Update Financial Records
2782 self
::updateFinancialAccounts($params, 'changedStatus');
2785 // change Payment Instrument for a Completed contribution
2786 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2787 // instrument is null and now new payment instrument is added along with the payment
2788 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2789 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2790 if (array_key_exists('payment_instrument_id', $params)) {
2791 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2792 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2793 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2794 //check if status is changed from Pending to Completed
2795 // do not update payment instrument changes for Pending to Completed
2796 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2797 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2798 // for all other statuses create new financial records
2799 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2800 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2801 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2804 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2805 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2806 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2807 // for any other payment instrument changes create new financial records
2808 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2809 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2810 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2812 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2813 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2814 // another special case when check number is changed, create new financial records
2815 // create financial trxn with negative amount
2816 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2817 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2818 // create financial trxn with positive amount
2819 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2820 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2821 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2825 //if Change contribution amount
2826 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2827 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2828 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2829 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2830 if (isset($totalAmount) &&
2831 $totalAmount != $params['prevContribution']->total_amount
) {
2832 //Update Financial Records
2833 $params['trxnParams']['from_financial_account_id'] = NULL;
2834 self
::updateFinancialAccounts($params, 'changedAmount');
2839 // records finanical trxn and entity financial trxn
2840 // also make it available as return value
2841 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2842 $params['entity_id'] = $financialTxn->id
;
2845 // record line items and finacial items
2846 if (empty($params['skipLineItem'])) {
2847 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2850 // create batch entry if batch_id is passed
2851 if (!empty($params['batch_id'])) {
2852 $entityParams = array(
2853 'batch_id' => $params['batch_id'],
2854 'entity_table' => 'civicrm_financial_trxn',
2855 'entity_id' => $financialTxn->id
,
2857 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2860 // when a fee is charged
2861 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2862 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2865 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2866 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2867 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2868 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2869 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2871 unset($params['line_item']);
2877 * Update all financial accounts entry
2879 * @param array $params contribution object, line item array and params for trxn
2881 * @param string $context update scenarios
2883 * @param null $skipTrxn
2887 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2888 $itemAmount = $trxnID = NULL;
2889 //get all the statuses
2890 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2891 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2892 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2893 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2894 && $context == 'changePaymentInstrument') {
2897 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2898 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2900 if ($context == 'changedStatus') {
2901 //get all the statuses
2902 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2904 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2905 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2906 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2907 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2909 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2910 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2911 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2912 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2913 $params['trxnParams']['to_financial_account_id'] = NULL;
2914 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2916 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2917 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2918 $financialTypeID, $relationTypeId);
2920 $itemAmount = $params['trxnParams']['total_amount'];
2922 elseif ($context == 'changePaymentInstrument') {
2923 if ($params['trxnParams']['total_amount'] < 0) {
2924 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2925 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2926 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2927 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2931 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2932 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2935 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2936 $params['entity_id'] = $trxn->id
;
2938 if ($context == 'changedStatus') {
2939 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2940 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2941 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2942 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2943 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2945 $entityParams = array(
2946 'entity_table' => 'civicrm_financial_item',
2947 'financial_trxn_id' => $trxn->id
,
2949 if (empty($params['line_item'])) {
2951 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
2952 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
2953 // & this can be removed
2956 foreach ($params['line_item'] as $fieldId => $fields) {
2957 foreach ($fields as $fieldValueId => $fieldValues) {
2959 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2960 2 => array($fieldValues['id'], 'Integer'),
2962 CRM_Core_DAO
::executeQuery($query, $fparams);
2964 1 => array($fieldValues['id'], 'Integer'),
2966 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2967 while ($financialItem->fetch()) {
2968 $entityParams['entity_id'] = $financialItem->id
;
2969 $entityParams['amount'] = $financialItem->amount
;
2970 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2977 if ($context != 'changePaymentInstrument') {
2978 $itemParams['entity_table'] = 'civicrm_line_item';
2979 $trxnIds['id'] = $params['entity_id'];
2980 foreach ($params['line_item'] as $fieldId => $fields) {
2981 foreach ($fields as $fieldValueId => $fieldValues) {
2982 $prevParams['entity_id'] = $fieldValues['id'];
2983 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2985 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2986 if ($params['contribution']->receive_date
) {
2987 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2990 $financialAccount = $prevfinancialItem->financial_account_id
;
2991 if (!empty($params['financial_account_id'])) {
2992 $financialAccount = $params['financial_account_id'];
2995 $currency = $params['prevContribution']->currency
;
2996 if ($params['contribution']->currency
) {
2997 $currency = $params['contribution']->currency
;
3000 if (!empty($params['is_quick_config'])) {
3001 $amount = $itemAmount;
3003 $amount = $params['total_amount'];
3007 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3008 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)) {
3011 $amount = $diff * $fieldValues['line_total'];
3014 $itemParams = array(
3015 'transaction_date' => $receiveDate,
3016 'contact_id' => $params['prevContribution']->contact_id
,
3017 'currency' => $currency,
3018 'amount' => $amount,
3019 'description' => $prevfinancialItem->description
,
3020 'status_id' => $prevfinancialItem->status_id
,
3021 'financial_account_id' => $financialAccount,
3022 'entity_table' => 'civicrm_line_item',
3023 'entity_id' => $fieldValues['id']
3025 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3027 if ($fieldValues['tax_amount']) {
3028 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3029 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3030 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3031 $itemParams['description'] = $taxTerm;
3032 if ($fieldValues['financial_type_id']) {
3033 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3035 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3043 * Check status validation on update of a contribution
3045 * @param array $values previous form values before submit
3047 * @param array $fields the input form values
3049 * @param array $errors list of errors
3054 public static function checkStatusValidation($values, &$fields, &$errors) {
3055 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3056 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3057 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3061 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3062 $checkStatus = array(
3063 'Cancelled' => array('Completed', 'Refunded'),
3064 'Completed' => array('Cancelled', 'Refunded'),
3065 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3066 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3067 'Refunded' => array('Cancelled', 'Completed')
3070 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3071 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(1 => $contributionStatuses[$values['contribution_status_id']], 2 => $contributionStatuses[$fields['contribution_status_id']]));
3076 * Delete contribution of contact
3080 * @param integer $contactId contact id
3084 public static function deleteContactContribution($contactId) {
3085 $contribution = new CRM_Contribute_DAO_Contribution();
3086 $contribution->contact_id
= $contactId;
3087 $contribution->find();
3088 while ($contribution->fetch()) {
3089 self
::deleteContribution($contribution->id
);
3094 * Get options for a given contribution field.
3095 * @see CRM_Core_DAO::buildOptions
3097 * @param String $fieldName
3098 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3099 * @param Array $props : whatever is known about this dao object
3101 * @return Array|bool
3103 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3104 $className = __CLASS__
;
3106 switch ($fieldName) {
3107 // This field is not part of this object but the api supports it
3108 case 'payment_processor':
3109 $className = 'CRM_Contribute_BAO_ContributionPage';
3110 // Filter results by contribution page
3111 if (!empty($props['contribution_page_id'])) {
3112 $page = civicrm_api('contribution_page', 'getsingle', array(
3114 'id' => ($props['contribution_page_id'])
3116 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3117 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3120 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3121 case 'honor_type_id':
3122 $className = 'CRM_Contribute_BAO_ContributionSoft';
3123 $fieldName = 'soft_credit_type_id';
3124 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3127 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3131 * Validate financial type
3135 * @param integer $financialTypeId Financial Type id
3137 * @param string $relationName
3139 * @return array|bool
3142 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3143 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3144 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3146 if (!$financialAccount) {
3147 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3154 * Function to record additional payment for partial and refund contributions
3156 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3157 * @param array $trxnData : to take user provided input of transaction details.
3158 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3161 * @param int $contributionId
3163 * @param string $paymentType
3164 * @param int $participantId
3166 * @return null|object
3168 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3169 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3170 $getInfoOf['id'] = $contributionId;
3171 $defaults = array();
3172 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3174 if ($paymentType == 'owed') {
3175 // build params for recording financial trxn entry
3176 $params['contribution'] = $contributionDAO;
3177 $params = array_merge($defaults, $params);
3178 $params['skipLineItem'] = TRUE;
3179 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3180 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3181 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3184 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3185 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3186 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3188 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3189 if (!empty($trxnId)) {
3190 $trxnId = $trxnId['trxn_id'];
3192 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3193 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3196 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3197 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3198 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3202 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3203 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3204 FROM civicrm_financial_trxn ft
3205 LEFT JOIN civicrm_entity_financial_trxn eft
3206 ON (ft.id = eft.financial_trxn_id)
3207 WHERE eft.entity_table = 'civicrm_contribution'
3208 AND eft.entity_id = {$contributionId}
3209 AND ft.to_financial_account_id != {$toFinancialAccount}
3210 AND ft.status_id = {$statusId}
3212 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3215 if ($contributionDAO->total_amount
== $sumOfPayments) {
3216 // update contribution status and
3217 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3218 $contributionDAO->contribution_status_id
= $statusId;
3219 $contributionDAO->cancel_date
= 'null';
3220 $contributionDAO->cancel_reason
= NULL;
3221 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3222 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3223 $contributionDAO->save();
3225 //Change status of financial record too
3226 $financialTrxn->status_id
= $statusId;
3227 $financialTrxn->save();
3229 // note : not using the self::add method,
3230 // the reason because it performs 'status change' related code execution for financial records
3231 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3232 // are coded below i.e. just updating financial_item status to 'Paid'
3234 if ($participantId) {
3235 // update participant status
3236 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3237 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3238 foreach ($ids as $val) {
3239 $participantUpdate['id'] = $val;
3240 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3241 CRM_Event_BAO_Participant
::add($participantUpdate);
3245 // update financial item statuses
3246 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3247 $paidStatus = array_search('Paid', $financialItemStatus);
3249 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3250 $sqlFinancialItemUpdate = "
3251 UPDATE civicrm_financial_item fi
3252 LEFT JOIN civicrm_entity_financial_trxn eft
3253 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3254 SET status_id = {$paidStatus}
3255 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3257 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3260 elseif ($paymentType == 'refund') {
3261 // build params for recording financial trxn entry
3262 $params['contribution'] = $contributionDAO;
3263 $params = array_merge($defaults, $params);
3264 $params['skipLineItem'] = TRUE;
3265 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3266 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3268 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3269 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3270 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3272 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3274 // note : not using the self::add method,
3275 // the reason because it performs 'status change' related code execution for financial records
3276 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3277 // are coded below i.e. just updating financial_item status to 'Paid'
3278 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3280 // add financial item entry
3281 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3282 $getLine['entity_id'] = $contributionDAO->id
;
3283 $getLine['entity_table'] = 'civicrm_contribution';
3284 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3285 if (!empty($lineItemId->id
)) {
3286 $addFinancialEntry = array(
3287 'transaction_date' => $financialTrxn->trxn_date
,
3288 'contact_id' => $contributionDAO->contact_id
,
3289 'amount' => $financialTrxn->total_amount
,
3290 'status_id' => array_search('Paid', $financialItemStatus),
3291 'entity_id' => $lineItemId->id
,
3292 'entity_table' => 'civicrm_line_item'
3294 $trxnIds['id'] = $financialTrxn->id
;
3295 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3297 if ($participantId) {
3298 // update participant status
3299 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3300 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3301 foreach ($ids as $val) {
3302 $participantUpdate['id'] = $val;
3303 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3304 CRM_Event_BAO_Participant
::add($participantUpdate);
3309 // activity creation
3310 if (!empty($financialTrxn)) {
3311 if ($participantId) {
3312 $inputParams['id'] = $participantId;
3315 $component = 'event';
3316 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3317 $entityObj = $entityObj[$participantId];
3319 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3321 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3323 return $financialTrxn;
3329 * @param $activityType
3331 * @param int $contributionId
3333 * @throws CRM_Core_Exception
3335 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3336 if ($component == 'event') {
3337 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3338 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3339 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3340 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3341 $targetCid = $entityObj->contact_id
;
3342 // source record id would be the contribution id
3343 $srcRecId = $contributionId;
3347 $activityParams = array(
3348 'source_contact_id' => $targetCid,
3349 'source_record_id' => $srcRecId,
3350 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3354 'subject' => $subject,
3355 'activity_date_time' => $date,
3356 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3360 'skipRecentView' => TRUE,
3363 // create activity with target contacts
3364 $session = CRM_Core_Session
::singleton();
3365 $id = $session->get('userID');
3367 $activityParams['source_contact_id'] = $id;
3368 $activityParams['target_contact_id'][] = $targetCid;
3370 CRM_Activity_BAO_Activity
::create($activityParams);
3374 * Get list of payments displayed by Contribute_Page_PaymentInfo
3378 * @param bool $getTrxnInfo
3379 * @param bool $usingLineTotal
3383 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3384 if ($component == 'event') {
3385 $entity = 'participant';
3386 $entityTable = 'civicrm_participant';
3387 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3389 if (!$contributionId) {
3390 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3391 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3392 $id = $primaryParticipantId;
3394 if (!$contributionId) {
3399 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3400 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3406 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3407 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3410 if (empty($total) ||
$usingLineTotal) {
3411 // for additional participants
3412 if ($entityTable == 'civicrm_participant') {
3413 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3415 foreach ($ids as $val) {
3416 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3420 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3424 $baseTrxnId = $total['trxn_id'];
3425 $total = $total['total_amount'];
3428 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3429 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3431 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3432 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3433 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3435 if ($paymentBalance == 0 && $contributionIsPayLater) {
3436 $paymentBalance = $total;
3439 $info['total'] = $total;
3440 $info['paid'] = $total - $paymentBalance;
3441 $info['balance'] = $paymentBalance;
3443 $info['component'] = $component;
3444 $info['payLater'] = $contributionIsPayLater;
3446 if ($getTrxnInfo && $baseTrxnId) {
3447 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3449 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3450 FROM civicrm_contribution con
3451 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3452 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3453 WHERE con.id = {$contributionId}
3456 // conditioned WHERE clause
3458 // if balance trxn exists don't include details of it in transaction info
3459 $sql .= " AND ft.id != {$baseTrxnId} ";
3461 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3463 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3464 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3465 while($resultDAO->fetch()) {
3466 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3467 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3469 'total_amount' => $resultDAO->total_amount
,
3470 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3471 'payment_instrument' => $paidByLabel,
3472 'receive_date' => $resultDAO->trxn_date
,
3473 'trxn_id' => $resultDAO->trxn_id
,
3474 'status' => $statuses[$resultDAO->status_id
],
3476 if ($paidByName == 'Check') {
3477 $val['check_number'] = $resultDAO->check_number
;
3481 $info['transaction'] = $rows;
3487 * Get financial account id has 'Sales Tax Account is'
3488 * account relationship with financial type
3490 * @param int $financialTypeId
3492 * @return FinancialAccountId
3494 public static function getFinancialAccountId($financialTypeId) {
3495 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3496 $searchParams = array(
3497 'entity_table' => 'civicrm_financial_type',
3498 'entity_id' => $financialTypeId,
3499 'account_relationship' => $accountRel,
3502 CRM_Financial_BAO_FinancialTypeAccount
::retrieve( $searchParams, $result );
3504 return CRM_Utils_Array
::value( 'financial_account_id', $result );
3507 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3508 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3510 // Update contribution
3511 if (!empty($params['id'])) {
3512 $id = $params['id'];
3513 $values = $ids = array();
3514 $contrbutionParams = array('id' => $id);
3515 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3517 // To assign pervious finantial type on update of contribution
3518 if (!isset($params['financial_type_id'])) {
3519 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3521 else if (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3522 // Assisn tax Amount on update of contrbution
3523 if (!empty($prevContributionValue->tax_amount
)) {
3524 $params['tax_amount'] = 'null';
3525 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3526 foreach ($params['line_item'] as $setID => $priceField) {
3527 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3528 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3535 // New Contrbution and update of contribution with tax rate financial type
3536 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3537 empty($params['skipLineItem']) && !$isLineItem)
3539 $taxRateParams = $taxRates[$params['financial_type_id']];
3540 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3541 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3543 // Get Line Item on update of contribution
3544 if (isset($params['id'])) {
3545 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3548 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3550 foreach ($params['line_item'] as $setID => $priceField) {
3551 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3552 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3555 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3557 else if (isset($params['api.line_item.create'])) {
3558 // Update total amount of contribution using lineItem
3559 $taxAmountArray = array();
3560 foreach ($params['api.line_item.create'] as $key => $value) {
3561 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3562 $taxRate = $taxRates[$value['financial_type_id']];
3563 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3564 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3567 $params['tax_amount'] = array_sum($taxAmountArray);
3568 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3571 // update line item of contrbution
3572 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3573 $taxRate = $taxRates[$params['financial_type_id']];
3574 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3575 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);