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 object 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));
106 $duplicates = array();
107 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
108 $error = CRM_Core_Error
::singleton();
109 $d = implode(', ', $duplicates);
110 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
113 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
118 // first clean up all the money fields
119 $moneyFields = array(
123 'non_deductible_amount',
126 //if priceset is used, no need to cleanup money
127 if (!empty($params['skipCleanMoney'])) {
128 unset($moneyFields[0]);
131 foreach ($moneyFields as $field) {
132 if (isset($params[$field])) {
133 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
137 // CRM-13420, set payment instrument to default if payment_instrument_id is empty
138 if (!$contributionID && empty($params['payment_instrument_id'])) {
139 $params['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument',
140 FALSE, FALSE, FALSE, 'AND is_default = 1'));
143 if (!empty($params['payment_instrument_id'])) {
144 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
145 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
146 $params['check_number'] = 'null';
150 // contribution status is missing, choose Completed as default status
151 // do this for create mode only
152 if (!$contributionID && empty($params['contribution_status_id'])) {
153 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
155 $setPrevContribution = TRUE;
156 // CRM-13964 partial payment
157 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
158 $partialAmtTotal = $params['partial_payment_total'];
159 $partialAmtPay = $params['partial_amount_pay'];
160 $params['total_amount'] = $partialAmtTotal;
161 if ($partialAmtPay < $partialAmtTotal) {
162 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
163 $params['is_pay_later'] = 0;
164 $setPrevContribution = FALSE;
168 if ($contributionID) {
169 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
172 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
174 $contribution = new CRM_Contribute_BAO_Contribution();
175 $contribution->copyValues($params);
177 $contribution->id
= $contributionID;
179 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
180 $config = CRM_Core_Config
::singleton();
181 $contribution->currency
= $config->defaultCurrency
;
184 if ($contributionID && $setPrevContribution) {
185 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
188 $result = $contribution->save();
190 // Add financial_trxn details as part of fix for CRM-4724
191 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
192 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
194 //add Account details
195 $params['contribution'] = $contribution;
196 self
::recordFinancialAccounts($params);
198 // reset the group contact cache for this group
199 CRM_Contact_BAO_GroupContactCache
::remove();
201 if ($contributionID) {
202 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
205 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
212 * Given the list of params in the params array, fetch the object
213 * and store the values in the values array
215 * @param array $params input parameters to find object
216 * @param array $values output values of the object
217 * @param array $ids the array that holds all the db ids
219 * @return CRM_Contribute_BAO_Contribution|null the found object or null
223 static function &getValues($params, &$values, &$ids) {
224 if (empty($params)) {
227 $contribution = new CRM_Contribute_BAO_Contribution();
229 $contribution->copyValues($params);
231 if ($contribution->find(TRUE)) {
232 $ids['contribution'] = $contribution->id
;
234 CRM_Core_DAO
::storeValues($contribution, $values);
236 return $contribution;
242 * Get the number of terms for this contribution for a given membership type
243 * based on querying the line item table and relevant price field values
244 * Note that any one contribution should only be able to have one line item relating to a particular membership
246 * @param int $membershipTypeID
250 public function getNumTermsByContributionAndMembershipType($membershipTypeID) {
251 if (!is_numeric($membershipTypeID)) {
252 //precautionary measure - this is being introduced to a mature release hence adding extra checks that
253 // might be removed later
256 $numTerms = CRM_Core_DAO
::singleValueQuery("
257 SELECT membership_num_terms FROM civicrm_line_item li
258 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
259 WHERE contribution_id = %1 AND membership_type_id = %2",
260 array(1 => array($this->id
, 'Integer') , 2 => array($membershipTypeID, 'Integer'))
262 // default of 1 is precautionary
263 return empty($numTerms) ?
1 : $numTerms;
267 * takes an associative array and creates a contribution object
269 * @param array $params (reference ) an assoc array of name/value pairs
270 * @param array $ids the array that holds all the db ids
272 * @return object CRM_Contribute_BAO_Contribution object
276 static function create(&$params, $ids = array()) {
277 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
278 foreach ($dateFields as $df) {
279 if (isset($params[$df])) {
280 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
284 $transaction = new CRM_Core_Transaction();
286 $contribution = self
::add($params, $ids);
288 if (is_a($contribution, 'CRM_Core_Error')) {
289 $transaction->rollback();
290 return $contribution;
293 $params['contribution_id'] = $contribution->id
;
295 if (!empty($params['custom']) &&
296 is_array($params['custom'])
298 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
301 $session = CRM_Core_Session
::singleton();
303 if (!empty($params['note'])) {
305 'entity_table' => 'civicrm_contribution',
306 'note' => $params['note'],
307 'entity_id' => $contribution->id
,
308 'contact_id' => $session->get('userID'),
309 'modified_date' => date('Ymd'),
311 if (!$noteParams['contact_id']) {
312 $noteParams['contact_id'] = $params['contact_id'];
314 CRM_Core_BAO_Note
::add($noteParams);
317 // make entry in batch entity batch table
318 if (!empty($params['batch_id'])) {
319 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
320 $titleFields = array(
326 $retrieveRequired = 0;
327 foreach ($titleFields as $titleField) {
328 if(!isset($contribution->$titleField)){
329 $retrieveRequired = 1;
333 if ($retrieveRequired == 1) {
334 $contribution->find(TRUE);
338 // check if activity record exist for this contribution, if
340 $activity = new CRM_Activity_DAO_Activity();
341 $activity->source_record_id
= $contribution->id
;
342 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
346 if (!$activity->find(TRUE)) {
347 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
350 // CRM-13237 : if activity record found, update it with campaign id of contribution
351 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
354 // Handle soft credit and / or link to personal campaign page
355 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
357 //Delete PCP against this contribution and create new on submitted PCP information
358 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
360 $deleteParams = array('id' => $pcpId);
361 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
363 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
364 $softParams = array();
365 $softParams['contribution_id'] = $contribution->id
;
366 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
367 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
368 $pcp['pcp_made_through_id'], 'contact_id'
370 $softParams['currency'] = $contribution->currency
;
371 $softParams['amount'] = $contribution->total_amount
;
372 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
373 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
374 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
375 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
376 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
378 if (isset($params['soft_credit'])) {
379 $softParams = $params['soft_credit'];
381 if (!empty($softIDs)) {
382 foreach ( $softIDs as $softID) {
383 if (!in_array($softID, $params['soft_credit_ids'])) {
384 $deleteParams = array('id' => $softID);
385 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
390 foreach ($softParams as $softParam) {
391 $softParam['contribution_id'] = $contribution->id
;
392 $softParam['currency'] = $contribution->currency
;
393 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
394 if (empty($softParam['amount'])) {
395 $softParam['amount'] = $contribution->total_amount
;
397 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
401 $transaction->commit();
403 // do not add to recent items for import, CRM-4399
404 if (empty($params['skipRecentView'])) {
405 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
406 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
408 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
409 $titleFields = array(
415 $retrieveRequired = 0;
416 foreach ($titleFields as $titleField) {
417 if(!isset($contribution->$titleField)){
418 $retrieveRequired = 1;
422 if($retrieveRequired == 1){
423 $contribution->find(TRUE);
425 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
426 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
428 $recentOther = array();
429 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
430 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
431 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
435 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
436 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
437 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
441 // add the recently created Contribution
442 CRM_Utils_Recent
::add($title,
446 $contribution->contact_id
,
452 return $contribution;
456 * Get the values for pseudoconstants for name->value and reverse.
458 * @param array $defaults (reference) the default values, some of which need to be resolved.
459 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
465 static function resolveDefaults(&$defaults, $reverse = FALSE) {
466 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
467 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
468 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
469 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
473 * This function is used to convert associative array names to values
476 * This function is used by both the web form layer and the api. Note that
477 * the api needs the name => value conversion, also the view layer typically
478 * requires value => name conversion
480 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
481 $id = $property . '_id';
483 $src = $reverse ?
$property : $id;
484 $dst = $reverse ?
$id : $property;
486 if (!array_key_exists($src, $defaults)) {
490 $look = $reverse ?
array_flip($lookup) : $lookup;
492 if (is_array($look)) {
493 if (!array_key_exists($defaults[$src], $look)) {
497 $defaults[$dst] = $look[$defaults[$src]];
502 * Takes a bunch of params that are needed to match certain criteria and
503 * retrieves the relevant objects. We'll tweak this function to be more
504 * full featured over a period of time. This is the inverse function of
505 * create. It also stores all the retrieved values in the default array
507 * @param array $params (reference ) an assoc array of name/value pairs
508 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
509 * in a hierarchical manner
510 * @param array $ids (reference) the array that holds all the db ids
512 * @return object CRM_Contribute_BAO_Contribution object
516 static function retrieve(&$params, &$defaults, &$ids) {
517 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
518 return $contribution;
522 * combine all the importable fields from the lower levels object
524 * The ordering is important, since currently we do not have a weight
525 * scheme. Adding weight is super important and should be done in the
526 * next week or so, before this can be called complete.
528 * @param string $contactType
529 * @param bool $status
531 * @return array array of importable Fields
535 static function &importableFields($contactType = 'Individual', $status = TRUE) {
536 if (!self
::$_importableFields) {
537 if (!self
::$_importableFields) {
538 self
::$_importableFields = array();
542 $fields = array('' => array('title' => ts('- do not import -')));
545 $fields = array('' => array('title' => ts('- Contribution Fields -')));
548 $note = CRM_Core_DAO_Note
::import();
549 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
550 unset($tmpFields['option_value']);
551 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
552 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
554 // Using new Dedupe rule.
556 'contact_type' => $contactType,
557 'used' => 'Unsupervised',
559 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
560 $tmpContactField = array();
561 if (is_array($fieldsArray)) {
562 foreach ($fieldsArray as $value) {
563 //skip if there is no dupe rule
564 if ($value == 'none') {
567 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
572 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
573 $tmpContactField[trim($value)] = $contactFields[trim($value)];
575 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
578 $title = $tmpContactField[trim($value)]['title'];
580 $tmpContactField[trim($value)]['title'] = $title;
584 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
585 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
586 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
587 $fields = array_merge($fields, $tmpContactField);
588 $fields = array_merge($fields, $tmpFields);
589 $fields = array_merge($fields, $note);
590 $fields = array_merge($fields, $optionFields);
591 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
592 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
593 self
::$_importableFields = $fields;
595 return self
::$_importableFields;
601 static function &exportableFields() {
602 if (!self
::$_exportableFields) {
603 if (!self
::$_exportableFields) {
604 self
::$_exportableFields = array();
607 $impFields = CRM_Contribute_DAO_Contribution
::export();
608 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
609 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
610 $typeField = CRM_Financial_DAO_FinancialType
::export();
611 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
612 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
613 $contributionStatus = array(
614 'contribution_status' => array(
615 'title' => ts('Contribution Status'),
616 'name' => 'contribution_status',
617 'data_type' => CRM_Utils_Type
::T_STRING
620 $contributionNote = array(
621 'contribution_note' =>
623 'title' => ts('Contribution Note'),
624 'name' => 'contribution_note',
625 'data_type' => CRM_Utils_Type
::T_TEXT
629 $contributionRecurId = array(
630 'contribution_recur_id' =>
632 'title' => ts('Recurring Contributions ID'),
633 'name' => 'contribution_recur_id',
634 'where' => 'civicrm_contribution.contribution_recur_id',
635 'data_type' => CRM_Utils_Type
::T_INT
638 $extraFields = array(
639 'contribution_batch' => array(
640 'title' => ts('Batch Name')
644 $softCreditFields = array(
645 'contribution_soft_credit_name' => array(
646 'name' => 'contribution_soft_credit_name',
647 'title' => 'Soft Credit For',
648 'where' => 'civicrm_contact_d.display_name',
649 'data_type' => CRM_Utils_Type
::T_STRING
651 'contribution_soft_credit_amount' => array(
652 'name' => 'contribution_soft_credit_amount',
653 'title' => 'Soft Credit Amount',
654 'where' => 'civicrm_contribution_soft.amount',
655 'data_type' => CRM_Utils_Type
::T_MONEY
657 'contribution_soft_credit_type' => array(
658 'name' => 'contribution_soft_credit_type',
659 'title' => 'Soft Credit Type',
660 'where' => 'contribution_softcredit_type.label',
661 'data_type' => CRM_Utils_Type
::T_STRING
663 'contribution_soft_credit_contribution_id' => array(
664 'name' => 'contribution_soft_credit_contribution_id',
665 'title' => 'Soft Credit For Contribution ID',
666 'where' => 'civicrm_contribution_soft.contribution_id',
667 'data_type' => CRM_Utils_Type
::T_INT
671 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
672 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
673 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
676 self
::$_exportableFields = $fields;
679 return self
::$_exportableFields;
683 * @param null $status
684 * @param null $startDate
685 * @param null $endDate
689 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
693 $where[] = 'contribution_status_id = 1';
697 $where[] = 'contribution_status_id = 3';
702 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
705 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
708 $whereCond = implode(' AND ', $where);
711 SELECT sum( total_amount ) as total_amount,
712 count( civicrm_contribution.id ) as total_count,
714 FROM civicrm_contribution
715 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
717 AND ( is_test = 0 OR is_test IS NULL )
718 AND contact.is_deleted = 0
722 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
725 while ($dao->fetch()) {
726 $count +
= $dao->total_count
;
727 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
730 return array('amount' => implode(', ', $amount),
738 * Delete the indirect records associated with this contribution first
742 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
745 static function deleteContribution($id) {
746 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
748 $transaction = new CRM_Core_Transaction();
751 //delete activity record
753 'source_record_id' => $id,
754 // activity type id for contribution
755 'activity_type_id' => 6,
758 CRM_Activity_BAO_Activity
::deleteActivity($params);
760 //delete billing address if exists for this contribution.
761 self
::deleteAddress($id);
763 //update pledge and pledge payment, CRM-3961
764 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
766 // remove entry from civicrm_price_set_entity, CRM-5095
767 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
768 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
770 // cleanup line items.
771 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
773 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
774 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
776 if ($participantId) {
777 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
780 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
784 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
785 $noteId = key($note);
787 CRM_Core_BAO_Note
::del($noteId, FALSE);
790 $dao = new CRM_Contribute_DAO_Contribution();
793 $results = $dao->delete();
795 $transaction->commit();
797 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
799 // delete the recently created Contribution
800 $contributionRecent = array(
802 'type' => 'Contribution',
804 CRM_Utils_Recent
::del($contributionRecent);
810 * Check if there is a contribution with the same trxn_id or invoice_id
813 * @param array $duplicates (reference ) store ids of duplicate contribs
817 * @internal param array $params (reference ) an assoc array of name/value pairs
818 * @return boolean true if duplicate, false otherwise
822 static function checkDuplicate($input, &$duplicates, $id = NULL) {
824 $id = CRM_Utils_Array
::value('id', $input);
826 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
827 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
833 $clause[] = "trxn_id = %1";
834 $input[1] = array($trxn_id, 'String');
838 $clause[] = "invoice_id = %2";
839 $input[2] = array($invoice_id, 'String');
842 if (empty($clause)) {
846 $clause = implode(' OR ', $clause);
848 $clause = "( $clause ) AND id != %3";
849 $input[3] = array($id, 'Integer');
852 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
853 $dao = CRM_Core_DAO
::executeQuery($query, $input);
855 while ($dao->fetch()) {
856 $duplicates[] = $dao->id
;
863 * takes an associative array and creates a contribution_product object
865 * the function extract all the params it needs to initialize the create a
866 * contribution_product object. the params array could contain additional unused name/value
869 * @param array $params (reference ) an assoc array of name/value pairs
871 * @return object CRM_Contribute_BAO_ContributionProduct object
875 static function addPremium(&$params) {
876 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
877 $contributionProduct->copyValues($params);
878 return $contributionProduct->save();
882 * Function to get list of contribution fields for profile
883 * For now we only allow custom contribution fields to be in
886 * @param boolean $addExtraFields true if special fields needs to be added
888 * @return array the list of contribution fields
892 static function getContributionFields($addExtraFields = TRUE) {
893 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
894 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
896 if ($addExtraFields) {
897 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
900 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
902 foreach ($contributionFields as $key => $var) {
903 if ($key == 'contribution_contact_id') {
906 elseif ($key == 'contribution_campaign_id') {
907 $var['title'] = ts('Campaign');
909 $fields[$key] = $var;
912 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
917 * Function to add extra fields specific to contribtion
921 static function getSpecialContributionFields() {
922 $extraFields = array(
923 'contribution_soft_credit_name' => array(
924 'name' => 'contribution_soft_credit_name',
925 'title' => 'Soft Credit Name',
926 'headerPattern' => '/^soft_credit_name$/i',
927 'where' => 'civicrm_contact_d.display_name',
929 'contribution_soft_credit_email' => array(
930 'name' => 'contribution_soft_credit_email',
931 'title' => 'Soft Credit Email',
932 'headerPattern' => '/^soft_credit_email$/i',
933 'where' => 'soft_email.email',
935 'contribution_soft_credit_phone' => array(
936 'name' => 'contribution_soft_credit_phone',
937 'title' => 'Soft Credit Phone',
938 'headerPattern' => '/^soft_credit_phone$/i',
939 'where' => 'soft_phone.phone',
941 'contribution_soft_credit_contact_id' => array(
942 'name' => 'contribution_soft_credit_contact_id',
943 'title' => 'Soft Credit Contact ID',
944 'headerPattern' => '/^soft_credit_contact_id$/i',
945 'where' => 'civicrm_contribution_soft.contact_id',
957 static function getCurrentandGoalAmount($pageID) {
959 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
960 FROM civicrm_contribution_page p,
961 civicrm_contribution c
962 WHERE p.id = c.contribution_page_id
964 AND c.cancel_date is null
968 $config = CRM_Core_Config
::singleton();
969 $params = array(1 => array($pageID, 'Integer'));
970 $dao = CRM_Core_DAO
::executeQuery($query, $params);
973 return array($dao->goal
, $dao->total
);
976 return array(NULL, NULL);
981 * Function to get list of contribution In Honor of contact Ids
983 * @param int $honorId In Honor of Contact ID
985 * @return return the list of contribution fields
990 static function getHonorContacts($honorId) {
992 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
993 $honorDAO->contact_id
= $honorId;
996 $type = CRM_Contribute_PseudoConstant
::financialType();
998 while ($honorDAO->fetch()) {
999 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1000 $contributionDAO->id
= $honorDAO->contribution_id
;
1002 if ($contributionDAO->find(TRUE)) {
1003 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1004 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1005 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1006 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1007 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1008 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1009 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1010 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1011 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1019 * function to get the sort name of a contact for a particular contribution
1021 * @param int $id id of the contribution
1023 * @return null|string sort name of the contact if found
1027 static function sortName($id) {
1028 $id = CRM_Utils_Type
::escape($id, 'Integer');
1031 SELECT civicrm_contact.sort_name
1032 FROM civicrm_contribution, civicrm_contact
1033 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1034 AND civicrm_contribution.id = {$id}
1036 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1044 static function annual($contactID) {
1045 if (is_array($contactID)) {
1046 $contactIDs = implode(',', $contactID);
1049 $contactIDs = $contactID;
1052 $config = CRM_Core_Config
::singleton();
1053 $startDate = $endDate = NULL;
1055 $currentMonth = date('m');
1056 $currentDay = date('d');
1057 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1058 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1059 (int ) $config->fiscalYearStart
['d'] > $currentDay
1062 $year = date('Y') - 1;
1067 $nextYear = $year +
1;
1069 if ($config->fiscalYearStart
) {
1070 if ($config->fiscalYearStart
['M'] < 10) {
1071 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1073 if ($config->fiscalYearStart
['d'] < 10) {
1074 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1076 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1081 $startDate = "$year$monthDay";
1082 $endDate = "$nextYear$monthDay";
1085 SELECT count(*) as count,
1086 sum(total_amount) as amount,
1087 avg(total_amount) as average,
1089 FROM civicrm_contribution b
1090 WHERE b.contact_id IN ( $contactIDs )
1091 AND b.contribution_status_id = 1
1093 AND b.receive_date >= $startDate
1094 AND b.receive_date < $endDate
1097 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1099 $amount = $average = array();
1100 while ($dao->fetch()) {
1101 if ($dao->count
> 0 && $dao->amount
> 0) {
1102 $count +
= $dao->count
;
1103 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1104 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1110 implode(', ', $amount),
1111 implode(', ', $average),
1114 return array(0, 0, 0);
1118 * Check if there is a contribution with the params passed in.
1119 * Used for trxn_id,invoice_id and contribution_id
1121 * @param array $params an assoc array of name/value pairs
1123 * @return array contribution id if success else NULL
1127 static function checkDuplicateIds($params) {
1128 $dao = new CRM_Contribute_DAO_Contribution();
1132 foreach ($params as $k => $v) {
1134 $clause[] = "$k = '$v'";
1137 $clause = implode(' AND ', $clause);
1138 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1139 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1141 while ($dao->fetch()) {
1149 * Function to get the contribution details for component export
1151 * @param int $exportMode export mode
1152 * @param string $componentIds component ids
1154 * @return array associated array
1159 static function getContributionDetails($exportMode, $componentIds) {
1160 $paymentDetails = array();
1161 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1163 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1164 $componentSelect = " civicrm_participant_payment.participant_id id";
1165 $additionalClause = "
1166 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1167 AND civicrm_participant_payment.participant_id {$componentClause} )
1170 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1171 $componentSelect = " civicrm_membership_payment.membership_id id";
1172 $additionalClause = "
1173 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1174 AND civicrm_membership_payment.membership_id {$componentClause} )
1177 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1178 $componentSelect = " civicrm_pledge_payment.id id";
1179 $additionalClause = "
1180 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1181 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1185 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1186 trxn_id, {$componentSelect}
1187 FROM civicrm_contribution
1188 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1189 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1190 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1191 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1192 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1193 AND option_group_contribution_status.id = contribution_status.option_group_id )
1197 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1199 while ($dao->fetch()) {
1200 $paymentDetails[$dao->id
] = array(
1201 'total_amount' => $dao->total_amount
,
1202 'contribution_status' => $dao->status
,
1203 'receive_date' => $dao->receive_date
,
1204 'pay_instru' => $dao->payment_instrument
,
1205 'trxn_id' => $dao->trxn_id
,
1209 return $paymentDetails;
1213 * Function to create address associated with contribution record.
1215 * @param array $params an associated array
1216 * @param $billingLocationTypeID
1218 * @internal param int $billingID $billingLocationTypeID
1220 * @return address id
1223 static function createAddress(&$params, $billingLocationTypeID) {
1224 $billingFields = array(
1227 'state_province_id',
1232 //build address array
1233 $addressParams = array();
1234 $addressParams['location_type_id'] = $billingLocationTypeID;
1235 $addressParams['is_billing'] = 1;
1237 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1238 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1239 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1240 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1242 foreach ($billingFields as $value) {
1243 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1246 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1248 return $address->id
;
1252 * Delete billing address record related contribution
1254 * @param null $contributionId
1255 * @param null $contactId
1257 * @internal param int $contact_id contact id
1258 * @internal param int $contribution_id contributionId
1262 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1264 $contactJoin = NULL;
1266 if ($contributionId) {
1267 $clauses[] = "cc.id = {$contributionId}";
1271 $clauses[] = "cco.id = {$contactId}";
1272 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1275 if (empty($clauses)) {
1276 CRM_Core_Error
::fatal();
1279 $condition = implode(' OR ', $clauses);
1283 FROM civicrm_address ca
1284 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1288 $dao = CRM_Core_DAO
::executeQuery($query);
1290 while ($dao->fetch()) {
1291 $params = array('id' => $dao->id
);
1292 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1297 * This function check online pending contribution associated w/
1298 * Online Event Registration or Online Membership signup.
1300 * @param int $componentId participant/membership id.
1301 * @param string $componentName Event/Membership.
1303 * @return $contributionId pending contribution id.
1306 static function checkOnlinePendingContribution($componentId, $componentName) {
1307 $contributionId = NULL;
1308 if (!$componentId ||
1309 !in_array($componentName, array('Event', 'Membership'))
1311 return $contributionId;
1314 if ($componentName == 'Event') {
1315 $idName = 'participant_id';
1316 $componentTable = 'civicrm_participant';
1317 $paymentTable = 'civicrm_participant_payment';
1318 $source = ts('Online Event Registration');
1321 if ($componentName == 'Membership') {
1322 $idName = 'membership_id';
1323 $componentTable = 'civicrm_membership';
1324 $paymentTable = 'civicrm_membership_payment';
1325 $source = ts('Online Contribution');
1328 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1331 SELECT component.id as {$idName},
1332 componentPayment.contribution_id as contribution_id,
1333 contribution.source source,
1334 contribution.contribution_status_id as contribution_status_id,
1335 contribution.is_pay_later as is_pay_later
1336 FROM $componentTable component
1337 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1338 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1339 WHERE component.id = {$componentId}";
1341 $dao = CRM_Core_DAO
::executeQuery($query);
1343 while ($dao->fetch()) {
1344 if ($dao->contribution_id
&&
1345 $dao->is_pay_later
&&
1346 $dao->contribution_status_id
== $pendingStatusId &&
1347 strpos($dao->source
, $source) !== FALSE
1349 $contributionId = $dao->contribution_id
;
1354 return $contributionId;
1358 * This function update contribution as well as related objects.
1360 static function transitionComponents($params, $processContributionObject = FALSE) {
1361 // get minimum required values.
1362 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1363 $componentId = CRM_Utils_Array
::value('component_id', $params);
1364 $componentName = CRM_Utils_Array
::value('componentName', $params);
1365 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1366 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1368 // if we already processed contribution object pass previous status id.
1369 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1371 $updateResult = array();
1373 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1375 // we process only ( Completed, Cancelled, or Failed ) contributions.
1376 if (!$contributionId ||
1377 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1378 array_search('Cancelled', $contributionStatuses),
1379 array_search('Failed', $contributionStatuses),
1382 return $updateResult;
1385 if (!$componentName ||
!$componentId) {
1386 // get the related component details.
1387 $componentDetails = self
::getComponentDetails($contributionId);
1390 $componentDetails['contact_id'] = $contactId;
1391 $componentDetails['component'] = $componentName;
1393 if ($componentName == 'event') {
1394 $componentDetails['participant'] = $componentId;
1397 $componentDetails['membership'] = $componentId;
1401 if (!empty($componentDetails['contact_id'])) {
1402 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1408 // do check for required ids.
1409 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1410 return $updateResult;
1413 //now we are ready w/ required ids, start processing.
1415 $baseIPN = new CRM_Core_Payment_BaseIPN();
1417 $input = $ids = $objects = array();
1419 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1420 $ids['contribution'] = $contributionId;
1421 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1422 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1423 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1424 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1425 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1426 $ids['contributionRecur'] = NULL;
1427 $ids['contributionPage'] = NULL;
1429 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1430 CRM_Core_Error
::fatal();
1433 $memberships = &$objects['membership'];
1434 $participant = &$objects['participant'];
1435 $pledgePayment = &$objects['pledge_payment'];
1436 $contribution = &$objects['contribution'];
1438 if ($pledgePayment) {
1439 $pledgePaymentIDs = array();
1440 foreach ($pledgePayment as $key => $object) {
1441 $pledgePaymentIDs[] = $object->id
;
1443 $pledgeID = $pledgePayment[0]->pledge_id
;
1446 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1449 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1450 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1455 // we might want to process contribution object.
1456 $processContribution = FALSE;
1457 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1458 if (is_array($memberships)) {
1459 foreach ($memberships as $membership) {
1461 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1462 $membership->save();
1464 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1465 if ($processContributionObject) {
1466 $processContribution = TRUE;
1473 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1474 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1476 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1477 if ($processContributionObject) {
1478 $processContribution = TRUE;
1482 if ($pledgePayment) {
1483 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1485 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1486 if ($processContributionObject) {
1487 $processContribution = TRUE;
1491 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1492 if (is_array($memberships)) {
1493 foreach ($memberships as $membership) {
1495 $membership->status_id
= array_search('Expired', $membershipStatuses);
1496 $membership->save();
1498 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1499 if ($processContributionObject) {
1500 $processContribution = TRUE;
1506 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1507 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1509 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1510 if ($processContributionObject) {
1511 $processContribution = TRUE;
1515 if ($pledgePayment) {
1516 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1518 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1519 if ($processContributionObject) {
1520 $processContribution = TRUE;
1524 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1526 // only pending contribution related object processed.
1527 if ($previousContriStatusId &&
1528 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1530 // this is case when we already processed contribution object.
1531 return $updateResult;
1533 elseif (!$previousContriStatusId &&
1534 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1536 // this is case when we are going to process contribution object later.
1537 return $updateResult;
1540 if (is_array($memberships)) {
1541 foreach ($memberships as $membership) {
1546 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1547 $membership->membership_type_id
,
1548 $membership->is_test
, $membership->id
1551 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1552 // this picks up membership type changes during renewals
1554 SELECT membership_type_id
1555 FROM civicrm_membership_log
1556 WHERE membership_id=$membership->id
1559 $dao = new CRM_Core_DAO
;
1561 if ($dao->fetch()) {
1562 if (!empty($dao->membership_type_id
)) {
1563 $membership->membership_type_id
= $dao->membership_type_id
;
1564 $membership->save();
1567 // else fall back to using current membership type
1570 // Figure out number of terms
1572 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1573 foreach ($lineitems as $lineitem) {
1574 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1575 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1577 // in case membership_num_terms comes through as null or zero
1578 $numterms = $numterms >= 1 ?
$numterms : 1;
1583 if ($currentMembership) {
1584 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1585 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1586 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1589 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1592 //get the status for membership.
1593 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1595 $dates['join_date'],
1598 $membership->membership_type_id
,
1602 $formattedParams = array(
1603 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1604 array_search('Current', $membershipStatuses)
1606 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1607 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1608 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1611 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1613 $membership->copyValues($formattedParams);
1614 $membership->save();
1616 //updating the membership log
1617 $membershipLog = array();
1618 $membershipLog = $formattedParams;
1619 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1620 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1622 $membershipLog['start_date'] = $logStartDate;
1623 $membershipLog['membership_id'] = $membership->id
;
1624 $membershipLog['modified_id'] = $membership->contact_id
;
1625 $membershipLog['modified_date'] = date('Ymd');
1626 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1628 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1630 //update related Memberships.
1631 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1633 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1636 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1637 if ($processContributionObject) {
1638 $processContribution = TRUE;
1641 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1647 $updatedStatusId = array_search('Registered', $participantStatuses);
1648 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1650 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1651 if ($processContributionObject) {
1652 $processContribution = TRUE;
1656 if ($pledgePayment) {
1657 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1659 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1660 if ($processContributionObject) {
1661 $processContribution = TRUE;
1666 // process contribution object.
1667 if ($processContribution) {
1668 $contributionParams = array();
1670 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1671 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1672 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1674 foreach ($fields as $field) {
1675 if (empty($params[$field])) {
1678 $contributionParams[$field] = $params[$field];
1681 $ids = array('contribution' => $contributionId);
1682 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1685 return $updateResult;
1689 * This function returns all contribution related object ids.
1691 public static function getComponentDetails($contributionId) {
1692 $componentDetails = $pledgePayment = array();
1693 if (!$contributionId) {
1694 return $componentDetails;
1698 SELECT c.id as contribution_id,
1699 c.contact_id as contact_id,
1700 mp.membership_id as membership_id,
1701 m.membership_type_id as membership_type_id,
1702 pp.participant_id as participant_id,
1703 p.event_id as event_id,
1704 pgp.id as pledge_payment_id
1705 FROM civicrm_contribution c
1706 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1707 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1708 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1709 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1710 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1711 WHERE c.id = $contributionId";
1713 $dao = CRM_Core_DAO
::executeQuery($query);
1714 $componentDetails = array();
1716 while ($dao->fetch()) {
1717 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1718 $componentDetails['contact_id'] = $dao->contact_id
;
1719 if ($dao->event_id
) {
1720 $componentDetails['event'] = $dao->event_id
;
1722 if ($dao->participant_id
) {
1723 $componentDetails['participant'] = $dao->participant_id
;
1725 if ($dao->membership_id
) {
1726 if (!isset($componentDetails['membership'])) {
1727 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1729 $componentDetails['membership'][] = $dao->membership_id
;
1730 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1732 if ($dao->pledge_payment_id
) {
1733 $pledgePayment[] = $dao->pledge_payment_id
;
1737 if ($pledgePayment) {
1738 $componentDetails['pledge_payment'] = $pledgePayment;
1741 return $componentDetails;
1746 * @param bool $includeSoftCredit
1748 * @return null|string
1750 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1755 $contactContributionsSQL = "
1756 SELECT contribution.id AS id
1757 FROM civicrm_contribution contribution
1758 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1760 $contactSoftCreditContributionsSQL = "
1761 SELECT contribution.id
1762 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1763 ON ( contribution.id = softContribution.contribution_id )
1764 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1765 $query = "SELECT count( x.id ) count FROM ( ";
1766 $query .= $contactContributionsSQL;
1768 if ($includeSoftCredit) {
1769 $query .= " UNION ";
1770 $query .= $contactSoftCreditContributionsSQL;
1775 return CRM_Core_DAO
::singleValueQuery($query);
1779 * Function to get individual id for onbehalf contribution
1781 * @param int $contributionId contribution id
1782 * @param int $contributorId contributor id
1784 * @return array $ids containing organization id and individual id
1787 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1791 if (!$contributionId) {
1795 // fetch contributor id if null
1796 if (!$contributorId) {
1797 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1798 $contributionId, 'contact_id'
1802 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1803 $activityTypeId = array_search('Contribution', $activityTypeIds);
1805 if ($activityTypeId && $contributorId) {
1807 SELECT civicrm_activity_contact.contact_id
1808 FROM civicrm_activity_contact
1809 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1810 WHERE civicrm_activity.activity_type_id = %1
1811 AND civicrm_activity.source_record_id = %2
1812 AND civicrm_activity_contact.record_type_id = %3
1815 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1816 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1819 1 => array($activityTypeId, 'Integer'),
1820 2 => array($contributionId, 'Integer'),
1821 3 => array($sourceID, 'Integer'),
1824 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1826 // for on behalf contribution source is individual and contributor is organization
1827 if ($sourceContactId && $sourceContactId != $contributorId) {
1828 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1829 // get rel type id for employee of relation
1830 foreach ($relationshipTypeIds as $id => $typeVals) {
1831 if ($typeVals['name_a_b'] == 'Employee of') {
1832 $relationshipTypeId = $id;
1837 $rel = new CRM_Contact_DAO_Relationship();
1838 $rel->relationship_type_id
= $relationshipTypeId;
1839 $rel->contact_id_a
= $sourceContactId;
1840 $rel->contact_id_b
= $contributorId;
1841 if ($rel->find(TRUE)) {
1842 $ids['individual_id'] = $rel->contact_id_a
;
1843 $ids['organization_id'] = $rel->contact_id_b
;
1855 static function getContributionDates() {
1856 $config = CRM_Core_Config
::singleton();
1857 $currentMonth = date('m');
1858 $currentDay = date('d');
1859 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1860 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1861 (int ) $config->fiscalYearStart
['d'] > $currentDay
1864 $year = date('Y') - 1;
1869 $year = array('Y' => $year);
1870 $yearDate = $config->fiscalYearStart
;
1871 $yearDate = array_merge($year, $yearDate);
1872 $yearDate = CRM_Utils_Date
::format($yearDate);
1874 $monthDate = date('Ym') . '01';
1880 'yearDate' => $yearDate,
1881 'monthDate' => $monthDate,
1886 * Load objects relations to contribution object
1887 * Objects are stored in the $_relatedObjects property
1888 * In the first instance we are just moving functionality from BASEIpn -
1889 * see http://issues.civicrm.org/jira/browse/CRM-9996
1891 * @param array $input Input as delivered from Payment Processor
1892 * @param array $ids Ids as Loaded by Payment Processor
1893 * @param boolean $required Is Payment processor / contribution page required
1894 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1895 * Note that the unit test for the BaseIPN class tests this function
1900 * @param bool $required
1901 * @param bool $loadAll
1906 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1908 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1909 if(empty($ids['contact']) && isset($this->contact_id
)){
1910 $ids['contact'] = $this->contact_id
;
1913 if (empty($this->_component
)) {
1914 if (! empty($ids['event'])) {
1915 $this->_component
= 'event';
1918 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1921 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1922 $contributionType = new CRM_Financial_BAO_FinancialType();
1923 $contributionType->id
= $this->financial_type_id
;
1924 if (!$contributionType->find(TRUE)) {
1925 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1927 if (!empty($ids['contact'])) {
1928 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1929 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1930 $this->_relatedObjects
['contact']->find(TRUE);
1932 $this->_relatedObjects
['contributionType'] = $contributionType;
1934 if ($this->_component
== 'contribute') {
1935 // retrieve the other optional objects first so
1936 // stuff down the line can use this info and do things
1938 //in any case get the memberships associated with the contribution
1939 //because we now support multiple memberships w/ price set
1940 // see if there are any other memberships to be considered for same contribution.
1942 SELECT membership_id
1943 FROM civicrm_membership_payment
1944 WHERE contribution_id = %1 ";
1945 $params = array(1 => array($this->id
, 'Integer'));
1947 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1948 while ($dao->fetch()) {
1949 if ($dao->membership_id
) {
1950 if (!is_array($ids['membership'])) {
1951 $ids['membership'] = array();
1953 $ids['membership'][] = $dao->membership_id
;
1957 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1958 foreach ($ids['membership'] as $id) {
1960 $membership = new CRM_Member_BAO_Membership();
1961 $membership->id
= $id;
1962 if (!$membership->find(TRUE)) {
1963 throw new Exception("Could not find membership record: $id");
1965 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1966 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1967 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1968 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1969 $membership->free();
1974 if (!empty($ids['pledge_payment'])) {
1976 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1977 if (empty($paymentID)) {
1980 $payment = new CRM_Pledge_BAO_PledgePayment();
1981 $payment->id
= $paymentID;
1982 if (!$payment->find(TRUE)) {
1983 throw new Exception("Could not find pledge payment record: " . $paymentID);
1985 $this->_relatedObjects
['pledge_payment'][] = $payment;
1989 if (!empty($ids['contributionRecur'])) {
1990 $recur = new CRM_Contribute_BAO_ContributionRecur();
1991 $recur->id
= $ids['contributionRecur'];
1992 if (!$recur->find(TRUE)) {
1993 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1995 $this->_relatedObjects
['contributionRecur'] = &$recur;
1996 //get payment processor id from recur object.
1997 $paymentProcessorID = $recur->payment_processor_id
;
1999 //for normal contribution get the payment processor id.
2000 if (!$paymentProcessorID) {
2001 if ($this->contribution_page_id
) {
2002 // get the payment processor id from contribution page
2003 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2004 $this->contribution_page_id
,
2008 //fail to load payment processor id.
2009 elseif (empty($ids['pledge_payment'])) {
2010 $loadObjectSuccess = TRUE;
2012 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2014 return $loadObjectSuccess;
2019 // we are in event mode
2020 // make sure event exists and is valid
2021 $event = new CRM_Event_BAO_Event();
2022 $event->id
= $ids['event'];
2023 if ($ids['event'] &&
2026 throw new Exception("Could not find event: " . $ids['event']);
2029 $this->_relatedObjects
['event'] = &$event;
2031 $participant = new CRM_Event_BAO_Participant();
2032 $participant->id
= $ids['participant'];
2033 if ($ids['participant'] &&
2034 !$participant->find(TRUE)
2036 throw new Exception("Could not find participant: " . $ids['participant']);
2038 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2040 $this->_relatedObjects
['participant'] = &$participant;
2042 if (!$paymentProcessorID) {
2043 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2047 $loadObjectSuccess = TRUE;
2048 if ($paymentProcessorID) {
2049 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2050 $this->is_test ?
'test' : 'live'
2052 $ids['paymentProcessor'] = $paymentProcessorID;
2053 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2055 elseif ($required) {
2056 $loadObjectSuccess = FALSE;
2057 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2060 return $loadObjectSuccess;
2064 * Create array of message information - ie. return html version, txt version, to field
2066 * @param array $input incoming information
2067 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2068 * just check presence of recur object but maintaining legacy approach
2070 * @param array $ids IDs of related objects
2071 * @param array $values any values that may have already been compiled by calling process
2072 * This is augmented by values 'gathered' by gatherMessageValues
2073 * @param bool $returnMessageText distinguishes between whether to send message or return
2074 * message text. We are working towards this function ALWAYS returning message text & calling
2075 * function doing emails / pdfs with it
2076 * @return array $messageArray - messages
2082 * @param bool $recur
2083 * @param bool $returnMessageText
2087 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2088 if (empty($this->_relatedObjects
)) {
2089 $this->loadRelatedObjects($input, $ids);
2091 if (empty($this->_component
)) {
2092 $this->_component
= CRM_Utils_Array
::value('component', $input);
2095 //not really sure what params might be passed in but lets merge em into values
2096 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2097 $template = CRM_Core_Smarty
::singleton();
2098 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2099 //what does recur 'mean here - to do with payment processor return functionality but
2100 // what is the importance
2101 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2102 $paymentObject = &CRM_Core_Payment
::singleton(
2103 $this->is_test ?
'test' : 'live',
2104 $this->_relatedObjects
['paymentProcessor']
2107 $entityID = $entity = NULL;
2108 if (isset($ids['contribution'])) {
2109 $entity = 'contribution';
2110 $entityID = $ids['contribution'];
2112 if (isset($ids['membership']) && $ids['membership']) {
2113 $entity = 'membership';
2114 $entityID = $ids['membership'];
2117 $url = $paymentObject->subscriptionURL($entityID, $entity);
2118 $template->assign('cancelSubscriptionUrl', $url);
2120 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2121 $template->assign('updateSubscriptionBillingUrl', $url);
2123 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2124 $template->assign('updateSubscriptionUrl', $url);
2126 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2127 //direct mode showing billing block, so use directIPN for temporary
2128 $template->assign('contributeMode', 'directIPN');
2131 // todo remove strtolower - check consistency
2132 if (strtolower($this->_component
) == 'event') {
2133 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2134 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2138 $values['contribution_id'] = $this->id
;
2139 if (!empty($ids['related_contact'])) {
2140 $values['related_contact'] = $ids['related_contact'];
2141 if (isset($ids['onbehalf_dupe_alert'])) {
2142 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2144 $entityBlock = array(
2145 'contact_id' => $ids['contact'],
2146 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2147 'Home', 'id', 'name'
2150 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2151 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2154 if ($this->is_test
) {
2157 if (!empty($this->_relatedObjects
['membership'])) {
2158 foreach ($this->_relatedObjects
['membership'] as $membership) {
2159 if ($membership->id
) {
2160 $values['isMembership'] = TRUE;
2162 // need to set the membership values here
2163 $template->assign('membership_assign', 1);
2164 $template->assign('membership_name',
2165 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2167 $template->assign('mem_start_date', $membership->start_date
);
2168 $template->assign('mem_join_date', $membership->join_date
);
2169 $template->assign('mem_end_date', $membership->end_date
);
2170 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2171 $template->assign('mem_status', $membership_status);
2172 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2173 $template->assign('is_pay_later', 1);
2176 // if separate payment there are two contributions recorded and the
2177 // admin will need to send a receipt for each of them separately.
2178 // we dont link the two in the db (but can potentially infer it if needed)
2179 $template->assign('is_separate_payment', 0);
2181 if ($recur && $paymentObject) {
2182 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2183 $template->assign('cancelSubscriptionUrl', $url);
2184 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2185 $template->assign('updateSubscriptionBillingUrl', $url);
2186 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2187 $template->assign('updateSubscriptionUrl', $url);
2190 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2193 // otherwise if its about sending emails, continue sending without return, as we
2194 // don't want to exit the loop.
2199 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2205 * Gather values for contribution mail - this function has been created
2206 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2207 * Values related to the contribution in question are gathered
2209 * @param array $input input into function (probably from payment processor)
2210 * @param array $ids the set of ids related to the inpurt
2212 * @return array $values
2214 * NB don't add direct calls to the function as we intend to change the signature
2223 function _gatherMessageValues($input, &$values, $ids = array()) {
2224 // set display address of contributor
2225 if ($this->address_id
) {
2226 $addressParams = array('id' => $this->address_id
);
2227 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2228 $addressDetails = array_values($addressDetails);
2229 $values['address'] = $addressDetails[0]['display'];
2231 if ($this->_component
== 'contribute') {
2232 if (isset($this->contribution_page_id
)) {
2233 CRM_Contribute_BAO_ContributionPage
::setValues(
2234 $this->contribution_page_id
,
2237 if ($this->contribution_page_id
) {
2238 // CRM-8254 - override default currency if applicable
2239 $config = CRM_Core_Config
::singleton();
2240 $config->defaultCurrency
= CRM_Utils_Array
::value(
2243 $config->defaultCurrency
2247 // no contribution page -probably back office
2249 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2250 $values['is_email_receipt'] = 1;
2251 $values['title'] = 'Contribution';
2253 // set lineItem for contribution
2255 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2256 if (!empty($lineItem)) {
2257 $itemId = key($lineItem);
2258 foreach ($lineItem as &$eachItem) {
2259 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2260 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2261 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2262 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2265 $values['lineItem'][0] = $lineItem;
2266 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2270 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2274 // if this is onbehalf of contribution then set related contact
2275 if (!empty($relatedContact['individual_id'])) {
2276 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2281 $eventParams = array(
2282 'id' => $this->_relatedObjects
['event']->id
,
2284 $values['event'] = array();
2286 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2288 //get location details
2289 $locationParams = array(
2290 'entity_id' => $this->_relatedObjects
['event']->id
,
2291 'entity_table' => 'civicrm_event',
2293 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2295 $ufJoinParams = array(
2296 'entity_table' => 'civicrm_event',
2297 'entity_id' => $ids['event'],
2298 'module' => 'CiviEvent',
2301 list($custom_pre_id,
2303 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2305 $values['custom_pre_id'] = $custom_pre_id;
2306 $values['custom_post_id'] = $custom_post_ids;
2308 // set lineItem for event contribution
2310 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2311 if (!empty($participantIds)) {
2312 foreach ($participantIds as $pIDs) {
2313 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2314 if (!CRM_Utils_System
::isNull($lineItem)) {
2315 $values['lineItem'][] = $lineItem;
2326 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2327 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2328 * Note we send directly from this function in some cases because it is only partly refactored
2329 * Don't call this function directly as the signature will change
2333 * @param $template CRM_Core_SMARTY
2334 * @param bool $recur
2335 * @param bool $returnMessageText
2339 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2340 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2341 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2342 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2343 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2344 $template->assign('useForMember', true);
2346 //assign honor information to receipt message
2347 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2349 if (isset($softRecord['soft_credit'])) {
2350 //if id of contribution page is present
2351 if (!empty($values['id'])) {
2352 $values['honor'] = array(
2353 'honor_profile_values' => array(),
2354 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2355 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2357 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2359 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2360 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2363 //offline contribution
2364 $softCreditTypes = $softCredits = array();
2365 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2366 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2367 $softCredits[$key] = array(
2368 'Name' => $softCredit['contact_name'],
2369 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2372 $template->assign('softCreditTypes', $softCreditTypes);
2373 $template->assign('softCredits', $softCredits);
2377 $dao = new CRM_Contribute_DAO_ContributionProduct();
2378 $dao->contribution_id
= $this->id
;
2379 if ($dao->find(TRUE)) {
2380 $premiumId = $dao->product_id
;
2381 $template->assign('option', $dao->product_option
);
2383 $productDAO = new CRM_Contribute_DAO_Product();
2384 $productDAO->id
= $premiumId;
2385 $productDAO->find(TRUE);
2386 $template->assign('selectPremium', TRUE);
2387 $template->assign('product_name', $productDAO->name
);
2388 $template->assign('price', $productDAO->price
);
2389 $template->assign('sku', $productDAO->sku
);
2391 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2392 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2393 if(empty($amount) && isset($this->total_amount
)){
2394 $amount = $this->total_amount
;
2396 $template->assign('amount', $amount);
2397 // add the new contribution values
2398 if (strtolower($this->_component
) == 'contribute') {
2400 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2401 $softDAO->contribution_id
= $this->id
;
2402 if ($softDAO->find(TRUE)) {
2403 $template->assign('pcpBlock', TRUE);
2404 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2405 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2406 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2408 //assign the pcp page title for email subject
2409 $pcpDAO = new CRM_PCP_DAO_PCP();
2410 $pcpDAO->id
= $softDAO->pcp_id
;
2411 if ($pcpDAO->find(TRUE)) {
2412 $template->assign('title', $pcpDAO->title
);
2417 if ($this->financial_type_id
) {
2418 $values['financial_type_id'] = $this->financial_type_id
;
2422 $template->assign('trxn_id', $this->trxn_id
);
2423 $template->assign('receive_date',
2424 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2426 $template->assign('contributeMode', 'notify');
2427 $template->assign('action', $this->is_test ?
1024 : 1);
2428 $template->assign('receipt_text',
2429 CRM_Utils_Array
::value('receipt_text',
2433 $template->assign('is_monetary', 1);
2434 $template->assign('is_recur', (bool) $recur);
2435 $template->assign('currency', $this->currency
);
2436 $template->assign('address', CRM_Utils_Address
::format($input));
2437 if ($this->_component
== 'event') {
2438 $template->assign('title', $values['event']['title']);
2439 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2440 $viewRoles = array();
2441 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2442 $viewRoles[] = $participantRoles[$v];
2444 $values['event']['participant_role'] = implode(', ', $viewRoles);
2445 $template->assign('event', $values['event']);
2446 $template->assign('location', $values['location']);
2447 $template->assign('customPre', $values['custom_pre_id']);
2448 $template->assign('customPost', $values['custom_post_id']);
2451 if ($this->_relatedObjects
['participant']->is_test
) {
2455 $values['params'] = array();
2456 //to get email of primary participant.
2457 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2458 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2459 //build an array of cId/pId of participants
2460 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2461 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2462 //send receipt to additional participant if exists
2463 if (count($additionalIDs)) {
2464 $template->assign('isPrimary', 0);
2465 $template->assign('customProfile', NULL);
2466 //set additionalParticipant true
2467 $values['params']['additionalParticipant'] = TRUE;
2468 foreach ($additionalIDs as $pId => $cId) {
2470 //to change the status pending to completed
2471 $additional = new CRM_Event_DAO_Participant();
2472 $additional->id
= $pId;
2473 $additional->contact_id
= $cId;
2474 $additional->find(TRUE);
2475 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2476 $additional->status_id
= 1;
2477 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2478 //if additional participant dont have email
2480 if (!$additionalParticipantInfo) {
2481 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2483 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2484 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2485 $additional->save();
2486 $additional->free();
2487 $template->assign('amount', $amount);
2488 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2492 //build an array of custom profile and assigning it to template
2493 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2495 if (count($customProfile)) {
2496 $template->assign('customProfile', $customProfile);
2499 // for primary contact
2500 $values['params']['additionalParticipant'] = FALSE;
2501 $template->assign('isPrimary', 1);
2502 $template->assign('amount', $primaryAmount);
2503 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2504 if ($this->payment_instrument_id
) {
2505 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2506 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2508 // carry paylater, since we did not created billing,
2509 // so need to pull email from primary location, CRM-4395
2510 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2516 * Function to check whether payment processor supports
2517 * cancellation of contribution subscription
2519 * @param int $contributionId contribution id
2521 * @param bool $isNotCancelled
2527 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2528 $cacheKeyString = "$contributionId";
2529 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2531 static $supportsCancel = array();
2533 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2534 $supportsCancel[$cacheKeyString] = FALSE;
2535 $isCancelled = FALSE;
2537 if ($isNotCancelled) {
2538 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2541 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2542 if (!empty($paymentObject)) {
2543 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2546 return $supportsCancel[$cacheKeyString];
2550 * Function to check whether subscription is already cancelled
2552 * @param int $contributionId contribution id
2554 * @return string $status contribution status
2558 static function isSubscriptionCancelled($contributionId) {
2560 SELECT cr.contribution_status_id
2561 FROM civicrm_contribution_recur cr
2562 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2563 WHERE con.id = %1 LIMIT 1";
2564 $params = array(1 => array($contributionId, 'Integer'));
2565 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2566 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2567 if ($status == 'Cancelled') {
2574 * Function to create all financial accounts entry
2576 * @param array $params contribution object, line item array and params for trxn
2579 * @param array $financialTrxnValues
2581 * @return null|object
2585 static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2586 $skipRecords = $update = $return = $isRelatedId = FALSE;
2588 $additionalParticipantId = array();
2589 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2591 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2592 $entityId = $params['participant_id'];
2593 $entityTable = 'civicrm_participant';
2594 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2596 elseif (!empty($params['membership_id'])) {
2597 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2598 // are created off one contribution should be handled elsewhere
2599 $entityId = $params['membership_id'];
2600 $entityTable = 'civicrm_membership';
2603 $entityId = $params['contribution']->id
;
2604 $entityTable = 'civicrm_contribution';
2607 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2608 $isRelatedId = TRUE;
2611 $entityID[] = $entityId;
2612 if (!empty($additionalParticipantId)) {
2613 $entityID +
= $additionalParticipantId;
2615 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2616 if (empty($params['prevContribution'])) {
2623 $statusId = $params['contribution']->contribution_status_id
;
2624 // CRM-13964 partial payment
2625 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2626 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2627 $partialAmtPay = $params['partial_amount_pay'];
2628 $partialAmtTotal = $params['partial_payment_total'];
2630 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2631 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2632 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2633 $params['total_amount'] = $partialAmtPay;
2635 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2636 if (empty($balanceTrxnInfo['trxn_id'])) {
2637 // create new balance transaction record
2638 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2639 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2641 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2642 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2643 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2644 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2645 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2646 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2647 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2648 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2649 $balanceTrxnParams['status_id'] = $statusId;
2650 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2651 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2652 if (!empty($params['payment_processor'])) {
2653 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2655 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2659 // build line item array if its not set in $params
2660 if (empty($params['line_item']) ||
$additionalParticipantId) {
2661 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2664 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2665 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2666 $skipRecords = TRUE;
2667 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2668 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2669 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2670 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2672 elseif (!empty($params['payment_processor'])) {
2673 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2675 elseif (!empty($params['payment_instrument_id'])) {
2676 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2679 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2680 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2681 $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);
2684 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2685 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2686 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2689 //build financial transaction params
2690 $trxnParams = array(
2691 'contribution_id' => $params['contribution']->id
,
2692 'to_financial_account_id' => $params['to_financial_account_id'],
2693 'trxn_date' => date('YmdHis'),
2694 'total_amount' => $totalAmount,
2695 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2696 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2697 'currency' => $params['contribution']->currency
,
2698 'trxn_id' => $params['contribution']->trxn_id
,
2699 'status_id' => $statusId,
2700 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2701 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2704 if (!empty($params['payment_processor'])) {
2705 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2708 if (isset($fromFinancialAccountId)) {
2709 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2712 // consider external values passed for recording transaction entry
2713 if (!empty($financialTrxnValues)) {
2714 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2717 $params['trxnParams'] = $trxnParams;
2719 if (!empty($params['prevContribution'])) {
2720 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2721 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2722 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2723 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2724 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2727 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2728 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2729 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))) {
2730 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2731 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2734 //if financial type is changed
2735 if (!empty($params['financial_type_id']) &&
2736 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2737 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2738 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2739 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2740 if ($oldFinancialAccount != $newFinancialAccount) {
2741 $params['total_amount'] = 0;
2742 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2743 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2744 $params['prevContribution']->financial_type_id
, $relationTypeId);
2747 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2748 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2749 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2752 self
::updateFinancialAccounts($params, 'changeFinancialType');
2753 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2754 $params['financial_account_id'] = $newFinancialAccount;
2755 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2756 self
::updateFinancialAccounts($params);
2757 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2761 //Update contribution status
2762 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2763 if (!empty($params['contribution_status_id']) &&
2764 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2765 //Update Financial Records
2766 self
::updateFinancialAccounts($params, 'changedStatus');
2769 // change Payment Instrument for a Completed contribution
2770 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2771 // instrument is null and now new payment instrument is added along with the payment
2772 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2773 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2774 if (array_key_exists('payment_instrument_id', $params)) {
2775 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2776 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2777 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2778 //check if status is changed from Pending to Completed
2779 // do not update payment instrument changes for Pending to Completed
2780 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2781 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2782 // for all other statuses create new financial records
2783 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2784 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2785 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2788 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2789 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2790 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2791 // for any other payment instrument changes create new financial records
2792 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2793 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2794 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2796 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2797 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2798 // another special case when check number is changed, create new financial records
2799 // create financial trxn with negative amount
2800 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2801 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2802 // create financial trxn with positive amount
2803 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2804 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2805 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2809 //if Change contribution amount
2810 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2811 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2812 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2813 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2814 if (isset($totalAmount) &&
2815 $totalAmount != $params['prevContribution']->total_amount
) {
2816 //Update Financial Records
2817 $params['trxnParams']['from_financial_account_id'] = NULL;
2818 self
::updateFinancialAccounts($params, 'changedAmount');
2823 // records finanical trxn and entity financial trxn
2824 // also make it available as return value
2825 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2826 $params['entity_id'] = $financialTxn->id
;
2829 // record line items and finacial items
2830 if (empty($params['skipLineItem'])) {
2831 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2834 // create batch entry if batch_id is passed
2835 if (!empty($params['batch_id'])) {
2836 $entityParams = array(
2837 'batch_id' => $params['batch_id'],
2838 'entity_table' => 'civicrm_financial_trxn',
2839 'entity_id' => $financialTxn->id
,
2841 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2844 // when a fee is charged
2845 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2846 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2849 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2850 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2851 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2852 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2853 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2855 unset($params['line_item']);
2861 * Function to update all financial accounts entry
2863 * @param array $params contribution object, line item array and params for trxn
2865 * @param string $context update scenarios
2867 * @param null $skipTrxn
2872 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2873 $itemAmount = $trxnID = NULL;
2874 //get all the statuses
2875 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2876 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2877 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2878 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2879 && $context == 'changePaymentInstrument') {
2882 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2883 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2885 if ($context == 'changedStatus') {
2886 //get all the statuses
2887 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2889 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2890 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2891 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2892 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2894 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2895 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2896 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2897 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2898 $params['trxnParams']['to_financial_account_id'] = NULL;
2899 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2901 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2902 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2903 $financialTypeID, $relationTypeId);
2905 $itemAmount = $params['trxnParams']['total_amount'];
2907 elseif ($context == 'changePaymentInstrument') {
2908 if ($params['trxnParams']['total_amount'] < 0) {
2909 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2910 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2911 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2912 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2916 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2917 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2920 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2921 $params['entity_id'] = $trxn->id
;
2923 if ($context == 'changedStatus') {
2924 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2925 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2926 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2927 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2928 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2930 $entityParams = array(
2931 'entity_table' => 'civicrm_financial_item',
2932 'financial_trxn_id' => $trxn->id
,
2934 if (empty($params['line_item'])) {
2936 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
2937 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
2938 // & this can be removed
2941 foreach ($params['line_item'] as $fieldId => $fields) {
2942 foreach ($fields as $fieldValueId => $fieldValues) {
2944 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2945 2 => array($fieldValues['id'], 'Integer'),
2947 CRM_Core_DAO
::executeQuery($query, $fparams);
2949 1 => array($fieldValues['id'], 'Integer'),
2951 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2952 while ($financialItem->fetch()) {
2953 $entityParams['entity_id'] = $financialItem->id
;
2954 $entityParams['amount'] = $financialItem->amount
;
2955 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2962 if ($context != 'changePaymentInstrument') {
2963 $itemParams['entity_table'] = 'civicrm_line_item';
2964 $trxnIds['id'] = $params['entity_id'];
2965 foreach ($params['line_item'] as $fieldId => $fields) {
2966 foreach ($fields as $fieldValueId => $fieldValues) {
2967 $prevParams['entity_id'] = $fieldValues['id'];
2968 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2970 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2971 if ($params['contribution']->receive_date
) {
2972 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2975 $financialAccount = $prevfinancialItem->financial_account_id
;
2976 if (!empty($params['financial_account_id'])) {
2977 $financialAccount = $params['financial_account_id'];
2980 $currency = $params['prevContribution']->currency
;
2981 if ($params['contribution']->currency
) {
2982 $currency = $params['contribution']->currency
;
2985 if (!empty($params['is_quick_config'])) {
2986 $amount = $itemAmount;
2988 $amount = $params['total_amount'];
2992 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
2993 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)) {
2996 $amount = $diff * $fieldValues['line_total'];
2999 $itemParams = array(
3000 'transaction_date' => $receiveDate,
3001 'contact_id' => $params['prevContribution']->contact_id
,
3002 'currency' => $currency,
3003 'amount' => $amount,
3004 'description' => $prevfinancialItem->description
,
3005 'status_id' => $prevfinancialItem->status_id
,
3006 'financial_account_id' => $financialAccount,
3007 'entity_table' => 'civicrm_line_item',
3008 'entity_id' => $fieldValues['id']
3010 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3012 if ($fieldValues['tax_amount']) {
3013 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3014 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3015 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3016 $itemParams['description'] = $taxTerm;
3017 if ($fieldValues['financial_type_id']) {
3018 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3020 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3028 * Function to check status validation on update of a contribution
3030 * @param array $values previous form values before submit
3032 * @param array $fields the input form values
3034 * @param array $errors list of errors
3040 static function checkStatusValidation($values, &$fields, &$errors) {
3041 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3042 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3043 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3047 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3048 $checkStatus = array(
3049 'Cancelled' => array('Completed', 'Refunded'),
3050 'Completed' => array('Cancelled', 'Refunded'),
3051 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3052 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3053 'Refunded' => array('Cancelled', 'Completed')
3056 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3057 $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']]));
3062 * Function to delete contribution of contact
3066 * @param integer $contactId contact id
3071 static function deleteContactContribution($contactId) {
3072 $contribution = new CRM_Contribute_DAO_Contribution();
3073 $contribution->contact_id
= $contactId;
3074 $contribution->find();
3075 while ($contribution->fetch()) {
3076 self
::deleteContribution($contribution->id
);
3081 * Get options for a given contribution field.
3082 * @see CRM_Core_DAO::buildOptions
3084 * @param String $fieldName
3085 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3086 * @param Array $props : whatever is known about this dao object
3088 * @return Array|bool
3090 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3091 $className = __CLASS__
;
3093 switch ($fieldName) {
3094 // This field is not part of this object but the api supports it
3095 case 'payment_processor':
3096 $className = 'CRM_Contribute_BAO_ContributionPage';
3097 // Filter results by contribution page
3098 if (!empty($props['contribution_page_id'])) {
3099 $page = civicrm_api('contribution_page', 'getsingle', array(
3101 'id' => ($props['contribution_page_id'])
3103 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3104 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3107 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3111 * Function to validate financial type
3115 * @param integer $financialTypeId Financial Type id
3117 * @param string $relationName
3119 * @return array|bool
3123 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3124 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3125 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3127 if (!$financialAccount) {
3128 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3135 * Function to record additional payment for partial and refund contributions
3137 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3138 * @param array $trxnData : to take user provided input of transaction details.
3139 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3142 * @param $contributionId
3144 * @param string $paymentType
3145 * @param null $participantId
3147 * @return null|object
3149 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3150 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3151 $getInfoOf['id'] = $contributionId;
3152 $defaults = array();
3153 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3155 if ($paymentType == 'owed') {
3156 // build params for recording financial trxn entry
3157 $params['contribution'] = $contributionDAO;
3158 $params = array_merge($defaults, $params);
3159 $params['skipLineItem'] = TRUE;
3160 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3161 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3162 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3165 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3166 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3167 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3169 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3170 if (!empty($trxnId)) {
3171 $trxnId = $trxnId['trxn_id'];
3173 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3174 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3177 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3178 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3179 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3183 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3184 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3185 FROM civicrm_financial_trxn ft
3186 LEFT JOIN civicrm_entity_financial_trxn eft
3187 ON (ft.id = eft.financial_trxn_id)
3188 WHERE eft.entity_table = 'civicrm_contribution'
3189 AND eft.entity_id = {$contributionId}
3190 AND ft.to_financial_account_id != {$toFinancialAccount}
3191 AND ft.status_id = {$statusId}
3193 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3196 if ($contributionDAO->total_amount
== $sumOfPayments) {
3197 // update contribution status and
3198 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3199 $contributionDAO->contribution_status_id
= $statusId;
3200 $contributionDAO->cancel_date
= 'null';
3201 $contributionDAO->cancel_reason
= NULL;
3202 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3203 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3204 $contributionDAO->save();
3206 //Change status of financial record too
3207 $financialTrxn->status_id
= $statusId;
3208 $financialTrxn->save();
3210 // note : not using the self::add method,
3211 // the reason because it performs 'status change' related code execution for financial records
3212 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3213 // are coded below i.e. just updating financial_item status to 'Paid'
3215 if ($participantId) {
3216 // update participant status
3217 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3218 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3219 foreach ($ids as $val) {
3220 $participantUpdate['id'] = $val;
3221 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3222 CRM_Event_BAO_Participant
::add($participantUpdate);
3226 // update financial item statuses
3227 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3228 $paidStatus = array_search('Paid', $financialItemStatus);
3230 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3231 $sqlFinancialItemUpdate = "
3232 UPDATE civicrm_financial_item fi
3233 LEFT JOIN civicrm_entity_financial_trxn eft
3234 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3235 SET status_id = {$paidStatus}
3236 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3238 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3241 elseif ($paymentType == 'refund') {
3242 // build params for recording financial trxn entry
3243 $params['contribution'] = $contributionDAO;
3244 $params = array_merge($defaults, $params);
3245 $params['skipLineItem'] = TRUE;
3246 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3247 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3249 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3250 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3251 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3253 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3255 // note : not using the self::add method,
3256 // the reason because it performs 'status change' related code execution for financial records
3257 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3258 // are coded below i.e. just updating financial_item status to 'Paid'
3259 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3261 // add financial item entry
3262 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3263 $getLine['entity_id'] = $contributionDAO->id
;
3264 $getLine['entity_table'] = 'civicrm_contribution';
3265 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3266 if (!empty($lineItemId->id
)) {
3267 $addFinancialEntry = array(
3268 'transaction_date' => $financialTrxn->trxn_date
,
3269 'contact_id' => $contributionDAO->contact_id
,
3270 'amount' => $financialTrxn->total_amount
,
3271 'status_id' => array_search('Paid', $financialItemStatus),
3272 'entity_id' => $lineItemId->id
,
3273 'entity_table' => 'civicrm_line_item'
3275 $trxnIds['id'] = $financialTrxn->id
;
3276 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3278 if ($participantId) {
3279 // update participant status
3280 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3281 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3282 foreach ($ids as $val) {
3283 $participantUpdate['id'] = $val;
3284 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3285 CRM_Event_BAO_Participant
::add($participantUpdate);
3290 // activity creation
3291 if (!empty($financialTrxn)) {
3292 if ($participantId) {
3293 $inputParams['id'] = $participantId;
3296 $component = 'event';
3297 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3298 $entityObj = $entityObj[$participantId];
3300 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3302 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3304 return $financialTrxn;
3310 * @param $activityType
3312 * @param $contributionId
3314 * @throws CRM_Core_Exception
3316 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3317 if ($component == 'event') {
3318 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3319 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3320 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3321 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3322 $targetCid = $entityObj->contact_id
;
3323 // source record id would be the contribution id
3324 $srcRecId = $contributionId;
3328 $activityParams = array(
3329 'source_contact_id' => $targetCid,
3330 'source_record_id' => $srcRecId,
3331 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3335 'subject' => $subject,
3336 'activity_date_time' => $date,
3337 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3341 'skipRecentView' => TRUE,
3344 // create activity with target contacts
3345 $session = CRM_Core_Session
::singleton();
3346 $id = $session->get('userID');
3348 $activityParams['source_contact_id'] = $id;
3349 $activityParams['target_contact_id'][] = $targetCid;
3351 CRM_Activity_BAO_Activity
::create($activityParams);
3355 * function to get list of payments displayed by Contribute_Page_PaymentInfo
3359 * @param bool $getTrxnInfo
3360 * @param bool $usingLineTotal
3364 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3365 if ($component == 'event') {
3366 $entity = 'participant';
3367 $entityTable = 'civicrm_participant';
3368 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3370 if (!$contributionId) {
3371 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3372 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3373 $id = $primaryParticipantId;
3377 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3378 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3384 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3385 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3388 if (empty($total) ||
$usingLineTotal) {
3389 // for additional participants
3390 if ($entityTable == 'civicrm_participant') {
3391 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3393 foreach ($ids as $val) {
3394 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3398 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3402 $baseTrxnId = $total['trxn_id'];
3403 $total = $total['total_amount'];
3406 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3407 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3409 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3410 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3411 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3413 if ($paymentBalance == 0 && $contributionIsPayLater) {
3414 $paymentBalance = $total;
3417 $info['total'] = $total;
3418 $info['paid'] = $total - $paymentBalance;
3419 $info['balance'] = $paymentBalance;
3421 $info['component'] = $component;
3422 $info['payLater'] = $contributionIsPayLater;
3424 if ($getTrxnInfo && $baseTrxnId) {
3425 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3427 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3428 FROM civicrm_contribution con
3429 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3430 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3431 WHERE con.id = {$contributionId}
3434 // conditioned WHERE clause
3436 // if balance trxn exists don't include details of it in transaction info
3437 $sql .= " AND ft.id != {$baseTrxnId} ";
3439 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3441 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3442 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3443 while($resultDAO->fetch()) {
3444 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3445 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3447 'total_amount' => $resultDAO->total_amount
,
3448 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3449 'payment_instrument' => $paidByLabel,
3450 'receive_date' => $resultDAO->trxn_date
,
3451 'trxn_id' => $resultDAO->trxn_id
,
3452 'status' => $statuses[$resultDAO->status_id
],
3454 if ($paidByName == 'Check') {
3455 $val['check_number'] = $resultDAO->check_number
;
3459 $info['transaction'] = $rows;
3465 * Function to get financial account id has 'Sales Tax Account is'
3466 * account relationship with financial type
3468 * @param $financialTypeId
3470 * @return FinancialAccountId
3472 static function getFinancialAccountId($financialTypeId) {
3473 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3474 $searchParams = array(
3475 'entity_table' => 'civicrm_financial_type',
3476 'entity_id' => $financialTypeId,
3477 'account_relationship' => $accountRel,
3480 CRM_Financial_BAO_FinancialTypeAccount
::retrieve( $searchParams, $result );
3482 return CRM_Utils_Array
::value( 'financial_account_id', $result );
3485 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3486 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3488 // Update contribution
3489 if (!empty($params['id'])) {
3490 $id = $params['id'];
3491 $values = $ids = array();
3492 $contrbutionParams = array('id' => $id);
3493 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3495 // To assign pervious finantial type on update of contribution
3496 if (!isset($params['financial_type_id'])) {
3497 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3499 else if (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3500 // Assisn tax Amount on update of contrbution
3501 if (!empty($prevContributionValue->tax_amount
)) {
3502 $params['tax_amount'] = 'null';
3503 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3504 foreach ($params['line_item'] as $setID => $priceField) {
3505 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3506 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3513 // New Contrbution and update of contribution with tax rate financial type
3514 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3515 empty($params['skipLineItem']) && !$isLineItem)
3517 $taxRateParams = $taxRates[$params['financial_type_id']];
3518 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3519 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3521 // Get Line Item on update of contribution
3522 if (isset($params['id'])) {
3523 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3526 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3528 foreach ($params['line_item'] as $setID => $priceField) {
3529 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3530 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3533 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3535 else if (isset($params['api.line_item.create'])) {
3536 // Update total amount of contribution using lineItem
3537 $taxAmountArray = array();
3538 foreach ($params['api.line_item.create'] as $key => $value) {
3539 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3540 $taxRate = $taxRates[$value['financial_type_id']];
3541 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3542 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3545 $params['tax_amount'] = array_sum($taxAmountArray);
3546 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3549 // update line item of contrbution
3550 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3551 $taxRate = $taxRates[$params['financial_type_id']];
3552 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3553 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);