3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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;
76 * @return \CRM_Contribute_DAO_Contribution
81 function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params (reference ) an assoc array of name/value pairs
93 * @param array $ids the array that holds all the db ids
95 * @return CRM_Contribute_BAO_Contribution object
99 static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
139 self
::calculateMissingAmountParams($params);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
174 $config = CRM_Core_Config
::singleton();
175 $contribution->currency
= $config->defaultCurrency
;
178 if ($contributionID && $setPrevContribution) {
179 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
182 $result = $contribution->save();
184 // Add financial_trxn details as part of fix for CRM-4724
185 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
186 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
188 //add Account details
189 $params['contribution'] = $contribution;
190 self
::recordFinancialAccounts($params);
192 // reset the group contact cache for this group
193 CRM_Contact_BAO_GroupContactCache
::remove();
195 if ($contributionID) {
196 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
199 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
206 * Get defaults for new entity
209 static function getDefaults() {
211 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
212 FALSE, FALSE, FALSE, 'AND is_default = 1')
214 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
219 * Given the list of params in the params array, fetch the object
220 * and store the values in the values array
222 * @param array $params input parameters to find object
223 * @param array $values output values of the object
224 * @param array $ids the array that holds all the db ids
226 * @return CRM_Contribute_BAO_Contribution|null the found object or null
230 static function &getValues($params, &$values, &$ids) {
231 if (empty($params)) {
234 $contribution = new CRM_Contribute_BAO_Contribution();
236 $contribution->copyValues($params);
238 if ($contribution->find(TRUE)) {
239 $ids['contribution'] = $contribution->id
;
241 CRM_Core_DAO
::storeValues($contribution, $values);
243 return $contribution;
245 $null = NULL; // return by reference
250 * @param array $params
254 public static function calculateMissingAmountParams(&$params) {
255 if (!isset($params['fee_amount'])) {
256 if (isset($params['total_amount']) && isset($params['net_amount'])) {
257 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
260 $params['fee_amount'] = 0;
263 if (!isset($params['net_amount'])) {
264 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
269 * Get the number of terms for this contribution for a given membership type
270 * based on querying the line item table and relevant price field values
271 * Note that any one contribution should only be able to have one line item relating to a particular membership
274 * @param int $membershipTypeID
276 * @param int $contributionID
280 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
281 $numTerms = CRM_Core_DAO
::singleValueQuery("
282 SELECT membership_num_terms FROM civicrm_line_item li
283 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
284 WHERE contribution_id = %1 AND membership_type_id = %2",
285 array(1 => array($contributionID, 'Integer') , 2 => array($membershipTypeID, 'Integer'))
287 // default of 1 is precautionary
288 return empty($numTerms) ?
1 : $numTerms;
292 * Takes an associative array and creates a contribution object
294 * @param array $params (reference ) an assoc array of name/value pairs
295 * @param array $ids the array that holds all the db ids
297 * @return CRM_Contribute_BAO_Contribution object
301 static function create(&$params, $ids = array()) {
302 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
303 foreach ($dateFields as $df) {
304 if (isset($params[$df])) {
305 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
309 $transaction = new CRM_Core_Transaction();
311 $contribution = self
::add($params, $ids);
313 if (is_a($contribution, 'CRM_Core_Error')) {
314 $transaction->rollback();
315 return $contribution;
318 $params['contribution_id'] = $contribution->id
;
320 if (!empty($params['custom']) &&
321 is_array($params['custom'])
323 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
326 $session = CRM_Core_Session
::singleton();
328 if (!empty($params['note'])) {
330 'entity_table' => 'civicrm_contribution',
331 'note' => $params['note'],
332 'entity_id' => $contribution->id
,
333 'contact_id' => $session->get('userID'),
334 'modified_date' => date('Ymd'),
336 if (!$noteParams['contact_id']) {
337 $noteParams['contact_id'] = $params['contact_id'];
339 CRM_Core_BAO_Note
::add($noteParams);
342 // make entry in batch entity batch table
343 if (!empty($params['batch_id'])) {
344 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
345 $titleFields = array(
351 $retrieveRequired = 0;
352 foreach ($titleFields as $titleField) {
353 if(!isset($contribution->$titleField)){
354 $retrieveRequired = 1;
358 if ($retrieveRequired == 1) {
359 $contribution->find(TRUE);
363 // check if activity record exist for this contribution, if
365 $activity = new CRM_Activity_DAO_Activity();
366 $activity->source_record_id
= $contribution->id
;
367 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
371 if (!$activity->find(TRUE)) {
372 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
375 // CRM-13237 : if activity record found, update it with campaign id of contribution
376 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
379 // Handle soft credit and / or link to personal campaign page
380 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
382 //Delete PCP against this contribution and create new on submitted PCP information
383 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
385 $deleteParams = array('id' => $pcpId);
386 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
388 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
389 $softParams = array();
390 $softParams['contribution_id'] = $contribution->id
;
391 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
392 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
393 $pcp['pcp_made_through_id'], 'contact_id'
395 $softParams['currency'] = $contribution->currency
;
396 $softParams['amount'] = $contribution->total_amount
;
397 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
398 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
399 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
400 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
401 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
403 if (isset($params['soft_credit'])) {
404 $softParams = $params['soft_credit'];
406 if (!empty($softIDs)) {
407 foreach ( $softIDs as $softID) {
408 if (!in_array($softID, $params['soft_credit_ids'])) {
409 $deleteParams = array('id' => $softID);
410 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
415 foreach ($softParams as $softParam) {
416 $softParam['contribution_id'] = $contribution->id
;
417 $softParam['currency'] = $contribution->currency
;
418 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
419 if (empty($softParam['amount'])) {
420 $softParam['amount'] = $contribution->total_amount
;
422 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
426 $transaction->commit();
428 // do not add to recent items for import, CRM-4399
429 if (empty($params['skipRecentView'])) {
430 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
431 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
433 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
434 $titleFields = array(
440 $retrieveRequired = 0;
441 foreach ($titleFields as $titleField) {
442 if(!isset($contribution->$titleField)){
443 $retrieveRequired = 1;
447 if($retrieveRequired == 1){
448 $contribution->find(TRUE);
450 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
451 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
453 $recentOther = array();
454 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
455 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
456 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
460 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
461 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
462 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
466 // add the recently created Contribution
467 CRM_Utils_Recent
::add($title,
471 $contribution->contact_id
,
477 return $contribution;
481 * Get the values for pseudoconstants for name->value and reverse.
483 * @param array $defaults (reference) the default values, some of which need to be resolved.
484 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
490 static function resolveDefaults(&$defaults, $reverse = FALSE) {
491 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
492 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
493 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
494 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
498 * This function is used to convert associative array names to values
501 * This function is used by both the web form layer and the api. Note that
502 * the api needs the name => value conversion, also the view layer typically
503 * requires value => name conversion
505 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
506 $id = $property . '_id';
508 $src = $reverse ?
$property : $id;
509 $dst = $reverse ?
$id : $property;
511 if (!array_key_exists($src, $defaults)) {
515 $look = $reverse ?
array_flip($lookup) : $lookup;
517 if (is_array($look)) {
518 if (!array_key_exists($defaults[$src], $look)) {
522 $defaults[$dst] = $look[$defaults[$src]];
527 * Takes a bunch of params that are needed to match certain criteria and
528 * retrieves the relevant objects. We'll tweak this function to be more
529 * full featured over a period of time. This is the inverse function of
530 * create. It also stores all the retrieved values in the default array
532 * @param array $params (reference ) an assoc array of name/value pairs
533 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
534 * in a hierarchical manner
535 * @param array $ids (reference) the array that holds all the db ids
537 * @return CRM_Contribute_BAO_Contribution object
541 static function retrieve(&$params, &$defaults, &$ids) {
542 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
543 return $contribution;
547 * Combine all the importable fields from the lower levels object
549 * The ordering is important, since currently we do not have a weight
550 * scheme. Adding weight is super important and should be done in the
551 * next week or so, before this can be called complete.
553 * @param string $contactType
554 * @param bool $status
556 * @return array array of importable Fields
560 static function &importableFields($contactType = 'Individual', $status = TRUE) {
561 if (!self
::$_importableFields) {
562 if (!self
::$_importableFields) {
563 self
::$_importableFields = array();
567 $fields = array('' => array('title' => ts('- do not import -')));
570 $fields = array('' => array('title' => ts('- Contribution Fields -')));
573 $note = CRM_Core_DAO_Note
::import();
574 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
575 unset($tmpFields['option_value']);
576 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
577 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
579 // Using new Dedupe rule.
581 'contact_type' => $contactType,
582 'used' => 'Unsupervised',
584 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
585 $tmpContactField = array();
586 if (is_array($fieldsArray)) {
587 foreach ($fieldsArray as $value) {
588 //skip if there is no dupe rule
589 if ($value == 'none') {
592 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
597 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
598 $tmpContactField[trim($value)] = $contactFields[trim($value)];
600 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
603 $title = $tmpContactField[trim($value)]['title'];
605 $tmpContactField[trim($value)]['title'] = $title;
609 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
610 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
611 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
612 $fields = array_merge($fields, $tmpContactField);
613 $fields = array_merge($fields, $tmpFields);
614 $fields = array_merge($fields, $note);
615 $fields = array_merge($fields, $optionFields);
616 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
617 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
618 self
::$_importableFields = $fields;
620 return self
::$_importableFields;
626 static function &exportableFields() {
627 if (!self
::$_exportableFields) {
628 if (!self
::$_exportableFields) {
629 self
::$_exportableFields = array();
632 $impFields = CRM_Contribute_DAO_Contribution
::export();
633 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
634 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
635 $typeField = CRM_Financial_DAO_FinancialType
::export();
636 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
637 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
638 $contributionStatus = array(
639 'contribution_status' => array(
640 'title' => ts('Contribution Status'),
641 'name' => 'contribution_status',
642 'data_type' => CRM_Utils_Type
::T_STRING
645 $contributionNote = array(
646 'contribution_note' =>
648 'title' => ts('Contribution Note'),
649 'name' => 'contribution_note',
650 'data_type' => CRM_Utils_Type
::T_TEXT
654 $contributionRecurId = array(
655 'contribution_recur_id' => array(
656 'title' => ts('Recurring Contributions ID'),
657 'name' => 'contribution_recur_id',
658 'where' => 'civicrm_contribution.contribution_recur_id',
659 'data_type' => CRM_Utils_Type
::T_INT
662 $extraFields = array(
663 'contribution_batch' => array(
664 'title' => ts('Batch Name')
668 $softCreditFields = array(
669 'contribution_soft_credit_name' => array(
670 'name' => 'contribution_soft_credit_name',
671 'title' => 'Soft Credit For',
672 'where' => 'civicrm_contact_d.display_name',
673 'data_type' => CRM_Utils_Type
::T_STRING
675 'contribution_soft_credit_amount' => array(
676 'name' => 'contribution_soft_credit_amount',
677 'title' => 'Soft Credit Amount',
678 'where' => 'civicrm_contribution_soft.amount',
679 'data_type' => CRM_Utils_Type
::T_MONEY
681 'contribution_soft_credit_type' => array(
682 'name' => 'contribution_soft_credit_type',
683 'title' => 'Soft Credit Type',
684 'where' => 'contribution_softcredit_type.label',
685 'data_type' => CRM_Utils_Type
::T_STRING
687 'contribution_soft_credit_contribution_id' => array(
688 'name' => 'contribution_soft_credit_contribution_id',
689 'title' => 'Soft Credit For Contribution ID',
690 'where' => 'civicrm_contribution_soft.contribution_id',
691 'data_type' => CRM_Utils_Type
::T_INT
695 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
696 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
697 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
700 self
::$_exportableFields = $fields;
703 return self
::$_exportableFields;
707 * @param null $status
708 * @param null $startDate
709 * @param null $endDate
713 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
717 $where[] = 'contribution_status_id = 1';
721 $where[] = 'contribution_status_id = 3';
726 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
729 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
732 $whereCond = implode(' AND ', $where);
735 SELECT sum( total_amount ) as total_amount,
736 count( civicrm_contribution.id ) as total_count,
738 FROM civicrm_contribution
739 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
741 AND ( is_test = 0 OR is_test IS NULL )
742 AND contact.is_deleted = 0
746 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
749 while ($dao->fetch()) {
750 $count +
= $dao->total_count
;
751 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
754 return array('amount' => implode(', ', $amount),
762 * Delete the indirect records associated with this contribution first
766 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
769 static function deleteContribution($id) {
770 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
772 $transaction = new CRM_Core_Transaction();
775 //delete activity record
777 'source_record_id' => $id,
778 // activity type id for contribution
779 'activity_type_id' => 6,
782 CRM_Activity_BAO_Activity
::deleteActivity($params);
784 //delete billing address if exists for this contribution.
785 self
::deleteAddress($id);
787 //update pledge and pledge payment, CRM-3961
788 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
790 // remove entry from civicrm_price_set_entity, CRM-5095
791 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
792 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
794 // cleanup line items.
795 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
797 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
798 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
800 if ($participantId) {
801 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
804 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
808 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
809 $noteId = key($note);
811 CRM_Core_BAO_Note
::del($noteId, FALSE);
814 $dao = new CRM_Contribute_DAO_Contribution();
817 $results = $dao->delete();
819 $transaction->commit();
821 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
823 // delete the recently created Contribution
824 $contributionRecent = array(
826 'type' => 'Contribution',
828 CRM_Utils_Recent
::del($contributionRecent);
834 * Check if there is a contribution with the same trxn_id or invoice_id
836 * @param array $input an assoc array of name/value pairs
837 * @param array $duplicates (reference ) store ids of duplicate contribs
841 * @return boolean true if duplicate, false otherwise
845 static function checkDuplicate($input, &$duplicates, $id = NULL) {
847 $id = CRM_Utils_Array
::value('id', $input);
849 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
850 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
856 $clause[] = "trxn_id = %1";
857 $input[1] = array($trxn_id, 'String');
861 $clause[] = "invoice_id = %2";
862 $input[2] = array($invoice_id, 'String');
865 if (empty($clause)) {
869 $clause = implode(' OR ', $clause);
871 $clause = "( $clause ) AND id != %3";
872 $input[3] = array($id, 'Integer');
875 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
876 $dao = CRM_Core_DAO
::executeQuery($query, $input);
878 while ($dao->fetch()) {
879 $duplicates[] = $dao->id
;
886 * Takes an associative array and creates a contribution_product object
888 * the function extract all the params it needs to initialize the create a
889 * contribution_product object. the params array could contain additional unused name/value
892 * @param array $params (reference ) an assoc array of name/value pairs
894 * @return CRM_Contribute_BAO_ContributionProduct object
898 static function addPremium(&$params) {
899 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
900 $contributionProduct->copyValues($params);
901 return $contributionProduct->save();
905 * Get list of contribution fields for profile
906 * For now we only allow custom contribution fields to be in
909 * @param boolean $addExtraFields true if special fields needs to be added
911 * @return array the list of contribution fields
915 static function getContributionFields($addExtraFields = TRUE) {
916 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
917 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
919 if ($addExtraFields) {
920 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
923 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
925 foreach ($contributionFields as $key => $var) {
926 if ($key == 'contribution_contact_id') {
929 elseif ($key == 'contribution_campaign_id') {
930 $var['title'] = ts('Campaign');
932 $fields[$key] = $var;
935 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
940 * Add extra fields specific to contribtion
944 static function getSpecialContributionFields() {
945 $extraFields = array(
946 'contribution_soft_credit_name' => array(
947 'name' => 'contribution_soft_credit_name',
948 'title' => 'Soft Credit Name',
949 'headerPattern' => '/^soft_credit_name$/i',
950 'where' => 'civicrm_contact_d.display_name',
952 'contribution_soft_credit_email' => array(
953 'name' => 'contribution_soft_credit_email',
954 'title' => 'Soft Credit Email',
955 'headerPattern' => '/^soft_credit_email$/i',
956 'where' => 'soft_email.email',
958 'contribution_soft_credit_phone' => array(
959 'name' => 'contribution_soft_credit_phone',
960 'title' => 'Soft Credit Phone',
961 'headerPattern' => '/^soft_credit_phone$/i',
962 'where' => 'soft_phone.phone',
964 'contribution_soft_credit_contact_id' => array(
965 'name' => 'contribution_soft_credit_contact_id',
966 'title' => 'Soft Credit Contact ID',
967 'headerPattern' => '/^soft_credit_contact_id$/i',
968 'where' => 'civicrm_contribution_soft.contact_id',
980 static function getCurrentandGoalAmount($pageID) {
982 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
983 FROM civicrm_contribution_page p,
984 civicrm_contribution c
985 WHERE p.id = c.contribution_page_id
987 AND c.cancel_date is null
991 $config = CRM_Core_Config
::singleton();
992 $params = array(1 => array($pageID, 'Integer'));
993 $dao = CRM_Core_DAO
::executeQuery($query, $params);
996 return array($dao->goal
, $dao->total
);
999 return array(NULL, NULL);
1004 * Get list of contribution In Honor of contact Ids
1006 * @param int $honorId In Honor of Contact ID
1008 * @return return the list of contribution fields
1013 static function getHonorContacts($honorId) {
1015 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1016 $honorDAO->contact_id
= $honorId;
1019 $type = CRM_Contribute_PseudoConstant
::financialType();
1021 while ($honorDAO->fetch()) {
1022 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1023 $contributionDAO->id
= $honorDAO->contribution_id
;
1025 if ($contributionDAO->find(TRUE)) {
1026 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1027 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1028 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1029 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1030 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1031 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1032 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1033 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1034 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1042 * Get the sort name of a contact for a particular contribution
1044 * @param int $id id of the contribution
1046 * @return null|string sort name of the contact if found
1050 static function sortName($id) {
1051 $id = CRM_Utils_Type
::escape($id, 'Integer');
1054 SELECT civicrm_contact.sort_name
1055 FROM civicrm_contribution, civicrm_contact
1056 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1057 AND civicrm_contribution.id = {$id}
1059 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1063 * @param int $contactID
1067 static function annual($contactID) {
1068 if (is_array($contactID)) {
1069 $contactIDs = implode(',', $contactID);
1072 $contactIDs = $contactID;
1075 $config = CRM_Core_Config
::singleton();
1076 $startDate = $endDate = NULL;
1078 $currentMonth = date('m');
1079 $currentDay = date('d');
1080 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1081 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1082 (int ) $config->fiscalYearStart
['d'] > $currentDay
1085 $year = date('Y') - 1;
1090 $nextYear = $year +
1;
1092 if ($config->fiscalYearStart
) {
1093 if ($config->fiscalYearStart
['M'] < 10) {
1094 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1096 if ($config->fiscalYearStart
['d'] < 10) {
1097 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1099 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1104 $startDate = "$year$monthDay";
1105 $endDate = "$nextYear$monthDay";
1108 SELECT count(*) as count,
1109 sum(total_amount) as amount,
1110 avg(total_amount) as average,
1112 FROM civicrm_contribution b
1113 WHERE b.contact_id IN ( $contactIDs )
1114 AND b.contribution_status_id = 1
1116 AND b.receive_date >= $startDate
1117 AND b.receive_date < $endDate
1120 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1122 $amount = $average = array();
1123 while ($dao->fetch()) {
1124 if ($dao->count
> 0 && $dao->amount
> 0) {
1125 $count +
= $dao->count
;
1126 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1127 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1133 implode(', ', $amount),
1134 implode(', ', $average),
1137 return array(0, 0, 0);
1141 * Check if there is a contribution with the params passed in.
1142 * Used for trxn_id,invoice_id and contribution_id
1144 * @param array $params an assoc array of name/value pairs
1146 * @return array contribution id if success else NULL
1150 static function checkDuplicateIds($params) {
1151 $dao = new CRM_Contribute_DAO_Contribution();
1155 foreach ($params as $k => $v) {
1157 $clause[] = "$k = '$v'";
1160 $clause = implode(' AND ', $clause);
1161 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1162 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1164 while ($dao->fetch()) {
1172 * Get the contribution details for component export
1174 * @param int $exportMode export mode
1175 * @param string $componentIds component ids
1177 * @return array associated array
1182 static function getContributionDetails($exportMode, $componentIds) {
1183 $paymentDetails = array();
1184 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1186 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1187 $componentSelect = " civicrm_participant_payment.participant_id id";
1188 $additionalClause = "
1189 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1190 AND civicrm_participant_payment.participant_id {$componentClause} )
1193 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1194 $componentSelect = " civicrm_membership_payment.membership_id id";
1195 $additionalClause = "
1196 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1197 AND civicrm_membership_payment.membership_id {$componentClause} )
1200 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1201 $componentSelect = " civicrm_pledge_payment.id id";
1202 $additionalClause = "
1203 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1204 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1208 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1209 trxn_id, {$componentSelect}
1210 FROM civicrm_contribution
1211 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1212 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1213 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1214 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1215 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1216 AND option_group_contribution_status.id = contribution_status.option_group_id )
1220 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1222 while ($dao->fetch()) {
1223 $paymentDetails[$dao->id
] = array(
1224 'total_amount' => $dao->total_amount
,
1225 'contribution_status' => $dao->status
,
1226 'receive_date' => $dao->receive_date
,
1227 'pay_instru' => $dao->payment_instrument
,
1228 'trxn_id' => $dao->trxn_id
,
1232 return $paymentDetails;
1236 * Create address associated with contribution record.
1238 * @param array $params an associated array
1239 * @param int $billingLocationTypeID
1241 * @return address id
1244 static function createAddress(&$params, $billingLocationTypeID) {
1245 $billingFields = array(
1248 'state_province_id',
1253 //build address array
1254 $addressParams = array();
1255 $addressParams['location_type_id'] = $billingLocationTypeID;
1256 $addressParams['is_billing'] = 1;
1258 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1259 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1260 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1261 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1263 foreach ($billingFields as $value) {
1264 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1267 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1269 return $address->id
;
1273 * Delete billing address record related contribution
1275 * @param int $contributionId
1276 * @param int $contactId
1281 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1283 $contactJoin = NULL;
1285 if ($contributionId) {
1286 $clauses[] = "cc.id = {$contributionId}";
1290 $clauses[] = "cco.id = {$contactId}";
1291 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1294 if (empty($clauses)) {
1295 CRM_Core_Error
::fatal();
1298 $condition = implode(' OR ', $clauses);
1302 FROM civicrm_address ca
1303 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1307 $dao = CRM_Core_DAO
::executeQuery($query);
1309 while ($dao->fetch()) {
1310 $params = array('id' => $dao->id
);
1311 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1316 * This function check online pending contribution associated w/
1317 * Online Event Registration or Online Membership signup.
1319 * @param int $componentId participant/membership id.
1320 * @param string $componentName Event/Membership.
1322 * @return $contributionId pending contribution id.
1325 static function checkOnlinePendingContribution($componentId, $componentName) {
1326 $contributionId = NULL;
1327 if (!$componentId ||
1328 !in_array($componentName, array('Event', 'Membership'))
1330 return $contributionId;
1333 if ($componentName == 'Event') {
1334 $idName = 'participant_id';
1335 $componentTable = 'civicrm_participant';
1336 $paymentTable = 'civicrm_participant_payment';
1337 $source = ts('Online Event Registration');
1340 if ($componentName == 'Membership') {
1341 $idName = 'membership_id';
1342 $componentTable = 'civicrm_membership';
1343 $paymentTable = 'civicrm_membership_payment';
1344 $source = ts('Online Contribution');
1347 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1350 SELECT component.id as {$idName},
1351 componentPayment.contribution_id as contribution_id,
1352 contribution.source source,
1353 contribution.contribution_status_id as contribution_status_id,
1354 contribution.is_pay_later as is_pay_later
1355 FROM $componentTable component
1356 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1357 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1358 WHERE component.id = {$componentId}";
1360 $dao = CRM_Core_DAO
::executeQuery($query);
1362 while ($dao->fetch()) {
1363 if ($dao->contribution_id
&&
1364 $dao->is_pay_later
&&
1365 $dao->contribution_status_id
== $pendingStatusId &&
1366 strpos($dao->source
, $source) !== FALSE
1368 $contributionId = $dao->contribution_id
;
1373 return $contributionId;
1377 * This function update contribution as well as related objects.
1379 static function transitionComponents($params, $processContributionObject = FALSE) {
1380 // get minimum required values.
1381 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1382 $componentId = CRM_Utils_Array
::value('component_id', $params);
1383 $componentName = CRM_Utils_Array
::value('componentName', $params);
1384 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1385 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1387 // if we already processed contribution object pass previous status id.
1388 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1390 $updateResult = array();
1392 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1394 // we process only ( Completed, Cancelled, or Failed ) contributions.
1395 if (!$contributionId ||
1396 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1397 array_search('Cancelled', $contributionStatuses),
1398 array_search('Failed', $contributionStatuses),
1401 return $updateResult;
1404 if (!$componentName ||
!$componentId) {
1405 // get the related component details.
1406 $componentDetails = self
::getComponentDetails($contributionId);
1409 $componentDetails['contact_id'] = $contactId;
1410 $componentDetails['component'] = $componentName;
1412 if ($componentName == 'event') {
1413 $componentDetails['participant'] = $componentId;
1416 $componentDetails['membership'] = $componentId;
1420 if (!empty($componentDetails['contact_id'])) {
1421 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1427 // do check for required ids.
1428 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1429 return $updateResult;
1432 //now we are ready w/ required ids, start processing.
1434 $baseIPN = new CRM_Core_Payment_BaseIPN();
1436 $input = $ids = $objects = array();
1438 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1439 $ids['contribution'] = $contributionId;
1440 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1441 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1442 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1443 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1444 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1445 $ids['contributionRecur'] = NULL;
1446 $ids['contributionPage'] = NULL;
1448 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1449 CRM_Core_Error
::fatal();
1452 $memberships = &$objects['membership'];
1453 $participant = &$objects['participant'];
1454 $pledgePayment = &$objects['pledge_payment'];
1455 $contribution = &$objects['contribution'];
1457 if ($pledgePayment) {
1458 $pledgePaymentIDs = array();
1459 foreach ($pledgePayment as $key => $object) {
1460 $pledgePaymentIDs[] = $object->id
;
1462 $pledgeID = $pledgePayment[0]->pledge_id
;
1465 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1468 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1469 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1474 // we might want to process contribution object.
1475 $processContribution = FALSE;
1476 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1477 if (is_array($memberships)) {
1478 foreach ($memberships as $membership) {
1480 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1481 $membership->save();
1483 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1484 if ($processContributionObject) {
1485 $processContribution = TRUE;
1492 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1493 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1495 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1496 if ($processContributionObject) {
1497 $processContribution = TRUE;
1501 if ($pledgePayment) {
1502 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1504 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1505 if ($processContributionObject) {
1506 $processContribution = TRUE;
1510 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1511 if (is_array($memberships)) {
1512 foreach ($memberships as $membership) {
1514 $membership->status_id
= array_search('Expired', $membershipStatuses);
1515 $membership->save();
1517 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1518 if ($processContributionObject) {
1519 $processContribution = TRUE;
1525 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1526 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1528 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1529 if ($processContributionObject) {
1530 $processContribution = TRUE;
1534 if ($pledgePayment) {
1535 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1537 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1538 if ($processContributionObject) {
1539 $processContribution = TRUE;
1543 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1545 // only pending contribution related object processed.
1546 if ($previousContriStatusId &&
1547 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1549 // this is case when we already processed contribution object.
1550 return $updateResult;
1552 elseif (!$previousContriStatusId &&
1553 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1555 // this is case when we are going to process contribution object later.
1556 return $updateResult;
1559 if (is_array($memberships)) {
1560 foreach ($memberships as $membership) {
1565 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1566 $membership->membership_type_id
,
1567 $membership->is_test
, $membership->id
1570 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1571 // this picks up membership type changes during renewals
1573 SELECT membership_type_id
1574 FROM civicrm_membership_log
1575 WHERE membership_id=$membership->id
1578 $dao = new CRM_Core_DAO
;
1580 if ($dao->fetch()) {
1581 if (!empty($dao->membership_type_id
)) {
1582 $membership->membership_type_id
= $dao->membership_type_id
;
1583 $membership->save();
1586 // else fall back to using current membership type
1589 // Figure out number of terms
1591 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1592 foreach ($lineitems as $lineitem) {
1593 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1594 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1596 // in case membership_num_terms comes through as null or zero
1597 $numterms = $numterms >= 1 ?
$numterms : 1;
1602 if ($currentMembership) {
1603 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1604 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1605 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1608 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1611 //get the status for membership.
1612 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1614 $dates['join_date'],
1617 $membership->membership_type_id
,
1621 $formattedParams = array(
1622 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1623 array_search('Current', $membershipStatuses)
1625 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1626 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1627 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1630 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1632 $membership->copyValues($formattedParams);
1633 $membership->save();
1635 //updating the membership log
1636 $membershipLog = array();
1637 $membershipLog = $formattedParams;
1638 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1639 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1641 $membershipLog['start_date'] = $logStartDate;
1642 $membershipLog['membership_id'] = $membership->id
;
1643 $membershipLog['modified_id'] = $membership->contact_id
;
1644 $membershipLog['modified_date'] = date('Ymd');
1645 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1647 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1649 //update related Memberships.
1650 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1652 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1655 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1656 if ($processContributionObject) {
1657 $processContribution = TRUE;
1660 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1666 $updatedStatusId = array_search('Registered', $participantStatuses);
1667 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1669 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1670 if ($processContributionObject) {
1671 $processContribution = TRUE;
1675 if ($pledgePayment) {
1676 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1678 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1679 if ($processContributionObject) {
1680 $processContribution = TRUE;
1685 // process contribution object.
1686 if ($processContribution) {
1687 $contributionParams = array();
1689 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1690 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1691 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1693 foreach ($fields as $field) {
1694 if (empty($params[$field])) {
1697 $contributionParams[$field] = $params[$field];
1700 $ids = array('contribution' => $contributionId);
1701 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1704 return $updateResult;
1708 * This function returns all contribution related object ids.
1710 public static function getComponentDetails($contributionId) {
1711 $componentDetails = $pledgePayment = array();
1712 if (!$contributionId) {
1713 return $componentDetails;
1717 SELECT c.id as contribution_id,
1718 c.contact_id as contact_id,
1719 mp.membership_id as membership_id,
1720 m.membership_type_id as membership_type_id,
1721 pp.participant_id as participant_id,
1722 p.event_id as event_id,
1723 pgp.id as pledge_payment_id
1724 FROM civicrm_contribution c
1725 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1726 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1727 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1728 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1729 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1730 WHERE c.id = $contributionId";
1732 $dao = CRM_Core_DAO
::executeQuery($query);
1733 $componentDetails = array();
1735 while ($dao->fetch()) {
1736 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1737 $componentDetails['contact_id'] = $dao->contact_id
;
1738 if ($dao->event_id
) {
1739 $componentDetails['event'] = $dao->event_id
;
1741 if ($dao->participant_id
) {
1742 $componentDetails['participant'] = $dao->participant_id
;
1744 if ($dao->membership_id
) {
1745 if (!isset($componentDetails['membership'])) {
1746 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1748 $componentDetails['membership'][] = $dao->membership_id
;
1749 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1751 if ($dao->pledge_payment_id
) {
1752 $pledgePayment[] = $dao->pledge_payment_id
;
1756 if ($pledgePayment) {
1757 $componentDetails['pledge_payment'] = $pledgePayment;
1760 return $componentDetails;
1764 * @param int $contactId
1765 * @param bool $includeSoftCredit
1767 * @return null|string
1769 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1774 $contactContributionsSQL = "
1775 SELECT contribution.id AS id
1776 FROM civicrm_contribution contribution
1777 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1779 $contactSoftCreditContributionsSQL = "
1780 SELECT contribution.id
1781 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1782 ON ( contribution.id = softContribution.contribution_id )
1783 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1784 $query = "SELECT count( x.id ) count FROM ( ";
1785 $query .= $contactContributionsSQL;
1787 if ($includeSoftCredit) {
1788 $query .= " UNION ";
1789 $query .= $contactSoftCreditContributionsSQL;
1794 return CRM_Core_DAO
::singleValueQuery($query);
1798 * Get individual id for onbehalf contribution
1800 * @param int $contributionId contribution id
1801 * @param int $contributorId contributor id
1803 * @return array $ids containing organization id and individual id
1806 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1810 if (!$contributionId) {
1814 // fetch contributor id if null
1815 if (!$contributorId) {
1816 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1817 $contributionId, 'contact_id'
1821 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1822 $activityTypeId = array_search('Contribution', $activityTypeIds);
1824 if ($activityTypeId && $contributorId) {
1826 SELECT civicrm_activity_contact.contact_id
1827 FROM civicrm_activity_contact
1828 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1829 WHERE civicrm_activity.activity_type_id = %1
1830 AND civicrm_activity.source_record_id = %2
1831 AND civicrm_activity_contact.record_type_id = %3
1834 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1835 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1838 1 => array($activityTypeId, 'Integer'),
1839 2 => array($contributionId, 'Integer'),
1840 3 => array($sourceID, 'Integer'),
1843 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1845 // for on behalf contribution source is individual and contributor is organization
1846 if ($sourceContactId && $sourceContactId != $contributorId) {
1847 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1848 // get rel type id for employee of relation
1849 foreach ($relationshipTypeIds as $id => $typeVals) {
1850 if ($typeVals['name_a_b'] == 'Employee of') {
1851 $relationshipTypeId = $id;
1856 $rel = new CRM_Contact_DAO_Relationship();
1857 $rel->relationship_type_id
= $relationshipTypeId;
1858 $rel->contact_id_a
= $sourceContactId;
1859 $rel->contact_id_b
= $contributorId;
1860 if ($rel->find(TRUE)) {
1861 $ids['individual_id'] = $rel->contact_id_a
;
1862 $ids['organization_id'] = $rel->contact_id_b
;
1874 static function getContributionDates() {
1875 $config = CRM_Core_Config
::singleton();
1876 $currentMonth = date('m');
1877 $currentDay = date('d');
1878 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1879 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1880 (int ) $config->fiscalYearStart
['d'] > $currentDay
1883 $year = date('Y') - 1;
1888 $year = array('Y' => $year);
1889 $yearDate = $config->fiscalYearStart
;
1890 $yearDate = array_merge($year, $yearDate);
1891 $yearDate = CRM_Utils_Date
::format($yearDate);
1893 $monthDate = date('Ym') . '01';
1899 'yearDate' => $yearDate,
1900 'monthDate' => $monthDate,
1905 * Load objects relations to contribution object
1906 * Objects are stored in the $_relatedObjects property
1907 * In the first instance we are just moving functionality from BASEIpn -
1908 * see http://issues.civicrm.org/jira/browse/CRM-9996
1910 * @param array $input Input as delivered from Payment Processor
1911 * @param array $ids Ids as Loaded by Payment Processor
1912 * @param boolean $required Is Payment processor / contribution page required
1913 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1914 * Note that the unit test for the BaseIPN class tests this function
1919 * @param bool $required
1920 * @param bool $loadAll
1925 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1927 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1928 if(empty($ids['contact']) && isset($this->contact_id
)){
1929 $ids['contact'] = $this->contact_id
;
1932 if (empty($this->_component
)) {
1933 if (! empty($ids['event'])) {
1934 $this->_component
= 'event';
1937 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1940 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1941 $contributionType = new CRM_Financial_BAO_FinancialType();
1942 $contributionType->id
= $this->financial_type_id
;
1943 if (!$contributionType->find(TRUE)) {
1944 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1946 if (!empty($ids['contact'])) {
1947 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1948 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1949 $this->_relatedObjects
['contact']->find(TRUE);
1951 $this->_relatedObjects
['contributionType'] = $contributionType;
1953 if ($this->_component
== 'contribute') {
1954 // retrieve the other optional objects first so
1955 // stuff down the line can use this info and do things
1957 //in any case get the memberships associated with the contribution
1958 //because we now support multiple memberships w/ price set
1959 // see if there are any other memberships to be considered for same contribution.
1961 SELECT membership_id
1962 FROM civicrm_membership_payment
1963 WHERE contribution_id = %1 ";
1964 $params = array(1 => array($this->id
, 'Integer'));
1966 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1967 while ($dao->fetch()) {
1968 if ($dao->membership_id
) {
1969 if (!is_array($ids['membership'])) {
1970 $ids['membership'] = array();
1972 $ids['membership'][] = $dao->membership_id
;
1976 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1977 foreach ($ids['membership'] as $id) {
1979 $membership = new CRM_Member_BAO_Membership();
1980 $membership->id
= $id;
1981 if (!$membership->find(TRUE)) {
1982 throw new Exception("Could not find membership record: $id");
1984 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1985 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1986 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1987 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1988 $membership->free();
1993 if (!empty($ids['pledge_payment'])) {
1995 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1996 if (empty($paymentID)) {
1999 $payment = new CRM_Pledge_BAO_PledgePayment();
2000 $payment->id
= $paymentID;
2001 if (!$payment->find(TRUE)) {
2002 throw new Exception("Could not find pledge payment record: " . $paymentID);
2004 $this->_relatedObjects
['pledge_payment'][] = $payment;
2008 if (!empty($ids['contributionRecur'])) {
2009 $recur = new CRM_Contribute_BAO_ContributionRecur();
2010 $recur->id
= $ids['contributionRecur'];
2011 if (!$recur->find(TRUE)) {
2012 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2014 $this->_relatedObjects
['contributionRecur'] = &$recur;
2015 //get payment processor id from recur object.
2016 $paymentProcessorID = $recur->payment_processor_id
;
2018 //for normal contribution get the payment processor id.
2019 if (!$paymentProcessorID) {
2020 if ($this->contribution_page_id
) {
2021 // get the payment processor id from contribution page
2022 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2023 $this->contribution_page_id
,
2027 //fail to load payment processor id.
2028 elseif (empty($ids['pledge_payment'])) {
2029 $loadObjectSuccess = TRUE;
2031 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2033 return $loadObjectSuccess;
2038 // we are in event mode
2039 // make sure event exists and is valid
2040 $event = new CRM_Event_BAO_Event();
2041 $event->id
= $ids['event'];
2042 if ($ids['event'] &&
2045 throw new Exception("Could not find event: " . $ids['event']);
2048 $this->_relatedObjects
['event'] = &$event;
2050 $participant = new CRM_Event_BAO_Participant();
2051 $participant->id
= $ids['participant'];
2052 if ($ids['participant'] &&
2053 !$participant->find(TRUE)
2055 throw new Exception("Could not find participant: " . $ids['participant']);
2057 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2059 $this->_relatedObjects
['participant'] = &$participant;
2061 if (!$paymentProcessorID) {
2062 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2066 if ($paymentProcessorID) {
2067 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2068 $this->is_test ?
'test' : 'live'
2070 $ids['paymentProcessor'] = $paymentProcessorID;
2071 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2073 elseif ($required) {
2074 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2081 * Create array of message information - ie. return html version, txt version, to field
2083 * @param array $input incoming information
2084 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2085 * just check presence of recur object but maintaining legacy approach
2087 * @param array $ids IDs of related objects
2088 * @param array $values any values that may have already been compiled by calling process
2089 * This is augmented by values 'gathered' by gatherMessageValues
2090 * @param bool $returnMessageText distinguishes between whether to send message or return
2091 * message text. We are working towards this function ALWAYS returning message text & calling
2092 * function doing emails / pdfs with it
2093 * @return array $messageArray - messages
2099 * @param bool $recur
2100 * @param bool $returnMessageText
2104 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2105 if (empty($this->_relatedObjects
)) {
2106 $this->loadRelatedObjects($input, $ids);
2108 if (empty($this->_component
)) {
2109 $this->_component
= CRM_Utils_Array
::value('component', $input);
2112 //not really sure what params might be passed in but lets merge em into values
2113 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2114 $template = CRM_Core_Smarty
::singleton();
2115 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2116 //what does recur 'mean here - to do with payment processor return functionality but
2117 // what is the importance
2118 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2119 $paymentObject = &CRM_Core_Payment
::singleton(
2120 $this->is_test ?
'test' : 'live',
2121 $this->_relatedObjects
['paymentProcessor']
2124 $entityID = $entity = NULL;
2125 if (isset($ids['contribution'])) {
2126 $entity = 'contribution';
2127 $entityID = $ids['contribution'];
2129 if (!empty($ids['membership'])) {
2130 //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
2131 // 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
2132 // line having loaded an array
2133 $ids['membership'] = (array) $ids['membership'];
2134 $entity = 'membership';
2135 $entityID = $ids['membership'][0];
2138 $url = $paymentObject->subscriptionURL($entityID, $entity);
2139 $template->assign('cancelSubscriptionUrl', $url);
2141 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2142 $template->assign('updateSubscriptionBillingUrl', $url);
2144 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2145 $template->assign('updateSubscriptionUrl', $url);
2147 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2148 //direct mode showing billing block, so use directIPN for temporary
2149 $template->assign('contributeMode', 'directIPN');
2152 // todo remove strtolower - check consistency
2153 if (strtolower($this->_component
) == 'event') {
2154 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2155 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2159 $values['contribution_id'] = $this->id
;
2160 if (!empty($ids['related_contact'])) {
2161 $values['related_contact'] = $ids['related_contact'];
2162 if (isset($ids['onbehalf_dupe_alert'])) {
2163 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2165 $entityBlock = array(
2166 'contact_id' => $ids['contact'],
2167 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2168 'Home', 'id', 'name'
2171 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2172 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2175 if ($this->is_test
) {
2178 if (!empty($this->_relatedObjects
['membership'])) {
2179 foreach ($this->_relatedObjects
['membership'] as $membership) {
2180 if ($membership->id
) {
2181 $values['isMembership'] = TRUE;
2183 // need to set the membership values here
2184 $template->assign('membership_assign', 1);
2185 $template->assign('membership_name',
2186 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2188 $template->assign('mem_start_date', $membership->start_date
);
2189 $template->assign('mem_join_date', $membership->join_date
);
2190 $template->assign('mem_end_date', $membership->end_date
);
2191 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2192 $template->assign('mem_status', $membership_status);
2193 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2194 $template->assign('is_pay_later', 1);
2197 // if separate payment there are two contributions recorded and the
2198 // admin will need to send a receipt for each of them separately.
2199 // we dont link the two in the db (but can potentially infer it if needed)
2200 $template->assign('is_separate_payment', 0);
2202 if ($recur && $paymentObject) {
2203 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2204 $template->assign('cancelSubscriptionUrl', $url);
2205 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2206 $template->assign('updateSubscriptionBillingUrl', $url);
2207 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2208 $template->assign('updateSubscriptionUrl', $url);
2211 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2214 // otherwise if its about sending emails, continue sending without return, as we
2215 // don't want to exit the loop.
2220 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2226 * Gather values for contribution mail - this function has been created
2227 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2228 * Values related to the contribution in question are gathered
2230 * @param array $input input into function (probably from payment processor)
2231 * @param array $ids the set of ids related to the inpurt
2233 * @return array $values
2235 * NB don't add direct calls to the function as we intend to change the signature
2244 function _gatherMessageValues($input, &$values, $ids = array()) {
2245 // set display address of contributor
2246 if ($this->address_id
) {
2247 $addressParams = array('id' => $this->address_id
);
2248 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2249 $addressDetails = array_values($addressDetails);
2250 $values['address'] = $addressDetails[0]['display'];
2252 if ($this->_component
== 'contribute') {
2253 if (isset($this->contribution_page_id
)) {
2254 CRM_Contribute_BAO_ContributionPage
::setValues(
2255 $this->contribution_page_id
,
2258 if ($this->contribution_page_id
) {
2259 // CRM-8254 - override default currency if applicable
2260 $config = CRM_Core_Config
::singleton();
2261 $config->defaultCurrency
= CRM_Utils_Array
::value(
2264 $config->defaultCurrency
2268 // no contribution page -probably back office
2270 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2271 $values['is_email_receipt'] = 1;
2272 $values['title'] = 'Contribution';
2274 // set lineItem for contribution
2276 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2277 if (!empty($lineItem)) {
2278 $itemId = key($lineItem);
2279 foreach ($lineItem as &$eachItem) {
2280 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2281 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2282 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2283 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2286 $values['lineItem'][0] = $lineItem;
2287 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2291 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2295 // if this is onbehalf of contribution then set related contact
2296 if (!empty($relatedContact['individual_id'])) {
2297 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2302 $eventParams = array(
2303 'id' => $this->_relatedObjects
['event']->id
,
2305 $values['event'] = array();
2307 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2309 //get location details
2310 $locationParams = array(
2311 'entity_id' => $this->_relatedObjects
['event']->id
,
2312 'entity_table' => 'civicrm_event',
2314 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2316 $ufJoinParams = array(
2317 'entity_table' => 'civicrm_event',
2318 'entity_id' => $ids['event'],
2319 'module' => 'CiviEvent',
2322 list($custom_pre_id,
2324 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2326 $values['custom_pre_id'] = $custom_pre_id;
2327 $values['custom_post_id'] = $custom_post_ids;
2329 // set lineItem for event contribution
2331 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2332 if (!empty($participantIds)) {
2333 foreach ($participantIds as $pIDs) {
2334 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2335 if (!CRM_Utils_System
::isNull($lineItem)) {
2336 $values['lineItem'][] = $lineItem;
2347 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2348 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2349 * Note we send directly from this function in some cases because it is only partly refactored
2350 * Don't call this function directly as the signature will change
2354 * @param $template CRM_Core_SMARTY
2355 * @param bool $recur
2356 * @param bool $returnMessageText
2360 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2361 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2362 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2363 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2364 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2365 $template->assign('useForMember', true);
2367 //assign honor information to receipt message
2368 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2370 if (isset($softRecord['soft_credit'])) {
2371 //if id of contribution page is present
2372 if (!empty($values['id'])) {
2373 $values['honor'] = array(
2374 'honor_profile_values' => array(),
2375 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2376 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2378 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2380 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2381 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2384 //offline contribution
2385 $softCreditTypes = $softCredits = array();
2386 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2387 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2388 $softCredits[$key] = array(
2389 'Name' => $softCredit['contact_name'],
2390 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2393 $template->assign('softCreditTypes', $softCreditTypes);
2394 $template->assign('softCredits', $softCredits);
2398 $dao = new CRM_Contribute_DAO_ContributionProduct();
2399 $dao->contribution_id
= $this->id
;
2400 if ($dao->find(TRUE)) {
2401 $premiumId = $dao->product_id
;
2402 $template->assign('option', $dao->product_option
);
2404 $productDAO = new CRM_Contribute_DAO_Product();
2405 $productDAO->id
= $premiumId;
2406 $productDAO->find(TRUE);
2407 $template->assign('selectPremium', TRUE);
2408 $template->assign('product_name', $productDAO->name
);
2409 $template->assign('price', $productDAO->price
);
2410 $template->assign('sku', $productDAO->sku
);
2412 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2413 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2414 if(empty($amount) && isset($this->total_amount
)){
2415 $amount = $this->total_amount
;
2417 $template->assign('amount', $amount);
2418 // add the new contribution values
2419 if (strtolower($this->_component
) == 'contribute') {
2421 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2422 $softDAO->contribution_id
= $this->id
;
2423 if ($softDAO->find(TRUE)) {
2424 $template->assign('pcpBlock', TRUE);
2425 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2426 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2427 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2429 //assign the pcp page title for email subject
2430 $pcpDAO = new CRM_PCP_DAO_PCP();
2431 $pcpDAO->id
= $softDAO->pcp_id
;
2432 if ($pcpDAO->find(TRUE)) {
2433 $template->assign('title', $pcpDAO->title
);
2438 if ($this->financial_type_id
) {
2439 $values['financial_type_id'] = $this->financial_type_id
;
2443 $template->assign('trxn_id', $this->trxn_id
);
2444 $template->assign('receive_date',
2445 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2447 $template->assign('contributeMode', 'notify');
2448 $template->assign('action', $this->is_test ?
1024 : 1);
2449 $template->assign('receipt_text',
2450 CRM_Utils_Array
::value('receipt_text',
2454 $template->assign('is_monetary', 1);
2455 $template->assign('is_recur', (bool) $recur);
2456 $template->assign('currency', $this->currency
);
2457 $template->assign('address', CRM_Utils_Address
::format($input));
2458 if ($this->_component
== 'event') {
2459 $template->assign('title', $values['event']['title']);
2460 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2461 $viewRoles = array();
2462 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2463 $viewRoles[] = $participantRoles[$v];
2465 $values['event']['participant_role'] = implode(', ', $viewRoles);
2466 $template->assign('event', $values['event']);
2467 $template->assign('location', $values['location']);
2468 $template->assign('customPre', $values['custom_pre_id']);
2469 $template->assign('customPost', $values['custom_post_id']);
2472 if ($this->_relatedObjects
['participant']->is_test
) {
2476 $values['params'] = array();
2477 //to get email of primary participant.
2478 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2479 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2480 //build an array of cId/pId of participants
2481 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2482 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2483 //send receipt to additional participant if exists
2484 if (count($additionalIDs)) {
2485 $template->assign('isPrimary', 0);
2486 $template->assign('customProfile', NULL);
2487 //set additionalParticipant true
2488 $values['params']['additionalParticipant'] = TRUE;
2489 foreach ($additionalIDs as $pId => $cId) {
2491 //to change the status pending to completed
2492 $additional = new CRM_Event_DAO_Participant();
2493 $additional->id
= $pId;
2494 $additional->contact_id
= $cId;
2495 $additional->find(TRUE);
2496 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2497 $additional->status_id
= 1;
2498 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2499 //if additional participant dont have email
2501 if (!$additionalParticipantInfo) {
2502 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2504 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2505 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2506 $additional->save();
2507 $additional->free();
2508 $template->assign('amount', $amount);
2509 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2513 //build an array of custom profile and assigning it to template
2514 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2516 if (count($customProfile)) {
2517 $template->assign('customProfile', $customProfile);
2520 // for primary contact
2521 $values['params']['additionalParticipant'] = FALSE;
2522 $template->assign('isPrimary', 1);
2523 $template->assign('amount', $primaryAmount);
2524 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2525 if ($this->payment_instrument_id
) {
2526 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2527 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2529 // carry paylater, since we did not created billing,
2530 // so need to pull email from primary location, CRM-4395
2531 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2537 * Check whether payment processor supports
2538 * cancellation of contribution subscription
2540 * @param int $contributionId contribution id
2542 * @param bool $isNotCancelled
2548 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2549 $cacheKeyString = "$contributionId";
2550 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2552 static $supportsCancel = array();
2554 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2555 $supportsCancel[$cacheKeyString] = FALSE;
2556 $isCancelled = FALSE;
2558 if ($isNotCancelled) {
2559 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2562 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2563 if (!empty($paymentObject)) {
2564 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2567 return $supportsCancel[$cacheKeyString];
2571 * Check whether subscription is already cancelled
2573 * @param int $contributionId contribution id
2575 * @return string $status contribution status
2579 static function isSubscriptionCancelled($contributionId) {
2581 SELECT cr.contribution_status_id
2582 FROM civicrm_contribution_recur cr
2583 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2584 WHERE con.id = %1 LIMIT 1";
2585 $params = array(1 => array($contributionId, 'Integer'));
2586 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2587 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2588 if ($status == 'Cancelled') {
2595 * Create all financial accounts entry
2597 * @param array $params contribution object, line item array and params for trxn
2600 * @param array $financialTrxnValues
2602 * @return null|object
2606 static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2607 $skipRecords = $update = $return = $isRelatedId = FALSE;
2609 $additionalParticipantId = array();
2610 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2612 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2613 $entityId = $params['participant_id'];
2614 $entityTable = 'civicrm_participant';
2615 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2617 elseif (!empty($params['membership_id'])) {
2618 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2619 // are created off one contribution should be handled elsewhere
2620 $entityId = $params['membership_id'];
2621 $entityTable = 'civicrm_membership';
2624 $entityId = $params['contribution']->id
;
2625 $entityTable = 'civicrm_contribution';
2628 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2629 $isRelatedId = TRUE;
2632 $entityID[] = $entityId;
2633 if (!empty($additionalParticipantId)) {
2634 $entityID +
= $additionalParticipantId;
2636 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2637 if (empty($params['prevContribution'])) {
2644 $statusId = $params['contribution']->contribution_status_id
;
2645 // CRM-13964 partial payment
2646 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2647 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2648 $partialAmtPay = $params['partial_amount_pay'];
2649 $partialAmtTotal = $params['partial_payment_total'];
2651 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2652 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2653 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2654 $params['total_amount'] = $partialAmtPay;
2656 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2657 if (empty($balanceTrxnInfo['trxn_id'])) {
2658 // create new balance transaction record
2659 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2660 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2662 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2663 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2664 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2665 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2666 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2667 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2668 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2669 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2670 $balanceTrxnParams['status_id'] = $statusId;
2671 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2672 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2673 if (!empty($params['payment_processor'])) {
2674 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2676 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2680 // build line item array if its not set in $params
2681 if (empty($params['line_item']) ||
$additionalParticipantId) {
2682 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2685 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2686 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2687 $skipRecords = TRUE;
2688 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2689 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2690 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2691 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2693 elseif (!empty($params['payment_processor'])) {
2694 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2696 elseif (!empty($params['payment_instrument_id'])) {
2697 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2700 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2701 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2702 $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);
2705 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2706 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2707 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2710 //build financial transaction params
2711 $trxnParams = array(
2712 'contribution_id' => $params['contribution']->id
,
2713 'to_financial_account_id' => $params['to_financial_account_id'],
2714 'trxn_date' => date('YmdHis'),
2715 'total_amount' => $totalAmount,
2716 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2717 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2718 'currency' => $params['contribution']->currency
,
2719 'trxn_id' => $params['contribution']->trxn_id
,
2720 'status_id' => $statusId,
2721 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2722 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2725 if (!empty($params['payment_processor'])) {
2726 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2729 if (isset($fromFinancialAccountId)) {
2730 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2733 // consider external values passed for recording transaction entry
2734 if (!empty($financialTrxnValues)) {
2735 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2738 $params['trxnParams'] = $trxnParams;
2740 if (!empty($params['prevContribution'])) {
2741 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2742 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2743 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2744 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2745 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2748 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2749 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2750 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))) {
2751 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2752 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2755 //if financial type is changed
2756 if (!empty($params['financial_type_id']) &&
2757 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2758 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2759 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2760 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2761 if ($oldFinancialAccount != $newFinancialAccount) {
2762 $params['total_amount'] = 0;
2763 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2764 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2765 $params['prevContribution']->financial_type_id
, $relationTypeId);
2768 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2769 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2770 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2773 self
::updateFinancialAccounts($params, 'changeFinancialType');
2774 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2775 $params['financial_account_id'] = $newFinancialAccount;
2776 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2777 self
::updateFinancialAccounts($params);
2778 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2782 //Update contribution status
2783 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2784 if (!empty($params['contribution_status_id']) &&
2785 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2786 //Update Financial Records
2787 self
::updateFinancialAccounts($params, 'changedStatus');
2790 // change Payment Instrument for a Completed contribution
2791 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2792 // instrument is null and now new payment instrument is added along with the payment
2793 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2794 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2795 if (array_key_exists('payment_instrument_id', $params)) {
2796 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2797 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2798 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2799 //check if status is changed from Pending to Completed
2800 // do not update payment instrument changes for Pending to Completed
2801 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2802 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2803 // for all other statuses create new financial records
2804 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2805 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2806 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2809 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2810 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2811 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2812 // for any other payment instrument changes create new financial records
2813 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2814 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2815 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2817 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2818 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2819 // another special case when check number is changed, create new financial records
2820 // create financial trxn with negative amount
2821 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2822 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2823 // create financial trxn with positive amount
2824 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2825 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2826 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2830 //if Change contribution amount
2831 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2832 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2833 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2834 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2835 if (isset($totalAmount) &&
2836 $totalAmount != $params['prevContribution']->total_amount
) {
2837 //Update Financial Records
2838 $params['trxnParams']['from_financial_account_id'] = NULL;
2839 self
::updateFinancialAccounts($params, 'changedAmount');
2844 // records finanical trxn and entity financial trxn
2845 // also make it available as return value
2846 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2847 $params['entity_id'] = $financialTxn->id
;
2850 // record line items and finacial items
2851 if (empty($params['skipLineItem'])) {
2852 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2855 // create batch entry if batch_id is passed
2856 if (!empty($params['batch_id'])) {
2857 $entityParams = array(
2858 'batch_id' => $params['batch_id'],
2859 'entity_table' => 'civicrm_financial_trxn',
2860 'entity_id' => $financialTxn->id
,
2862 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2865 // when a fee is charged
2866 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2867 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2870 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2871 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2872 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2873 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2874 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2876 unset($params['line_item']);
2882 * Update all financial accounts entry
2884 * @param array $params contribution object, line item array and params for trxn
2886 * @param string $context update scenarios
2888 * @param null $skipTrxn
2893 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2894 $itemAmount = $trxnID = NULL;
2895 //get all the statuses
2896 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2897 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2898 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2899 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2900 && $context == 'changePaymentInstrument') {
2903 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2904 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2906 if ($context == 'changedStatus') {
2907 //get all the statuses
2908 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2910 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2911 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2912 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2913 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2915 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2916 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2917 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2918 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2919 $params['trxnParams']['to_financial_account_id'] = NULL;
2920 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2922 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2923 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2924 $financialTypeID, $relationTypeId);
2926 $itemAmount = $params['trxnParams']['total_amount'];
2928 elseif ($context == 'changePaymentInstrument') {
2929 if ($params['trxnParams']['total_amount'] < 0) {
2930 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2931 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2932 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2933 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2937 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2938 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2941 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2942 $params['entity_id'] = $trxn->id
;
2944 if ($context == 'changedStatus') {
2945 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2946 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2947 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2948 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2949 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2951 $entityParams = array(
2952 'entity_table' => 'civicrm_financial_item',
2953 'financial_trxn_id' => $trxn->id
,
2955 if (empty($params['line_item'])) {
2957 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
2958 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
2959 // & this can be removed
2962 foreach ($params['line_item'] as $fieldId => $fields) {
2963 foreach ($fields as $fieldValueId => $fieldValues) {
2965 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2966 2 => array($fieldValues['id'], 'Integer'),
2968 CRM_Core_DAO
::executeQuery($query, $fparams);
2970 1 => array($fieldValues['id'], 'Integer'),
2972 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2973 while ($financialItem->fetch()) {
2974 $entityParams['entity_id'] = $financialItem->id
;
2975 $entityParams['amount'] = $financialItem->amount
;
2976 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2983 if ($context != 'changePaymentInstrument') {
2984 $itemParams['entity_table'] = 'civicrm_line_item';
2985 $trxnIds['id'] = $params['entity_id'];
2986 foreach ($params['line_item'] as $fieldId => $fields) {
2987 foreach ($fields as $fieldValueId => $fieldValues) {
2988 $prevParams['entity_id'] = $fieldValues['id'];
2989 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2991 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2992 if ($params['contribution']->receive_date
) {
2993 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2996 $financialAccount = $prevfinancialItem->financial_account_id
;
2997 if (!empty($params['financial_account_id'])) {
2998 $financialAccount = $params['financial_account_id'];
3001 $currency = $params['prevContribution']->currency
;
3002 if ($params['contribution']->currency
) {
3003 $currency = $params['contribution']->currency
;
3006 if (!empty($params['is_quick_config'])) {
3007 $amount = $itemAmount;
3009 $amount = $params['total_amount'];
3013 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3014 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)) {
3017 $amount = $diff * $fieldValues['line_total'];
3020 $itemParams = array(
3021 'transaction_date' => $receiveDate,
3022 'contact_id' => $params['prevContribution']->contact_id
,
3023 'currency' => $currency,
3024 'amount' => $amount,
3025 'description' => $prevfinancialItem->description
,
3026 'status_id' => $prevfinancialItem->status_id
,
3027 'financial_account_id' => $financialAccount,
3028 'entity_table' => 'civicrm_line_item',
3029 'entity_id' => $fieldValues['id']
3031 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3033 if ($fieldValues['tax_amount']) {
3034 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3035 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3036 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3037 $itemParams['description'] = $taxTerm;
3038 if ($fieldValues['financial_type_id']) {
3039 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3041 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3049 * Check status validation on update of a contribution
3051 * @param array $values previous form values before submit
3053 * @param array $fields the input form values
3055 * @param array $errors list of errors
3061 static function checkStatusValidation($values, &$fields, &$errors) {
3062 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3063 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3064 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3068 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3069 $checkStatus = array(
3070 'Cancelled' => array('Completed', 'Refunded'),
3071 'Completed' => array('Cancelled', 'Refunded'),
3072 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3073 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3074 'Refunded' => array('Cancelled', 'Completed')
3077 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3078 $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']]));
3083 * Delete contribution of contact
3087 * @param integer $contactId contact id
3092 static function deleteContactContribution($contactId) {
3093 $contribution = new CRM_Contribute_DAO_Contribution();
3094 $contribution->contact_id
= $contactId;
3095 $contribution->find();
3096 while ($contribution->fetch()) {
3097 self
::deleteContribution($contribution->id
);
3102 * Get options for a given contribution field.
3103 * @see CRM_Core_DAO::buildOptions
3105 * @param String $fieldName
3106 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3107 * @param Array $props : whatever is known about this dao object
3109 * @return Array|bool
3111 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3112 $className = __CLASS__
;
3114 switch ($fieldName) {
3115 // This field is not part of this object but the api supports it
3116 case 'payment_processor':
3117 $className = 'CRM_Contribute_BAO_ContributionPage';
3118 // Filter results by contribution page
3119 if (!empty($props['contribution_page_id'])) {
3120 $page = civicrm_api('contribution_page', 'getsingle', array(
3122 'id' => ($props['contribution_page_id'])
3124 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3125 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3128 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3129 case 'honor_type_id':
3130 $className = 'CRM_Contribute_BAO_ContributionSoft';
3131 $fieldName = 'soft_credit_type_id';
3132 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3135 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3139 * Validate financial type
3143 * @param integer $financialTypeId Financial Type id
3145 * @param string $relationName
3147 * @return array|bool
3151 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3152 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3153 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3155 if (!$financialAccount) {
3156 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3163 * Function to record additional payment for partial and refund contributions
3165 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3166 * @param array $trxnData : to take user provided input of transaction details.
3167 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3170 * @param int $contributionId
3172 * @param string $paymentType
3173 * @param int $participantId
3175 * @return null|object
3177 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3178 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3179 $getInfoOf['id'] = $contributionId;
3180 $defaults = array();
3181 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3183 if ($paymentType == 'owed') {
3184 // build params for recording financial trxn entry
3185 $params['contribution'] = $contributionDAO;
3186 $params = array_merge($defaults, $params);
3187 $params['skipLineItem'] = TRUE;
3188 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3189 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3190 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3193 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3194 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3195 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3197 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3198 if (!empty($trxnId)) {
3199 $trxnId = $trxnId['trxn_id'];
3201 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3202 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3205 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3206 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3207 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3211 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3212 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3213 FROM civicrm_financial_trxn ft
3214 LEFT JOIN civicrm_entity_financial_trxn eft
3215 ON (ft.id = eft.financial_trxn_id)
3216 WHERE eft.entity_table = 'civicrm_contribution'
3217 AND eft.entity_id = {$contributionId}
3218 AND ft.to_financial_account_id != {$toFinancialAccount}
3219 AND ft.status_id = {$statusId}
3221 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3224 if ($contributionDAO->total_amount
== $sumOfPayments) {
3225 // update contribution status and
3226 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3227 $contributionDAO->contribution_status_id
= $statusId;
3228 $contributionDAO->cancel_date
= 'null';
3229 $contributionDAO->cancel_reason
= NULL;
3230 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3231 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3232 $contributionDAO->save();
3234 //Change status of financial record too
3235 $financialTrxn->status_id
= $statusId;
3236 $financialTrxn->save();
3238 // note : not using the self::add method,
3239 // the reason because it performs 'status change' related code execution for financial records
3240 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3241 // are coded below i.e. just updating financial_item status to 'Paid'
3243 if ($participantId) {
3244 // update participant status
3245 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3246 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3247 foreach ($ids as $val) {
3248 $participantUpdate['id'] = $val;
3249 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3250 CRM_Event_BAO_Participant
::add($participantUpdate);
3254 // update financial item statuses
3255 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3256 $paidStatus = array_search('Paid', $financialItemStatus);
3258 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3259 $sqlFinancialItemUpdate = "
3260 UPDATE civicrm_financial_item fi
3261 LEFT JOIN civicrm_entity_financial_trxn eft
3262 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3263 SET status_id = {$paidStatus}
3264 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3266 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3269 elseif ($paymentType == 'refund') {
3270 // build params for recording financial trxn entry
3271 $params['contribution'] = $contributionDAO;
3272 $params = array_merge($defaults, $params);
3273 $params['skipLineItem'] = TRUE;
3274 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3275 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3277 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3278 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3279 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3281 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3283 // note : not using the self::add method,
3284 // the reason because it performs 'status change' related code execution for financial records
3285 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3286 // are coded below i.e. just updating financial_item status to 'Paid'
3287 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3289 // add financial item entry
3290 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3291 $getLine['entity_id'] = $contributionDAO->id
;
3292 $getLine['entity_table'] = 'civicrm_contribution';
3293 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3294 if (!empty($lineItemId->id
)) {
3295 $addFinancialEntry = array(
3296 'transaction_date' => $financialTrxn->trxn_date
,
3297 'contact_id' => $contributionDAO->contact_id
,
3298 'amount' => $financialTrxn->total_amount
,
3299 'status_id' => array_search('Paid', $financialItemStatus),
3300 'entity_id' => $lineItemId->id
,
3301 'entity_table' => 'civicrm_line_item'
3303 $trxnIds['id'] = $financialTrxn->id
;
3304 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3306 if ($participantId) {
3307 // update participant status
3308 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3309 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3310 foreach ($ids as $val) {
3311 $participantUpdate['id'] = $val;
3312 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3313 CRM_Event_BAO_Participant
::add($participantUpdate);
3318 // activity creation
3319 if (!empty($financialTrxn)) {
3320 if ($participantId) {
3321 $inputParams['id'] = $participantId;
3324 $component = 'event';
3325 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3326 $entityObj = $entityObj[$participantId];
3328 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3330 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3332 return $financialTrxn;
3338 * @param $activityType
3340 * @param int $contributionId
3342 * @throws CRM_Core_Exception
3344 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3345 if ($component == 'event') {
3346 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3347 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3348 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3349 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3350 $targetCid = $entityObj->contact_id
;
3351 // source record id would be the contribution id
3352 $srcRecId = $contributionId;
3356 $activityParams = array(
3357 'source_contact_id' => $targetCid,
3358 'source_record_id' => $srcRecId,
3359 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3363 'subject' => $subject,
3364 'activity_date_time' => $date,
3365 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3369 'skipRecentView' => TRUE,
3372 // create activity with target contacts
3373 $session = CRM_Core_Session
::singleton();
3374 $id = $session->get('userID');
3376 $activityParams['source_contact_id'] = $id;
3377 $activityParams['target_contact_id'][] = $targetCid;
3379 CRM_Activity_BAO_Activity
::create($activityParams);
3383 * Get list of payments displayed by Contribute_Page_PaymentInfo
3387 * @param bool $getTrxnInfo
3388 * @param bool $usingLineTotal
3392 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3393 if ($component == 'event') {
3394 $entity = 'participant';
3395 $entityTable = 'civicrm_participant';
3396 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3398 if (!$contributionId) {
3399 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3400 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3401 $id = $primaryParticipantId;
3403 if (!$contributionId) {
3408 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3409 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3415 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3416 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3419 if (empty($total) ||
$usingLineTotal) {
3420 // for additional participants
3421 if ($entityTable == 'civicrm_participant') {
3422 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3424 foreach ($ids as $val) {
3425 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3429 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3433 $baseTrxnId = $total['trxn_id'];
3434 $total = $total['total_amount'];
3437 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3438 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3440 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3441 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3442 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3444 if ($paymentBalance == 0 && $contributionIsPayLater) {
3445 $paymentBalance = $total;
3448 $info['total'] = $total;
3449 $info['paid'] = $total - $paymentBalance;
3450 $info['balance'] = $paymentBalance;
3452 $info['component'] = $component;
3453 $info['payLater'] = $contributionIsPayLater;
3455 if ($getTrxnInfo && $baseTrxnId) {
3456 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3458 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3459 FROM civicrm_contribution con
3460 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3461 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3462 WHERE con.id = {$contributionId}
3465 // conditioned WHERE clause
3467 // if balance trxn exists don't include details of it in transaction info
3468 $sql .= " AND ft.id != {$baseTrxnId} ";
3470 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3472 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3473 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3474 while($resultDAO->fetch()) {
3475 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3476 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3478 'total_amount' => $resultDAO->total_amount
,
3479 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3480 'payment_instrument' => $paidByLabel,
3481 'receive_date' => $resultDAO->trxn_date
,
3482 'trxn_id' => $resultDAO->trxn_id
,
3483 'status' => $statuses[$resultDAO->status_id
],
3485 if ($paidByName == 'Check') {
3486 $val['check_number'] = $resultDAO->check_number
;
3490 $info['transaction'] = $rows;
3496 * Get financial account id has 'Sales Tax Account is'
3497 * account relationship with financial type
3499 * @param int $financialTypeId
3501 * @return FinancialAccountId
3503 static function getFinancialAccountId($financialTypeId) {
3504 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3505 $searchParams = array(
3506 'entity_table' => 'civicrm_financial_type',
3507 'entity_id' => $financialTypeId,
3508 'account_relationship' => $accountRel,
3511 CRM_Financial_BAO_FinancialTypeAccount
::retrieve( $searchParams, $result );
3513 return CRM_Utils_Array
::value( 'financial_account_id', $result );
3516 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3517 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3519 // Update contribution
3520 if (!empty($params['id'])) {
3521 $id = $params['id'];
3522 $values = $ids = array();
3523 $contrbutionParams = array('id' => $id);
3524 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3526 // To assign pervious finantial type on update of contribution
3527 if (!isset($params['financial_type_id'])) {
3528 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3530 else if (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3531 // Assisn tax Amount on update of contrbution
3532 if (!empty($prevContributionValue->tax_amount
)) {
3533 $params['tax_amount'] = 'null';
3534 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3535 foreach ($params['line_item'] as $setID => $priceField) {
3536 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3537 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3544 // New Contrbution and update of contribution with tax rate financial type
3545 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3546 empty($params['skipLineItem']) && !$isLineItem)
3548 $taxRateParams = $taxRates[$params['financial_type_id']];
3549 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3550 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3552 // Get Line Item on update of contribution
3553 if (isset($params['id'])) {
3554 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3557 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3559 foreach ($params['line_item'] as $setID => $priceField) {
3560 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3561 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3564 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3566 else if (isset($params['api.line_item.create'])) {
3567 // Update total amount of contribution using lineItem
3568 $taxAmountArray = array();
3569 foreach ($params['api.line_item.create'] as $key => $value) {
3570 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3571 $taxRate = $taxRates[$value['financial_type_id']];
3572 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3573 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3576 $params['tax_amount'] = array_sum($taxAmountArray);
3577 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3580 // update line item of contrbution
3581 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3582 $taxRate = $taxRates[$params['financial_type_id']];
3583 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3584 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);