3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * Static field for all the contribution information that we can potentially import
43 static $_importableFields = NULL;
46 * Static field for all the contribution information that we can potentially export
51 static $_exportableFields = NULL;
54 * Field for all the objects related to this contribution
55 * @var array of objects (e.g membership object, participant object)
57 public $_relatedObjects = array();
60 * Field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
65 * @var string component or event
67 public $_component = NULL;
76 * @return \CRM_Contribute_DAO_Contribution
81 function __construct() {
82 parent
::__construct();
86 * Takes an associative array and creates a contribution object
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params (reference ) an assoc array of name/value pairs
93 * @param array $ids the array that holds all the db ids
95 * @return CRM_Contribute_BAO_Contribution object
99 static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
139 self
::calculateMissingAmountParams($params);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
174 $config = CRM_Core_Config
::singleton();
175 $contribution->currency
= $config->defaultCurrency
;
178 if ($contributionID && $setPrevContribution) {
179 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
182 $result = $contribution->save();
184 // Add financial_trxn details as part of fix for CRM-4724
185 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
186 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
188 //add Account details
189 $params['contribution'] = $contribution;
190 self
::recordFinancialAccounts($params);
192 // reset the group contact cache for this group
193 CRM_Contact_BAO_GroupContactCache
::remove();
195 if ($contributionID) {
196 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
199 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
206 * Get defaults for new entity
209 static function getDefaults() {
211 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
212 FALSE, FALSE, FALSE, 'AND is_default = 1')
214 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
219 * Given the list of params in the params array, fetch the object
220 * and store the values in the values array
222 * @param array $params input parameters to find object
223 * @param array $values output values of the object
224 * @param array $ids the array that holds all the db ids
226 * @return CRM_Contribute_BAO_Contribution|null the found object or null
230 static function &getValues($params, &$values, &$ids) {
231 if (empty($params)) {
234 $contribution = new CRM_Contribute_BAO_Contribution();
236 $contribution->copyValues($params);
238 if ($contribution->find(TRUE)) {
239 $ids['contribution'] = $contribution->id
;
241 CRM_Core_DAO
::storeValues($contribution, $values);
243 return $contribution;
245 $null = NULL; // return by reference
250 * @param array $params
254 public static function calculateMissingAmountParams(&$params) {
255 if (!isset($params['fee_amount'])) {
256 if (isset($params['total_amount']) && isset($params['net_amount'])) {
257 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
260 $params['fee_amount'] = 0;
263 if (!isset($params['net_amount'])) {
264 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
269 * Get the number of terms for this contribution for a given membership type
270 * based on querying the line item table and relevant price field values
271 * Note that any one contribution should only be able to have one line item relating to a particular membership
274 * @param int $membershipTypeID
276 * @param int $contributionID
280 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
281 $numTerms = CRM_Core_DAO
::singleValueQuery("
282 SELECT membership_num_terms FROM civicrm_line_item li
283 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
284 WHERE contribution_id = %1 AND membership_type_id = %2",
285 array(1 => array($contributionID, 'Integer') , 2 => array($membershipTypeID, 'Integer'))
287 // default of 1 is precautionary
288 return empty($numTerms) ?
1 : $numTerms;
292 * Takes an associative array and creates a contribution object
294 * @param array $params (reference ) an assoc array of name/value pairs
295 * @param array $ids the array that holds all the db ids
297 * @return CRM_Contribute_BAO_Contribution object
301 static function create(&$params, $ids = array()) {
302 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
303 foreach ($dateFields as $df) {
304 if (isset($params[$df])) {
305 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
309 $transaction = new CRM_Core_Transaction();
311 $contribution = self
::add($params, $ids);
313 if (is_a($contribution, 'CRM_Core_Error')) {
314 $transaction->rollback();
315 return $contribution;
318 $params['contribution_id'] = $contribution->id
;
320 if (!empty($params['custom']) &&
321 is_array($params['custom'])
323 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
326 $session = CRM_Core_Session
::singleton();
328 if (!empty($params['note'])) {
330 'entity_table' => 'civicrm_contribution',
331 'note' => $params['note'],
332 'entity_id' => $contribution->id
,
333 'contact_id' => $session->get('userID'),
334 'modified_date' => date('Ymd'),
336 if (!$noteParams['contact_id']) {
337 $noteParams['contact_id'] = $params['contact_id'];
339 CRM_Core_BAO_Note
::add($noteParams);
342 // make entry in batch entity batch table
343 if (!empty($params['batch_id'])) {
344 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
345 $titleFields = array(
351 $retrieveRequired = 0;
352 foreach ($titleFields as $titleField) {
353 if(!isset($contribution->$titleField)){
354 $retrieveRequired = 1;
358 if ($retrieveRequired == 1) {
359 $contribution->find(TRUE);
363 // check if activity record exist for this contribution, if
365 $activity = new CRM_Activity_DAO_Activity();
366 $activity->source_record_id
= $contribution->id
;
367 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
371 if (!$activity->find(TRUE)) {
372 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
375 // CRM-13237 : if activity record found, update it with campaign id of contribution
376 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
379 // Handle soft credit and / or link to personal campaign page
380 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
382 //Delete PCP against this contribution and create new on submitted PCP information
383 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
385 $deleteParams = array('id' => $pcpId);
386 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
388 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
389 $softParams = array();
390 $softParams['contribution_id'] = $contribution->id
;
391 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
392 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
393 $pcp['pcp_made_through_id'], 'contact_id'
395 $softParams['currency'] = $contribution->currency
;
396 $softParams['amount'] = $contribution->total_amount
;
397 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
398 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
399 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
400 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
401 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
403 if (isset($params['soft_credit'])) {
404 $softParams = $params['soft_credit'];
406 if (!empty($softIDs)) {
407 foreach ( $softIDs as $softID) {
408 if (!in_array($softID, $params['soft_credit_ids'])) {
409 $deleteParams = array('id' => $softID);
410 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
415 foreach ($softParams as $softParam) {
416 $softParam['contribution_id'] = $contribution->id
;
417 $softParam['currency'] = $contribution->currency
;
418 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
419 if (empty($softParam['amount'])) {
420 $softParam['amount'] = $contribution->total_amount
;
422 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
426 $transaction->commit();
428 // do not add to recent items for import, CRM-4399
429 if (empty($params['skipRecentView'])) {
430 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
431 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
433 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
434 $titleFields = array(
440 $retrieveRequired = 0;
441 foreach ($titleFields as $titleField) {
442 if(!isset($contribution->$titleField)){
443 $retrieveRequired = 1;
447 if($retrieveRequired == 1){
448 $contribution->find(TRUE);
450 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
451 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
453 $recentOther = array();
454 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
455 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
456 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
460 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
461 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
462 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
466 // add the recently created Contribution
467 CRM_Utils_Recent
::add($title,
471 $contribution->contact_id
,
477 return $contribution;
481 * Get the values for pseudoconstants for name->value and reverse.
483 * @param array $defaults (reference) the default values, some of which need to be resolved.
484 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
490 static function resolveDefaults(&$defaults, $reverse = FALSE) {
491 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
492 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
493 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
494 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
498 * This function is used to convert associative array names to values
501 * This function is used by both the web form layer and the api. Note that
502 * the api needs the name => value conversion, also the view layer typically
503 * requires value => name conversion
505 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
506 $id = $property . '_id';
508 $src = $reverse ?
$property : $id;
509 $dst = $reverse ?
$id : $property;
511 if (!array_key_exists($src, $defaults)) {
515 $look = $reverse ?
array_flip($lookup) : $lookup;
517 if (is_array($look)) {
518 if (!array_key_exists($defaults[$src], $look)) {
522 $defaults[$dst] = $look[$defaults[$src]];
527 * Takes a bunch of params that are needed to match certain criteria and
528 * retrieves the relevant objects. We'll tweak this function to be more
529 * full featured over a period of time. This is the inverse function of
530 * create. It also stores all the retrieved values in the default array
532 * @param array $params (reference ) an assoc array of name/value pairs
533 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
534 * in a hierarchical manner
535 * @param array $ids (reference) the array that holds all the db ids
537 * @return CRM_Contribute_BAO_Contribution object
541 static function retrieve(&$params, &$defaults, &$ids) {
542 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
543 return $contribution;
547 * Combine all the importable fields from the lower levels object
549 * The ordering is important, since currently we do not have a weight
550 * scheme. Adding weight is super important and should be done in the
551 * next week or so, before this can be called complete.
553 * @param string $contactType
554 * @param bool $status
556 * @return array array of importable Fields
560 static function &importableFields($contactType = 'Individual', $status = TRUE) {
561 if (!self
::$_importableFields) {
562 if (!self
::$_importableFields) {
563 self
::$_importableFields = array();
567 $fields = array('' => array('title' => ts('- do not import -')));
570 $fields = array('' => array('title' => ts('- Contribution Fields -')));
573 $note = CRM_Core_DAO_Note
::import();
574 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
575 unset($tmpFields['option_value']);
576 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
577 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
579 // Using new Dedupe rule.
581 'contact_type' => $contactType,
582 'used' => 'Unsupervised',
584 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
585 $tmpContactField = array();
586 if (is_array($fieldsArray)) {
587 foreach ($fieldsArray as $value) {
588 //skip if there is no dupe rule
589 if ($value == 'none') {
592 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
597 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
598 $tmpContactField[trim($value)] = $contactFields[trim($value)];
600 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
603 $title = $tmpContactField[trim($value)]['title'];
605 $tmpContactField[trim($value)]['title'] = $title;
609 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
610 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
611 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
612 $fields = array_merge($fields, $tmpContactField);
613 $fields = array_merge($fields, $tmpFields);
614 $fields = array_merge($fields, $note);
615 $fields = array_merge($fields, $optionFields);
616 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
617 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
618 self
::$_importableFields = $fields;
620 return self
::$_importableFields;
626 static function &exportableFields() {
627 if (!self
::$_exportableFields) {
628 if (!self
::$_exportableFields) {
629 self
::$_exportableFields = array();
632 $impFields = CRM_Contribute_DAO_Contribution
::export();
633 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
634 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
635 $typeField = CRM_Financial_DAO_FinancialType
::export();
636 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
637 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
638 $contributionStatus = array(
639 'contribution_status' => array(
640 'title' => ts('Contribution Status'),
641 'name' => 'contribution_status',
642 'data_type' => CRM_Utils_Type
::T_STRING
645 $contributionNote = array(
646 'contribution_note' =>
648 'title' => ts('Contribution Note'),
649 'name' => 'contribution_note',
650 'data_type' => CRM_Utils_Type
::T_TEXT
654 $contributionRecurId = array(
655 'contribution_recur_id' =>
657 'title' => ts('Recurring Contributions ID'),
658 'name' => 'contribution_recur_id',
659 'where' => 'civicrm_contribution.contribution_recur_id',
660 'data_type' => CRM_Utils_Type
::T_INT
663 $extraFields = array(
664 'contribution_batch' => array(
665 'title' => ts('Batch Name')
669 $softCreditFields = array(
670 'contribution_soft_credit_name' => array(
671 'name' => 'contribution_soft_credit_name',
672 'title' => 'Soft Credit For',
673 'where' => 'civicrm_contact_d.display_name',
674 'data_type' => CRM_Utils_Type
::T_STRING
676 'contribution_soft_credit_amount' => array(
677 'name' => 'contribution_soft_credit_amount',
678 'title' => 'Soft Credit Amount',
679 'where' => 'civicrm_contribution_soft.amount',
680 'data_type' => CRM_Utils_Type
::T_MONEY
682 'contribution_soft_credit_type' => array(
683 'name' => 'contribution_soft_credit_type',
684 'title' => 'Soft Credit Type',
685 'where' => 'contribution_softcredit_type.label',
686 'data_type' => CRM_Utils_Type
::T_STRING
688 'contribution_soft_credit_contribution_id' => array(
689 'name' => 'contribution_soft_credit_contribution_id',
690 'title' => 'Soft Credit For Contribution ID',
691 'where' => 'civicrm_contribution_soft.contribution_id',
692 'data_type' => CRM_Utils_Type
::T_INT
696 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
697 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
698 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
701 self
::$_exportableFields = $fields;
704 return self
::$_exportableFields;
708 * @param null $status
709 * @param null $startDate
710 * @param null $endDate
714 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
718 $where[] = 'contribution_status_id = 1';
722 $where[] = 'contribution_status_id = 3';
727 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
730 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
733 $whereCond = implode(' AND ', $where);
736 SELECT sum( total_amount ) as total_amount,
737 count( civicrm_contribution.id ) as total_count,
739 FROM civicrm_contribution
740 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
742 AND ( is_test = 0 OR is_test IS NULL )
743 AND contact.is_deleted = 0
747 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
750 while ($dao->fetch()) {
751 $count +
= $dao->total_count
;
752 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
755 return array('amount' => implode(', ', $amount),
763 * Delete the indirect records associated with this contribution first
767 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
770 static function deleteContribution($id) {
771 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
773 $transaction = new CRM_Core_Transaction();
776 //delete activity record
778 'source_record_id' => $id,
779 // activity type id for contribution
780 'activity_type_id' => 6,
783 CRM_Activity_BAO_Activity
::deleteActivity($params);
785 //delete billing address if exists for this contribution.
786 self
::deleteAddress($id);
788 //update pledge and pledge payment, CRM-3961
789 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
791 // remove entry from civicrm_price_set_entity, CRM-5095
792 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
793 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
795 // cleanup line items.
796 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
798 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
799 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
801 if ($participantId) {
802 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
805 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
809 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
810 $noteId = key($note);
812 CRM_Core_BAO_Note
::del($noteId, FALSE);
815 $dao = new CRM_Contribute_DAO_Contribution();
818 $results = $dao->delete();
820 $transaction->commit();
822 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
824 // delete the recently created Contribution
825 $contributionRecent = array(
827 'type' => 'Contribution',
829 CRM_Utils_Recent
::del($contributionRecent);
835 * Check if there is a contribution with the same trxn_id or invoice_id
837 * @param array $input an assoc array of name/value pairs
838 * @param array $duplicates (reference ) store ids of duplicate contribs
842 * @return boolean true if duplicate, false otherwise
846 static function checkDuplicate($input, &$duplicates, $id = NULL) {
848 $id = CRM_Utils_Array
::value('id', $input);
850 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
851 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
857 $clause[] = "trxn_id = %1";
858 $input[1] = array($trxn_id, 'String');
862 $clause[] = "invoice_id = %2";
863 $input[2] = array($invoice_id, 'String');
866 if (empty($clause)) {
870 $clause = implode(' OR ', $clause);
872 $clause = "( $clause ) AND id != %3";
873 $input[3] = array($id, 'Integer');
876 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
877 $dao = CRM_Core_DAO
::executeQuery($query, $input);
879 while ($dao->fetch()) {
880 $duplicates[] = $dao->id
;
887 * Takes an associative array and creates a contribution_product object
889 * the function extract all the params it needs to initialize the create a
890 * contribution_product object. the params array could contain additional unused name/value
893 * @param array $params (reference ) an assoc array of name/value pairs
895 * @return CRM_Contribute_BAO_ContributionProduct object
899 static function addPremium(&$params) {
900 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
901 $contributionProduct->copyValues($params);
902 return $contributionProduct->save();
906 * Get list of contribution fields for profile
907 * For now we only allow custom contribution fields to be in
910 * @param boolean $addExtraFields true if special fields needs to be added
912 * @return array the list of contribution fields
916 static function getContributionFields($addExtraFields = TRUE) {
917 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
918 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
920 if ($addExtraFields) {
921 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
924 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
926 foreach ($contributionFields as $key => $var) {
927 if ($key == 'contribution_contact_id') {
930 elseif ($key == 'contribution_campaign_id') {
931 $var['title'] = ts('Campaign');
933 $fields[$key] = $var;
936 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
941 * Add extra fields specific to contribtion
945 static function getSpecialContributionFields() {
946 $extraFields = array(
947 'contribution_soft_credit_name' => array(
948 'name' => 'contribution_soft_credit_name',
949 'title' => 'Soft Credit Name',
950 'headerPattern' => '/^soft_credit_name$/i',
951 'where' => 'civicrm_contact_d.display_name',
953 'contribution_soft_credit_email' => array(
954 'name' => 'contribution_soft_credit_email',
955 'title' => 'Soft Credit Email',
956 'headerPattern' => '/^soft_credit_email$/i',
957 'where' => 'soft_email.email',
959 'contribution_soft_credit_phone' => array(
960 'name' => 'contribution_soft_credit_phone',
961 'title' => 'Soft Credit Phone',
962 'headerPattern' => '/^soft_credit_phone$/i',
963 'where' => 'soft_phone.phone',
965 'contribution_soft_credit_contact_id' => array(
966 'name' => 'contribution_soft_credit_contact_id',
967 'title' => 'Soft Credit Contact ID',
968 'headerPattern' => '/^soft_credit_contact_id$/i',
969 'where' => 'civicrm_contribution_soft.contact_id',
981 static function getCurrentandGoalAmount($pageID) {
983 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
984 FROM civicrm_contribution_page p,
985 civicrm_contribution c
986 WHERE p.id = c.contribution_page_id
988 AND c.cancel_date is null
992 $config = CRM_Core_Config
::singleton();
993 $params = array(1 => array($pageID, 'Integer'));
994 $dao = CRM_Core_DAO
::executeQuery($query, $params);
997 return array($dao->goal
, $dao->total
);
1000 return array(NULL, NULL);
1005 * Get list of contribution In Honor of contact Ids
1007 * @param int $honorId In Honor of Contact ID
1009 * @return return the list of contribution fields
1014 static function getHonorContacts($honorId) {
1016 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1017 $honorDAO->contact_id
= $honorId;
1020 $type = CRM_Contribute_PseudoConstant
::financialType();
1022 while ($honorDAO->fetch()) {
1023 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1024 $contributionDAO->id
= $honorDAO->contribution_id
;
1026 if ($contributionDAO->find(TRUE)) {
1027 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1028 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1029 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1030 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1031 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1032 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1033 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1034 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1035 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1043 * Get the sort name of a contact for a particular contribution
1045 * @param int $id id of the contribution
1047 * @return null|string sort name of the contact if found
1051 static function sortName($id) {
1052 $id = CRM_Utils_Type
::escape($id, 'Integer');
1055 SELECT civicrm_contact.sort_name
1056 FROM civicrm_contribution, civicrm_contact
1057 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1058 AND civicrm_contribution.id = {$id}
1060 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1064 * @param int $contactID
1068 static function annual($contactID) {
1069 if (is_array($contactID)) {
1070 $contactIDs = implode(',', $contactID);
1073 $contactIDs = $contactID;
1076 $config = CRM_Core_Config
::singleton();
1077 $startDate = $endDate = NULL;
1079 $currentMonth = date('m');
1080 $currentDay = date('d');
1081 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1082 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1083 (int ) $config->fiscalYearStart
['d'] > $currentDay
1086 $year = date('Y') - 1;
1091 $nextYear = $year +
1;
1093 if ($config->fiscalYearStart
) {
1094 if ($config->fiscalYearStart
['M'] < 10) {
1095 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1097 if ($config->fiscalYearStart
['d'] < 10) {
1098 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1100 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1105 $startDate = "$year$monthDay";
1106 $endDate = "$nextYear$monthDay";
1109 SELECT count(*) as count,
1110 sum(total_amount) as amount,
1111 avg(total_amount) as average,
1113 FROM civicrm_contribution b
1114 WHERE b.contact_id IN ( $contactIDs )
1115 AND b.contribution_status_id = 1
1117 AND b.receive_date >= $startDate
1118 AND b.receive_date < $endDate
1121 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1123 $amount = $average = array();
1124 while ($dao->fetch()) {
1125 if ($dao->count
> 0 && $dao->amount
> 0) {
1126 $count +
= $dao->count
;
1127 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1128 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1134 implode(', ', $amount),
1135 implode(', ', $average),
1138 return array(0, 0, 0);
1142 * Check if there is a contribution with the params passed in.
1143 * Used for trxn_id,invoice_id and contribution_id
1145 * @param array $params an assoc array of name/value pairs
1147 * @return array contribution id if success else NULL
1151 static function checkDuplicateIds($params) {
1152 $dao = new CRM_Contribute_DAO_Contribution();
1156 foreach ($params as $k => $v) {
1158 $clause[] = "$k = '$v'";
1161 $clause = implode(' AND ', $clause);
1162 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1163 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1165 while ($dao->fetch()) {
1173 * Get the contribution details for component export
1175 * @param int $exportMode export mode
1176 * @param string $componentIds component ids
1178 * @return array associated array
1183 static function getContributionDetails($exportMode, $componentIds) {
1184 $paymentDetails = array();
1185 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1187 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1188 $componentSelect = " civicrm_participant_payment.participant_id id";
1189 $additionalClause = "
1190 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1191 AND civicrm_participant_payment.participant_id {$componentClause} )
1194 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1195 $componentSelect = " civicrm_membership_payment.membership_id id";
1196 $additionalClause = "
1197 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1198 AND civicrm_membership_payment.membership_id {$componentClause} )
1201 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1202 $componentSelect = " civicrm_pledge_payment.id id";
1203 $additionalClause = "
1204 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1205 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1209 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1210 trxn_id, {$componentSelect}
1211 FROM civicrm_contribution
1212 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1213 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1214 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1215 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1216 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1217 AND option_group_contribution_status.id = contribution_status.option_group_id )
1221 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1223 while ($dao->fetch()) {
1224 $paymentDetails[$dao->id
] = array(
1225 'total_amount' => $dao->total_amount
,
1226 'contribution_status' => $dao->status
,
1227 'receive_date' => $dao->receive_date
,
1228 'pay_instru' => $dao->payment_instrument
,
1229 'trxn_id' => $dao->trxn_id
,
1233 return $paymentDetails;
1237 * Create address associated with contribution record.
1239 * @param array $params an associated array
1240 * @param int $billingLocationTypeID
1242 * @return address id
1245 static function createAddress(&$params, $billingLocationTypeID) {
1246 $billingFields = array(
1249 'state_province_id',
1254 //build address array
1255 $addressParams = array();
1256 $addressParams['location_type_id'] = $billingLocationTypeID;
1257 $addressParams['is_billing'] = 1;
1259 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1260 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1261 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1262 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1264 foreach ($billingFields as $value) {
1265 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1268 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1270 return $address->id
;
1274 * Delete billing address record related contribution
1276 * @param int $contributionId
1277 * @param int $contactId
1282 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1284 $contactJoin = NULL;
1286 if ($contributionId) {
1287 $clauses[] = "cc.id = {$contributionId}";
1291 $clauses[] = "cco.id = {$contactId}";
1292 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1295 if (empty($clauses)) {
1296 CRM_Core_Error
::fatal();
1299 $condition = implode(' OR ', $clauses);
1303 FROM civicrm_address ca
1304 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1308 $dao = CRM_Core_DAO
::executeQuery($query);
1310 while ($dao->fetch()) {
1311 $params = array('id' => $dao->id
);
1312 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1317 * This function check online pending contribution associated w/
1318 * Online Event Registration or Online Membership signup.
1320 * @param int $componentId participant/membership id.
1321 * @param string $componentName Event/Membership.
1323 * @return $contributionId pending contribution id.
1326 static function checkOnlinePendingContribution($componentId, $componentName) {
1327 $contributionId = NULL;
1328 if (!$componentId ||
1329 !in_array($componentName, array('Event', 'Membership'))
1331 return $contributionId;
1334 if ($componentName == 'Event') {
1335 $idName = 'participant_id';
1336 $componentTable = 'civicrm_participant';
1337 $paymentTable = 'civicrm_participant_payment';
1338 $source = ts('Online Event Registration');
1341 if ($componentName == 'Membership') {
1342 $idName = 'membership_id';
1343 $componentTable = 'civicrm_membership';
1344 $paymentTable = 'civicrm_membership_payment';
1345 $source = ts('Online Contribution');
1348 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1351 SELECT component.id as {$idName},
1352 componentPayment.contribution_id as contribution_id,
1353 contribution.source source,
1354 contribution.contribution_status_id as contribution_status_id,
1355 contribution.is_pay_later as is_pay_later
1356 FROM $componentTable component
1357 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1358 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1359 WHERE component.id = {$componentId}";
1361 $dao = CRM_Core_DAO
::executeQuery($query);
1363 while ($dao->fetch()) {
1364 if ($dao->contribution_id
&&
1365 $dao->is_pay_later
&&
1366 $dao->contribution_status_id
== $pendingStatusId &&
1367 strpos($dao->source
, $source) !== FALSE
1369 $contributionId = $dao->contribution_id
;
1374 return $contributionId;
1378 * This function update contribution as well as related objects.
1380 static function transitionComponents($params, $processContributionObject = FALSE) {
1381 // get minimum required values.
1382 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1383 $componentId = CRM_Utils_Array
::value('component_id', $params);
1384 $componentName = CRM_Utils_Array
::value('componentName', $params);
1385 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1386 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1388 // if we already processed contribution object pass previous status id.
1389 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1391 $updateResult = array();
1393 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1395 // we process only ( Completed, Cancelled, or Failed ) contributions.
1396 if (!$contributionId ||
1397 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1398 array_search('Cancelled', $contributionStatuses),
1399 array_search('Failed', $contributionStatuses),
1402 return $updateResult;
1405 if (!$componentName ||
!$componentId) {
1406 // get the related component details.
1407 $componentDetails = self
::getComponentDetails($contributionId);
1410 $componentDetails['contact_id'] = $contactId;
1411 $componentDetails['component'] = $componentName;
1413 if ($componentName == 'event') {
1414 $componentDetails['participant'] = $componentId;
1417 $componentDetails['membership'] = $componentId;
1421 if (!empty($componentDetails['contact_id'])) {
1422 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1428 // do check for required ids.
1429 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1430 return $updateResult;
1433 //now we are ready w/ required ids, start processing.
1435 $baseIPN = new CRM_Core_Payment_BaseIPN();
1437 $input = $ids = $objects = array();
1439 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1440 $ids['contribution'] = $contributionId;
1441 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1442 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1443 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1444 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1445 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1446 $ids['contributionRecur'] = NULL;
1447 $ids['contributionPage'] = NULL;
1449 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1450 CRM_Core_Error
::fatal();
1453 $memberships = &$objects['membership'];
1454 $participant = &$objects['participant'];
1455 $pledgePayment = &$objects['pledge_payment'];
1456 $contribution = &$objects['contribution'];
1458 if ($pledgePayment) {
1459 $pledgePaymentIDs = array();
1460 foreach ($pledgePayment as $key => $object) {
1461 $pledgePaymentIDs[] = $object->id
;
1463 $pledgeID = $pledgePayment[0]->pledge_id
;
1466 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1469 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1470 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1475 // we might want to process contribution object.
1476 $processContribution = FALSE;
1477 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1478 if (is_array($memberships)) {
1479 foreach ($memberships as $membership) {
1481 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1482 $membership->save();
1484 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1485 if ($processContributionObject) {
1486 $processContribution = TRUE;
1493 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1494 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1496 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1497 if ($processContributionObject) {
1498 $processContribution = TRUE;
1502 if ($pledgePayment) {
1503 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1505 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1506 if ($processContributionObject) {
1507 $processContribution = TRUE;
1511 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1512 if (is_array($memberships)) {
1513 foreach ($memberships as $membership) {
1515 $membership->status_id
= array_search('Expired', $membershipStatuses);
1516 $membership->save();
1518 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1519 if ($processContributionObject) {
1520 $processContribution = TRUE;
1526 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1527 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1529 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1530 if ($processContributionObject) {
1531 $processContribution = TRUE;
1535 if ($pledgePayment) {
1536 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1538 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1539 if ($processContributionObject) {
1540 $processContribution = TRUE;
1544 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1546 // only pending contribution related object processed.
1547 if ($previousContriStatusId &&
1548 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1550 // this is case when we already processed contribution object.
1551 return $updateResult;
1553 elseif (!$previousContriStatusId &&
1554 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1556 // this is case when we are going to process contribution object later.
1557 return $updateResult;
1560 if (is_array($memberships)) {
1561 foreach ($memberships as $membership) {
1566 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1567 $membership->membership_type_id
,
1568 $membership->is_test
, $membership->id
1571 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1572 // this picks up membership type changes during renewals
1574 SELECT membership_type_id
1575 FROM civicrm_membership_log
1576 WHERE membership_id=$membership->id
1579 $dao = new CRM_Core_DAO
;
1581 if ($dao->fetch()) {
1582 if (!empty($dao->membership_type_id
)) {
1583 $membership->membership_type_id
= $dao->membership_type_id
;
1584 $membership->save();
1587 // else fall back to using current membership type
1590 // Figure out number of terms
1592 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1593 foreach ($lineitems as $lineitem) {
1594 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1595 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1597 // in case membership_num_terms comes through as null or zero
1598 $numterms = $numterms >= 1 ?
$numterms : 1;
1603 if ($currentMembership) {
1604 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1605 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1606 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1609 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1612 //get the status for membership.
1613 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1615 $dates['join_date'],
1618 $membership->membership_type_id
,
1622 $formattedParams = array(
1623 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1624 array_search('Current', $membershipStatuses)
1626 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1627 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1628 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1631 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1633 $membership->copyValues($formattedParams);
1634 $membership->save();
1636 //updating the membership log
1637 $membershipLog = array();
1638 $membershipLog = $formattedParams;
1639 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1640 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1642 $membershipLog['start_date'] = $logStartDate;
1643 $membershipLog['membership_id'] = $membership->id
;
1644 $membershipLog['modified_id'] = $membership->contact_id
;
1645 $membershipLog['modified_date'] = date('Ymd');
1646 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1648 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1650 //update related Memberships.
1651 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1653 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1656 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1657 if ($processContributionObject) {
1658 $processContribution = TRUE;
1661 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1667 $updatedStatusId = array_search('Registered', $participantStatuses);
1668 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1670 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1671 if ($processContributionObject) {
1672 $processContribution = TRUE;
1676 if ($pledgePayment) {
1677 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1679 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1680 if ($processContributionObject) {
1681 $processContribution = TRUE;
1686 // process contribution object.
1687 if ($processContribution) {
1688 $contributionParams = array();
1690 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1691 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1692 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1694 foreach ($fields as $field) {
1695 if (empty($params[$field])) {
1698 $contributionParams[$field] = $params[$field];
1701 $ids = array('contribution' => $contributionId);
1702 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1705 return $updateResult;
1709 * This function returns all contribution related object ids.
1711 public static function getComponentDetails($contributionId) {
1712 $componentDetails = $pledgePayment = array();
1713 if (!$contributionId) {
1714 return $componentDetails;
1718 SELECT c.id as contribution_id,
1719 c.contact_id as contact_id,
1720 mp.membership_id as membership_id,
1721 m.membership_type_id as membership_type_id,
1722 pp.participant_id as participant_id,
1723 p.event_id as event_id,
1724 pgp.id as pledge_payment_id
1725 FROM civicrm_contribution c
1726 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1727 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1728 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1729 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1730 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1731 WHERE c.id = $contributionId";
1733 $dao = CRM_Core_DAO
::executeQuery($query);
1734 $componentDetails = array();
1736 while ($dao->fetch()) {
1737 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1738 $componentDetails['contact_id'] = $dao->contact_id
;
1739 if ($dao->event_id
) {
1740 $componentDetails['event'] = $dao->event_id
;
1742 if ($dao->participant_id
) {
1743 $componentDetails['participant'] = $dao->participant_id
;
1745 if ($dao->membership_id
) {
1746 if (!isset($componentDetails['membership'])) {
1747 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1749 $componentDetails['membership'][] = $dao->membership_id
;
1750 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1752 if ($dao->pledge_payment_id
) {
1753 $pledgePayment[] = $dao->pledge_payment_id
;
1757 if ($pledgePayment) {
1758 $componentDetails['pledge_payment'] = $pledgePayment;
1761 return $componentDetails;
1765 * @param int $contactId
1766 * @param bool $includeSoftCredit
1768 * @return null|string
1770 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1775 $contactContributionsSQL = "
1776 SELECT contribution.id AS id
1777 FROM civicrm_contribution contribution
1778 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1780 $contactSoftCreditContributionsSQL = "
1781 SELECT contribution.id
1782 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1783 ON ( contribution.id = softContribution.contribution_id )
1784 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1785 $query = "SELECT count( x.id ) count FROM ( ";
1786 $query .= $contactContributionsSQL;
1788 if ($includeSoftCredit) {
1789 $query .= " UNION ";
1790 $query .= $contactSoftCreditContributionsSQL;
1795 return CRM_Core_DAO
::singleValueQuery($query);
1799 * Get individual id for onbehalf contribution
1801 * @param int $contributionId contribution id
1802 * @param int $contributorId contributor id
1804 * @return array $ids containing organization id and individual id
1807 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1811 if (!$contributionId) {
1815 // fetch contributor id if null
1816 if (!$contributorId) {
1817 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1818 $contributionId, 'contact_id'
1822 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1823 $activityTypeId = array_search('Contribution', $activityTypeIds);
1825 if ($activityTypeId && $contributorId) {
1827 SELECT civicrm_activity_contact.contact_id
1828 FROM civicrm_activity_contact
1829 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1830 WHERE civicrm_activity.activity_type_id = %1
1831 AND civicrm_activity.source_record_id = %2
1832 AND civicrm_activity_contact.record_type_id = %3
1835 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1836 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1839 1 => array($activityTypeId, 'Integer'),
1840 2 => array($contributionId, 'Integer'),
1841 3 => array($sourceID, 'Integer'),
1844 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1846 // for on behalf contribution source is individual and contributor is organization
1847 if ($sourceContactId && $sourceContactId != $contributorId) {
1848 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1849 // get rel type id for employee of relation
1850 foreach ($relationshipTypeIds as $id => $typeVals) {
1851 if ($typeVals['name_a_b'] == 'Employee of') {
1852 $relationshipTypeId = $id;
1857 $rel = new CRM_Contact_DAO_Relationship();
1858 $rel->relationship_type_id
= $relationshipTypeId;
1859 $rel->contact_id_a
= $sourceContactId;
1860 $rel->contact_id_b
= $contributorId;
1861 if ($rel->find(TRUE)) {
1862 $ids['individual_id'] = $rel->contact_id_a
;
1863 $ids['organization_id'] = $rel->contact_id_b
;
1875 static function getContributionDates() {
1876 $config = CRM_Core_Config
::singleton();
1877 $currentMonth = date('m');
1878 $currentDay = date('d');
1879 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1880 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1881 (int ) $config->fiscalYearStart
['d'] > $currentDay
1884 $year = date('Y') - 1;
1889 $year = array('Y' => $year);
1890 $yearDate = $config->fiscalYearStart
;
1891 $yearDate = array_merge($year, $yearDate);
1892 $yearDate = CRM_Utils_Date
::format($yearDate);
1894 $monthDate = date('Ym') . '01';
1900 'yearDate' => $yearDate,
1901 'monthDate' => $monthDate,
1906 * Load objects relations to contribution object
1907 * Objects are stored in the $_relatedObjects property
1908 * In the first instance we are just moving functionality from BASEIpn -
1909 * see http://issues.civicrm.org/jira/browse/CRM-9996
1911 * @param array $input Input as delivered from Payment Processor
1912 * @param array $ids Ids as Loaded by Payment Processor
1913 * @param boolean $required Is Payment processor / contribution page required
1914 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1915 * Note that the unit test for the BaseIPN class tests this function
1920 * @param bool $required
1921 * @param bool $loadAll
1926 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1928 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1929 if(empty($ids['contact']) && isset($this->contact_id
)){
1930 $ids['contact'] = $this->contact_id
;
1933 if (empty($this->_component
)) {
1934 if (! empty($ids['event'])) {
1935 $this->_component
= 'event';
1938 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1941 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1942 $contributionType = new CRM_Financial_BAO_FinancialType();
1943 $contributionType->id
= $this->financial_type_id
;
1944 if (!$contributionType->find(TRUE)) {
1945 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1947 if (!empty($ids['contact'])) {
1948 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1949 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1950 $this->_relatedObjects
['contact']->find(TRUE);
1952 $this->_relatedObjects
['contributionType'] = $contributionType;
1954 if ($this->_component
== 'contribute') {
1955 // retrieve the other optional objects first so
1956 // stuff down the line can use this info and do things
1958 //in any case get the memberships associated with the contribution
1959 //because we now support multiple memberships w/ price set
1960 // see if there are any other memberships to be considered for same contribution.
1962 SELECT membership_id
1963 FROM civicrm_membership_payment
1964 WHERE contribution_id = %1 ";
1965 $params = array(1 => array($this->id
, 'Integer'));
1967 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1968 while ($dao->fetch()) {
1969 if ($dao->membership_id
) {
1970 if (!is_array($ids['membership'])) {
1971 $ids['membership'] = array();
1973 $ids['membership'][] = $dao->membership_id
;
1977 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1978 foreach ($ids['membership'] as $id) {
1980 $membership = new CRM_Member_BAO_Membership();
1981 $membership->id
= $id;
1982 if (!$membership->find(TRUE)) {
1983 throw new Exception("Could not find membership record: $id");
1985 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1986 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1987 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1988 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1989 $membership->free();
1994 if (!empty($ids['pledge_payment'])) {
1996 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1997 if (empty($paymentID)) {
2000 $payment = new CRM_Pledge_BAO_PledgePayment();
2001 $payment->id
= $paymentID;
2002 if (!$payment->find(TRUE)) {
2003 throw new Exception("Could not find pledge payment record: " . $paymentID);
2005 $this->_relatedObjects
['pledge_payment'][] = $payment;
2009 if (!empty($ids['contributionRecur'])) {
2010 $recur = new CRM_Contribute_BAO_ContributionRecur();
2011 $recur->id
= $ids['contributionRecur'];
2012 if (!$recur->find(TRUE)) {
2013 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2015 $this->_relatedObjects
['contributionRecur'] = &$recur;
2016 //get payment processor id from recur object.
2017 $paymentProcessorID = $recur->payment_processor_id
;
2019 //for normal contribution get the payment processor id.
2020 if (!$paymentProcessorID) {
2021 if ($this->contribution_page_id
) {
2022 // get the payment processor id from contribution page
2023 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2024 $this->contribution_page_id
,
2028 //fail to load payment processor id.
2029 elseif (empty($ids['pledge_payment'])) {
2030 $loadObjectSuccess = TRUE;
2032 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2034 return $loadObjectSuccess;
2039 // we are in event mode
2040 // make sure event exists and is valid
2041 $event = new CRM_Event_BAO_Event();
2042 $event->id
= $ids['event'];
2043 if ($ids['event'] &&
2046 throw new Exception("Could not find event: " . $ids['event']);
2049 $this->_relatedObjects
['event'] = &$event;
2051 $participant = new CRM_Event_BAO_Participant();
2052 $participant->id
= $ids['participant'];
2053 if ($ids['participant'] &&
2054 !$participant->find(TRUE)
2056 throw new Exception("Could not find participant: " . $ids['participant']);
2058 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2060 $this->_relatedObjects
['participant'] = &$participant;
2062 if (!$paymentProcessorID) {
2063 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2067 if ($paymentProcessorID) {
2068 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2069 $this->is_test ?
'test' : 'live'
2071 $ids['paymentProcessor'] = $paymentProcessorID;
2072 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2074 elseif ($required) {
2075 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2082 * Create array of message information - ie. return html version, txt version, to field
2084 * @param array $input incoming information
2085 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2086 * just check presence of recur object but maintaining legacy approach
2088 * @param array $ids IDs of related objects
2089 * @param array $values any values that may have already been compiled by calling process
2090 * This is augmented by values 'gathered' by gatherMessageValues
2091 * @param bool $returnMessageText distinguishes between whether to send message or return
2092 * message text. We are working towards this function ALWAYS returning message text & calling
2093 * function doing emails / pdfs with it
2094 * @return array $messageArray - messages
2100 * @param bool $recur
2101 * @param bool $returnMessageText
2105 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2106 if (empty($this->_relatedObjects
)) {
2107 $this->loadRelatedObjects($input, $ids);
2109 if (empty($this->_component
)) {
2110 $this->_component
= CRM_Utils_Array
::value('component', $input);
2113 //not really sure what params might be passed in but lets merge em into values
2114 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2115 $template = CRM_Core_Smarty
::singleton();
2116 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2117 //what does recur 'mean here - to do with payment processor return functionality but
2118 // what is the importance
2119 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2120 $paymentObject = &CRM_Core_Payment
::singleton(
2121 $this->is_test ?
'test' : 'live',
2122 $this->_relatedObjects
['paymentProcessor']
2125 $entityID = $entity = NULL;
2126 if (isset($ids['contribution'])) {
2127 $entity = 'contribution';
2128 $entityID = $ids['contribution'];
2130 if (!empty($ids['membership'])) {
2131 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2132 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2133 // line having loaded an array
2134 $ids['membership'] = (array) $ids['membership'];
2135 $entity = 'membership';
2136 $entityID = $ids['membership'][0];
2139 $url = $paymentObject->subscriptionURL($entityID, $entity);
2140 $template->assign('cancelSubscriptionUrl', $url);
2142 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2143 $template->assign('updateSubscriptionBillingUrl', $url);
2145 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2146 $template->assign('updateSubscriptionUrl', $url);
2148 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2149 //direct mode showing billing block, so use directIPN for temporary
2150 $template->assign('contributeMode', 'directIPN');
2153 // todo remove strtolower - check consistency
2154 if (strtolower($this->_component
) == 'event') {
2155 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2156 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2160 $values['contribution_id'] = $this->id
;
2161 if (!empty($ids['related_contact'])) {
2162 $values['related_contact'] = $ids['related_contact'];
2163 if (isset($ids['onbehalf_dupe_alert'])) {
2164 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2166 $entityBlock = array(
2167 'contact_id' => $ids['contact'],
2168 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2169 'Home', 'id', 'name'
2172 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2173 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2176 if ($this->is_test
) {
2179 if (!empty($this->_relatedObjects
['membership'])) {
2180 foreach ($this->_relatedObjects
['membership'] as $membership) {
2181 if ($membership->id
) {
2182 $values['isMembership'] = TRUE;
2184 // need to set the membership values here
2185 $template->assign('membership_assign', 1);
2186 $template->assign('membership_name',
2187 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2189 $template->assign('mem_start_date', $membership->start_date
);
2190 $template->assign('mem_join_date', $membership->join_date
);
2191 $template->assign('mem_end_date', $membership->end_date
);
2192 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2193 $template->assign('mem_status', $membership_status);
2194 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2195 $template->assign('is_pay_later', 1);
2198 // if separate payment there are two contributions recorded and the
2199 // admin will need to send a receipt for each of them separately.
2200 // we dont link the two in the db (but can potentially infer it if needed)
2201 $template->assign('is_separate_payment', 0);
2203 if ($recur && $paymentObject) {
2204 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2205 $template->assign('cancelSubscriptionUrl', $url);
2206 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2207 $template->assign('updateSubscriptionBillingUrl', $url);
2208 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2209 $template->assign('updateSubscriptionUrl', $url);
2212 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2215 // otherwise if its about sending emails, continue sending without return, as we
2216 // don't want to exit the loop.
2221 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2227 * Gather values for contribution mail - this function has been created
2228 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2229 * Values related to the contribution in question are gathered
2231 * @param array $input input into function (probably from payment processor)
2232 * @param array $ids the set of ids related to the inpurt
2234 * @return array $values
2236 * NB don't add direct calls to the function as we intend to change the signature
2245 function _gatherMessageValues($input, &$values, $ids = array()) {
2246 // set display address of contributor
2247 if ($this->address_id
) {
2248 $addressParams = array('id' => $this->address_id
);
2249 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2250 $addressDetails = array_values($addressDetails);
2251 $values['address'] = $addressDetails[0]['display'];
2253 if ($this->_component
== 'contribute') {
2254 if (isset($this->contribution_page_id
)) {
2255 CRM_Contribute_BAO_ContributionPage
::setValues(
2256 $this->contribution_page_id
,
2259 if ($this->contribution_page_id
) {
2260 // CRM-8254 - override default currency if applicable
2261 $config = CRM_Core_Config
::singleton();
2262 $config->defaultCurrency
= CRM_Utils_Array
::value(
2265 $config->defaultCurrency
2269 // no contribution page -probably back office
2271 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2272 $values['is_email_receipt'] = 1;
2273 $values['title'] = 'Contribution';
2275 // set lineItem for contribution
2277 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2278 if (!empty($lineItem)) {
2279 $itemId = key($lineItem);
2280 foreach ($lineItem as &$eachItem) {
2281 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2282 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2283 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2284 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2287 $values['lineItem'][0] = $lineItem;
2288 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2292 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2296 // if this is onbehalf of contribution then set related contact
2297 if (!empty($relatedContact['individual_id'])) {
2298 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2303 $eventParams = array(
2304 'id' => $this->_relatedObjects
['event']->id
,
2306 $values['event'] = array();
2308 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2310 //get location details
2311 $locationParams = array(
2312 'entity_id' => $this->_relatedObjects
['event']->id
,
2313 'entity_table' => 'civicrm_event',
2315 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2317 $ufJoinParams = array(
2318 'entity_table' => 'civicrm_event',
2319 'entity_id' => $ids['event'],
2320 'module' => 'CiviEvent',
2323 list($custom_pre_id,
2325 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2327 $values['custom_pre_id'] = $custom_pre_id;
2328 $values['custom_post_id'] = $custom_post_ids;
2330 // set lineItem for event contribution
2332 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2333 if (!empty($participantIds)) {
2334 foreach ($participantIds as $pIDs) {
2335 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2336 if (!CRM_Utils_System
::isNull($lineItem)) {
2337 $values['lineItem'][] = $lineItem;
2348 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2349 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2350 * Note we send directly from this function in some cases because it is only partly refactored
2351 * Don't call this function directly as the signature will change
2355 * @param $template CRM_Core_SMARTY
2356 * @param bool $recur
2357 * @param bool $returnMessageText
2361 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2362 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2363 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2364 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2365 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2366 $template->assign('useForMember', true);
2368 //assign honor information to receipt message
2369 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2371 if (isset($softRecord['soft_credit'])) {
2372 //if id of contribution page is present
2373 if (!empty($values['id'])) {
2374 $values['honor'] = array(
2375 'honor_profile_values' => array(),
2376 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2377 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2379 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2381 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2382 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2385 //offline contribution
2386 $softCreditTypes = $softCredits = array();
2387 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2388 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2389 $softCredits[$key] = array(
2390 'Name' => $softCredit['contact_name'],
2391 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2394 $template->assign('softCreditTypes', $softCreditTypes);
2395 $template->assign('softCredits', $softCredits);
2399 $dao = new CRM_Contribute_DAO_ContributionProduct();
2400 $dao->contribution_id
= $this->id
;
2401 if ($dao->find(TRUE)) {
2402 $premiumId = $dao->product_id
;
2403 $template->assign('option', $dao->product_option
);
2405 $productDAO = new CRM_Contribute_DAO_Product();
2406 $productDAO->id
= $premiumId;
2407 $productDAO->find(TRUE);
2408 $template->assign('selectPremium', TRUE);
2409 $template->assign('product_name', $productDAO->name
);
2410 $template->assign('price', $productDAO->price
);
2411 $template->assign('sku', $productDAO->sku
);
2413 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2414 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2415 if(empty($amount) && isset($this->total_amount
)){
2416 $amount = $this->total_amount
;
2418 $template->assign('amount', $amount);
2419 // add the new contribution values
2420 if (strtolower($this->_component
) == 'contribute') {
2422 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2423 $softDAO->contribution_id
= $this->id
;
2424 if ($softDAO->find(TRUE)) {
2425 $template->assign('pcpBlock', TRUE);
2426 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2427 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2428 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2430 //assign the pcp page title for email subject
2431 $pcpDAO = new CRM_PCP_DAO_PCP();
2432 $pcpDAO->id
= $softDAO->pcp_id
;
2433 if ($pcpDAO->find(TRUE)) {
2434 $template->assign('title', $pcpDAO->title
);
2439 if ($this->financial_type_id
) {
2440 $values['financial_type_id'] = $this->financial_type_id
;
2444 $template->assign('trxn_id', $this->trxn_id
);
2445 $template->assign('receive_date',
2446 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2448 $template->assign('contributeMode', 'notify');
2449 $template->assign('action', $this->is_test ?
1024 : 1);
2450 $template->assign('receipt_text',
2451 CRM_Utils_Array
::value('receipt_text',
2455 $template->assign('is_monetary', 1);
2456 $template->assign('is_recur', (bool) $recur);
2457 $template->assign('currency', $this->currency
);
2458 $template->assign('address', CRM_Utils_Address
::format($input));
2459 if ($this->_component
== 'event') {
2460 $template->assign('title', $values['event']['title']);
2461 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2462 $viewRoles = array();
2463 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2464 $viewRoles[] = $participantRoles[$v];
2466 $values['event']['participant_role'] = implode(', ', $viewRoles);
2467 $template->assign('event', $values['event']);
2468 $template->assign('location', $values['location']);
2469 $template->assign('customPre', $values['custom_pre_id']);
2470 $template->assign('customPost', $values['custom_post_id']);
2473 if ($this->_relatedObjects
['participant']->is_test
) {
2477 $values['params'] = array();
2478 //to get email of primary participant.
2479 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2480 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2481 //build an array of cId/pId of participants
2482 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2483 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2484 //send receipt to additional participant if exists
2485 if (count($additionalIDs)) {
2486 $template->assign('isPrimary', 0);
2487 $template->assign('customProfile', NULL);
2488 //set additionalParticipant true
2489 $values['params']['additionalParticipant'] = TRUE;
2490 foreach ($additionalIDs as $pId => $cId) {
2492 //to change the status pending to completed
2493 $additional = new CRM_Event_DAO_Participant();
2494 $additional->id
= $pId;
2495 $additional->contact_id
= $cId;
2496 $additional->find(TRUE);
2497 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2498 $additional->status_id
= 1;
2499 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2500 //if additional participant dont have email
2502 if (!$additionalParticipantInfo) {
2503 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2505 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2506 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2507 $additional->save();
2508 $additional->free();
2509 $template->assign('amount', $amount);
2510 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2514 //build an array of custom profile and assigning it to template
2515 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2517 if (count($customProfile)) {
2518 $template->assign('customProfile', $customProfile);
2521 // for primary contact
2522 $values['params']['additionalParticipant'] = FALSE;
2523 $template->assign('isPrimary', 1);
2524 $template->assign('amount', $primaryAmount);
2525 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2526 if ($this->payment_instrument_id
) {
2527 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2528 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2530 // carry paylater, since we did not created billing,
2531 // so need to pull email from primary location, CRM-4395
2532 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2538 * Check whether payment processor supports
2539 * cancellation of contribution subscription
2541 * @param int $contributionId contribution id
2543 * @param bool $isNotCancelled
2549 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2550 $cacheKeyString = "$contributionId";
2551 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2553 static $supportsCancel = array();
2555 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2556 $supportsCancel[$cacheKeyString] = FALSE;
2557 $isCancelled = FALSE;
2559 if ($isNotCancelled) {
2560 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2563 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2564 if (!empty($paymentObject)) {
2565 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2568 return $supportsCancel[$cacheKeyString];
2572 * Check whether subscription is already cancelled
2574 * @param int $contributionId contribution id
2576 * @return string $status contribution status
2580 static function isSubscriptionCancelled($contributionId) {
2582 SELECT cr.contribution_status_id
2583 FROM civicrm_contribution_recur cr
2584 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2585 WHERE con.id = %1 LIMIT 1";
2586 $params = array(1 => array($contributionId, 'Integer'));
2587 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2588 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2589 if ($status == 'Cancelled') {
2596 * Create all financial accounts entry
2598 * @param array $params contribution object, line item array and params for trxn
2601 * @param array $financialTrxnValues
2603 * @return null|object
2607 static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2608 $skipRecords = $update = $return = $isRelatedId = FALSE;
2610 $additionalParticipantId = array();
2611 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2613 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2614 $entityId = $params['participant_id'];
2615 $entityTable = 'civicrm_participant';
2616 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2618 elseif (!empty($params['membership_id'])) {
2619 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2620 // are created off one contribution should be handled elsewhere
2621 $entityId = $params['membership_id'];
2622 $entityTable = 'civicrm_membership';
2625 $entityId = $params['contribution']->id
;
2626 $entityTable = 'civicrm_contribution';
2629 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2630 $isRelatedId = TRUE;
2633 $entityID[] = $entityId;
2634 if (!empty($additionalParticipantId)) {
2635 $entityID +
= $additionalParticipantId;
2637 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2638 if (empty($params['prevContribution'])) {
2645 $statusId = $params['contribution']->contribution_status_id
;
2646 // CRM-13964 partial payment
2647 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2648 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2649 $partialAmtPay = $params['partial_amount_pay'];
2650 $partialAmtTotal = $params['partial_payment_total'];
2652 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2653 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2654 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2655 $params['total_amount'] = $partialAmtPay;
2657 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2658 if (empty($balanceTrxnInfo['trxn_id'])) {
2659 // create new balance transaction record
2660 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2661 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2663 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2664 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2665 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2666 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2667 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2668 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2669 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2670 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2671 $balanceTrxnParams['status_id'] = $statusId;
2672 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2673 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2674 if (!empty($params['payment_processor'])) {
2675 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2677 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2681 // build line item array if its not set in $params
2682 if (empty($params['line_item']) ||
$additionalParticipantId) {
2683 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2686 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2687 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2688 $skipRecords = TRUE;
2689 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2690 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2691 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2692 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2694 elseif (!empty($params['payment_processor'])) {
2695 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2697 elseif (!empty($params['payment_instrument_id'])) {
2698 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2701 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2702 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2703 $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);
2706 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2707 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2708 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2711 //build financial transaction params
2712 $trxnParams = array(
2713 'contribution_id' => $params['contribution']->id
,
2714 'to_financial_account_id' => $params['to_financial_account_id'],
2715 'trxn_date' => date('YmdHis'),
2716 'total_amount' => $totalAmount,
2717 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2718 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2719 'currency' => $params['contribution']->currency
,
2720 'trxn_id' => $params['contribution']->trxn_id
,
2721 'status_id' => $statusId,
2722 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2723 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2726 if (!empty($params['payment_processor'])) {
2727 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2730 if (isset($fromFinancialAccountId)) {
2731 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2734 // consider external values passed for recording transaction entry
2735 if (!empty($financialTrxnValues)) {
2736 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2739 $params['trxnParams'] = $trxnParams;
2741 if (!empty($params['prevContribution'])) {
2742 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2743 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2744 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2745 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2746 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2749 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2750 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2751 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))) {
2752 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2753 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2756 //if financial type is changed
2757 if (!empty($params['financial_type_id']) &&
2758 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2759 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2760 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2761 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2762 if ($oldFinancialAccount != $newFinancialAccount) {
2763 $params['total_amount'] = 0;
2764 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2765 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2766 $params['prevContribution']->financial_type_id
, $relationTypeId);
2769 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2770 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2771 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2774 self
::updateFinancialAccounts($params, 'changeFinancialType');
2775 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2776 $params['financial_account_id'] = $newFinancialAccount;
2777 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2778 self
::updateFinancialAccounts($params);
2779 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2783 //Update contribution status
2784 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2785 if (!empty($params['contribution_status_id']) &&
2786 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2787 //Update Financial Records
2788 self
::updateFinancialAccounts($params, 'changedStatus');
2791 // change Payment Instrument for a Completed contribution
2792 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2793 // instrument is null and now new payment instrument is added along with the payment
2794 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2795 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2796 if (array_key_exists('payment_instrument_id', $params)) {
2797 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2798 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2799 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2800 //check if status is changed from Pending to Completed
2801 // do not update payment instrument changes for Pending to Completed
2802 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2803 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2804 // for all other statuses create new financial records
2805 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2806 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2807 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2810 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2811 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2812 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2813 // for any other payment instrument changes create new financial records
2814 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2815 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2816 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2818 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2819 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2820 // another special case when check number is changed, create new financial records
2821 // create financial trxn with negative amount
2822 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2823 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2824 // create financial trxn with positive amount
2825 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2826 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2827 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2831 //if Change contribution amount
2832 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2833 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2834 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2835 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2836 if (isset($totalAmount) &&
2837 $totalAmount != $params['prevContribution']->total_amount
) {
2838 //Update Financial Records
2839 $params['trxnParams']['from_financial_account_id'] = NULL;
2840 self
::updateFinancialAccounts($params, 'changedAmount');
2845 // records finanical trxn and entity financial trxn
2846 // also make it available as return value
2847 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2848 $params['entity_id'] = $financialTxn->id
;
2851 // record line items and finacial items
2852 if (empty($params['skipLineItem'])) {
2853 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2856 // create batch entry if batch_id is passed
2857 if (!empty($params['batch_id'])) {
2858 $entityParams = array(
2859 'batch_id' => $params['batch_id'],
2860 'entity_table' => 'civicrm_financial_trxn',
2861 'entity_id' => $financialTxn->id
,
2863 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2866 // when a fee is charged
2867 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2868 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2871 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2872 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2873 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2874 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2875 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2877 unset($params['line_item']);
2883 * Update all financial accounts entry
2885 * @param array $params contribution object, line item array and params for trxn
2887 * @param string $context update scenarios
2889 * @param null $skipTrxn
2894 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2895 $itemAmount = $trxnID = NULL;
2896 //get all the statuses
2897 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2898 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2899 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2900 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2901 && $context == 'changePaymentInstrument') {
2904 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2905 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2907 if ($context == 'changedStatus') {
2908 //get all the statuses
2909 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2911 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2912 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2913 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2914 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2916 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2917 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2918 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2919 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2920 $params['trxnParams']['to_financial_account_id'] = NULL;
2921 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2923 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2924 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2925 $financialTypeID, $relationTypeId);
2927 $itemAmount = $params['trxnParams']['total_amount'];
2929 elseif ($context == 'changePaymentInstrument') {
2930 if ($params['trxnParams']['total_amount'] < 0) {
2931 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2932 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2933 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2934 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2938 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2939 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2942 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2943 $params['entity_id'] = $trxn->id
;
2945 if ($context == 'changedStatus') {
2946 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2947 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2948 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2949 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2950 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2952 $entityParams = array(
2953 'entity_table' => 'civicrm_financial_item',
2954 'financial_trxn_id' => $trxn->id
,
2956 if (empty($params['line_item'])) {
2958 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
2959 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
2960 // & this can be removed
2963 foreach ($params['line_item'] as $fieldId => $fields) {
2964 foreach ($fields as $fieldValueId => $fieldValues) {
2966 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2967 2 => array($fieldValues['id'], 'Integer'),
2969 CRM_Core_DAO
::executeQuery($query, $fparams);
2971 1 => array($fieldValues['id'], 'Integer'),
2973 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2974 while ($financialItem->fetch()) {
2975 $entityParams['entity_id'] = $financialItem->id
;
2976 $entityParams['amount'] = $financialItem->amount
;
2977 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2984 if ($context != 'changePaymentInstrument') {
2985 $itemParams['entity_table'] = 'civicrm_line_item';
2986 $trxnIds['id'] = $params['entity_id'];
2987 foreach ($params['line_item'] as $fieldId => $fields) {
2988 foreach ($fields as $fieldValueId => $fieldValues) {
2989 $prevParams['entity_id'] = $fieldValues['id'];
2990 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2992 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2993 if ($params['contribution']->receive_date
) {
2994 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2997 $financialAccount = $prevfinancialItem->financial_account_id
;
2998 if (!empty($params['financial_account_id'])) {
2999 $financialAccount = $params['financial_account_id'];
3002 $currency = $params['prevContribution']->currency
;
3003 if ($params['contribution']->currency
) {
3004 $currency = $params['contribution']->currency
;
3007 if (!empty($params['is_quick_config'])) {
3008 $amount = $itemAmount;
3010 $amount = $params['total_amount'];
3014 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3015 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)) {
3018 $amount = $diff * $fieldValues['line_total'];
3021 $itemParams = array(
3022 'transaction_date' => $receiveDate,
3023 'contact_id' => $params['prevContribution']->contact_id
,
3024 'currency' => $currency,
3025 'amount' => $amount,
3026 'description' => $prevfinancialItem->description
,
3027 'status_id' => $prevfinancialItem->status_id
,
3028 'financial_account_id' => $financialAccount,
3029 'entity_table' => 'civicrm_line_item',
3030 'entity_id' => $fieldValues['id']
3032 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3034 if ($fieldValues['tax_amount']) {
3035 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3036 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3037 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3038 $itemParams['description'] = $taxTerm;
3039 if ($fieldValues['financial_type_id']) {
3040 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3042 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3050 * Check status validation on update of a contribution
3052 * @param array $values previous form values before submit
3054 * @param array $fields the input form values
3056 * @param array $errors list of errors
3062 static function checkStatusValidation($values, &$fields, &$errors) {
3063 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3064 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3065 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3069 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3070 $checkStatus = array(
3071 'Cancelled' => array('Completed', 'Refunded'),
3072 'Completed' => array('Cancelled', 'Refunded'),
3073 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3074 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3075 'Refunded' => array('Cancelled', 'Completed')
3078 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3079 $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']]));
3084 * Delete contribution of contact
3088 * @param integer $contactId contact id
3093 static function deleteContactContribution($contactId) {
3094 $contribution = new CRM_Contribute_DAO_Contribution();
3095 $contribution->contact_id
= $contactId;
3096 $contribution->find();
3097 while ($contribution->fetch()) {
3098 self
::deleteContribution($contribution->id
);
3103 * Get options for a given contribution field.
3104 * @see CRM_Core_DAO::buildOptions
3106 * @param String $fieldName
3107 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3108 * @param Array $props : whatever is known about this dao object
3110 * @return Array|bool
3112 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3113 $className = __CLASS__
;
3115 switch ($fieldName) {
3116 // This field is not part of this object but the api supports it
3117 case 'payment_processor':
3118 $className = 'CRM_Contribute_BAO_ContributionPage';
3119 // Filter results by contribution page
3120 if (!empty($props['contribution_page_id'])) {
3121 $page = civicrm_api('contribution_page', 'getsingle', array(
3123 'id' => ($props['contribution_page_id'])
3125 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3126 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3129 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3130 case 'honor_type_id':
3131 $className = 'CRM_Contribute_BAO_ContributionSoft';
3132 $fieldName = 'soft_credit_type_id';
3133 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3136 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3140 * Validate financial type
3144 * @param integer $financialTypeId Financial Type id
3146 * @param string $relationName
3148 * @return array|bool
3152 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3153 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3154 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3156 if (!$financialAccount) {
3157 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3164 * Function to record additional payment for partial and refund contributions
3166 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3167 * @param array $trxnData : to take user provided input of transaction details.
3168 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3171 * @param int $contributionId
3173 * @param string $paymentType
3174 * @param int $participantId
3176 * @return null|object
3178 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3179 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3180 $getInfoOf['id'] = $contributionId;
3181 $defaults = array();
3182 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3184 if ($paymentType == 'owed') {
3185 // build params for recording financial trxn entry
3186 $params['contribution'] = $contributionDAO;
3187 $params = array_merge($defaults, $params);
3188 $params['skipLineItem'] = TRUE;
3189 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3190 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3191 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3194 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3195 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3196 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3198 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3199 if (!empty($trxnId)) {
3200 $trxnId = $trxnId['trxn_id'];
3202 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3203 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3206 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3207 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3208 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3212 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3213 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3214 FROM civicrm_financial_trxn ft
3215 LEFT JOIN civicrm_entity_financial_trxn eft
3216 ON (ft.id = eft.financial_trxn_id)
3217 WHERE eft.entity_table = 'civicrm_contribution'
3218 AND eft.entity_id = {$contributionId}
3219 AND ft.to_financial_account_id != {$toFinancialAccount}
3220 AND ft.status_id = {$statusId}
3222 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3225 if ($contributionDAO->total_amount
== $sumOfPayments) {
3226 // update contribution status and
3227 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3228 $contributionDAO->contribution_status_id
= $statusId;
3229 $contributionDAO->cancel_date
= 'null';
3230 $contributionDAO->cancel_reason
= NULL;
3231 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3232 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3233 $contributionDAO->save();
3235 //Change status of financial record too
3236 $financialTrxn->status_id
= $statusId;
3237 $financialTrxn->save();
3239 // note : not using the self::add method,
3240 // the reason because it performs 'status change' related code execution for financial records
3241 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3242 // are coded below i.e. just updating financial_item status to 'Paid'
3244 if ($participantId) {
3245 // update participant status
3246 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3247 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3248 foreach ($ids as $val) {
3249 $participantUpdate['id'] = $val;
3250 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3251 CRM_Event_BAO_Participant
::add($participantUpdate);
3255 // update financial item statuses
3256 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3257 $paidStatus = array_search('Paid', $financialItemStatus);
3259 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3260 $sqlFinancialItemUpdate = "
3261 UPDATE civicrm_financial_item fi
3262 LEFT JOIN civicrm_entity_financial_trxn eft
3263 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3264 SET status_id = {$paidStatus}
3265 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3267 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3270 elseif ($paymentType == 'refund') {
3271 // build params for recording financial trxn entry
3272 $params['contribution'] = $contributionDAO;
3273 $params = array_merge($defaults, $params);
3274 $params['skipLineItem'] = TRUE;
3275 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3276 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3278 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3279 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3280 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3282 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3284 // note : not using the self::add method,
3285 // the reason because it performs 'status change' related code execution for financial records
3286 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3287 // are coded below i.e. just updating financial_item status to 'Paid'
3288 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3290 // add financial item entry
3291 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3292 $getLine['entity_id'] = $contributionDAO->id
;
3293 $getLine['entity_table'] = 'civicrm_contribution';
3294 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3295 if (!empty($lineItemId->id
)) {
3296 $addFinancialEntry = array(
3297 'transaction_date' => $financialTrxn->trxn_date
,
3298 'contact_id' => $contributionDAO->contact_id
,
3299 'amount' => $financialTrxn->total_amount
,
3300 'status_id' => array_search('Paid', $financialItemStatus),
3301 'entity_id' => $lineItemId->id
,
3302 'entity_table' => 'civicrm_line_item'
3304 $trxnIds['id'] = $financialTrxn->id
;
3305 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3307 if ($participantId) {
3308 // update participant status
3309 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3310 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3311 foreach ($ids as $val) {
3312 $participantUpdate['id'] = $val;
3313 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3314 CRM_Event_BAO_Participant
::add($participantUpdate);
3319 // activity creation
3320 if (!empty($financialTrxn)) {
3321 if ($participantId) {
3322 $inputParams['id'] = $participantId;
3325 $component = 'event';
3326 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3327 $entityObj = $entityObj[$participantId];
3329 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3331 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3333 return $financialTrxn;
3339 * @param $activityType
3341 * @param int $contributionId
3343 * @throws CRM_Core_Exception
3345 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3346 if ($component == 'event') {
3347 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3348 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3349 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3350 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3351 $targetCid = $entityObj->contact_id
;
3352 // source record id would be the contribution id
3353 $srcRecId = $contributionId;
3357 $activityParams = array(
3358 'source_contact_id' => $targetCid,
3359 'source_record_id' => $srcRecId,
3360 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3364 'subject' => $subject,
3365 'activity_date_time' => $date,
3366 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3370 'skipRecentView' => TRUE,
3373 // create activity with target contacts
3374 $session = CRM_Core_Session
::singleton();
3375 $id = $session->get('userID');
3377 $activityParams['source_contact_id'] = $id;
3378 $activityParams['target_contact_id'][] = $targetCid;
3380 CRM_Activity_BAO_Activity
::create($activityParams);
3384 * Get list of payments displayed by Contribute_Page_PaymentInfo
3388 * @param bool $getTrxnInfo
3389 * @param bool $usingLineTotal
3393 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3394 if ($component == 'event') {
3395 $entity = 'participant';
3396 $entityTable = 'civicrm_participant';
3397 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3399 if (!$contributionId) {
3400 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3401 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3402 $id = $primaryParticipantId;
3404 if (!$contributionId) {
3409 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3410 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3416 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3417 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3420 if (empty($total) ||
$usingLineTotal) {
3421 // for additional participants
3422 if ($entityTable == 'civicrm_participant') {
3423 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3425 foreach ($ids as $val) {
3426 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3430 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3434 $baseTrxnId = $total['trxn_id'];
3435 $total = $total['total_amount'];
3438 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3439 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3441 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3442 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3443 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3445 if ($paymentBalance == 0 && $contributionIsPayLater) {
3446 $paymentBalance = $total;
3449 $info['total'] = $total;
3450 $info['paid'] = $total - $paymentBalance;
3451 $info['balance'] = $paymentBalance;
3453 $info['component'] = $component;
3454 $info['payLater'] = $contributionIsPayLater;
3456 if ($getTrxnInfo && $baseTrxnId) {
3457 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3459 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3460 FROM civicrm_contribution con
3461 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3462 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3463 WHERE con.id = {$contributionId}
3466 // conditioned WHERE clause
3468 // if balance trxn exists don't include details of it in transaction info
3469 $sql .= " AND ft.id != {$baseTrxnId} ";
3471 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3473 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3474 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3475 while($resultDAO->fetch()) {
3476 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3477 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3479 'total_amount' => $resultDAO->total_amount
,
3480 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3481 'payment_instrument' => $paidByLabel,
3482 'receive_date' => $resultDAO->trxn_date
,
3483 'trxn_id' => $resultDAO->trxn_id
,
3484 'status' => $statuses[$resultDAO->status_id
],
3486 if ($paidByName == 'Check') {
3487 $val['check_number'] = $resultDAO->check_number
;
3491 $info['transaction'] = $rows;
3497 * Get financial account id has 'Sales Tax Account is'
3498 * account relationship with financial type
3500 * @param int $financialTypeId
3502 * @return FinancialAccountId
3504 static function getFinancialAccountId($financialTypeId) {
3505 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3506 $searchParams = array(
3507 'entity_table' => 'civicrm_financial_type',
3508 'entity_id' => $financialTypeId,
3509 'account_relationship' => $accountRel,
3512 CRM_Financial_BAO_FinancialTypeAccount
::retrieve( $searchParams, $result );
3514 return CRM_Utils_Array
::value( 'financial_account_id', $result );
3517 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3518 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3520 // Update contribution
3521 if (!empty($params['id'])) {
3522 $id = $params['id'];
3523 $values = $ids = array();
3524 $contrbutionParams = array('id' => $id);
3525 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3527 // To assign pervious finantial type on update of contribution
3528 if (!isset($params['financial_type_id'])) {
3529 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3531 else if (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3532 // Assisn tax Amount on update of contrbution
3533 if (!empty($prevContributionValue->tax_amount
)) {
3534 $params['tax_amount'] = 'null';
3535 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3536 foreach ($params['line_item'] as $setID => $priceField) {
3537 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3538 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3545 // New Contrbution and update of contribution with tax rate financial type
3546 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3547 empty($params['skipLineItem']) && !$isLineItem)
3549 $taxRateParams = $taxRates[$params['financial_type_id']];
3550 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3551 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3553 // Get Line Item on update of contribution
3554 if (isset($params['id'])) {
3555 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3558 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3560 foreach ($params['line_item'] as $setID => $priceField) {
3561 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3562 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3565 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3567 else if (isset($params['api.line_item.create'])) {
3568 // Update total amount of contribution using lineItem
3569 $taxAmountArray = array();
3570 foreach ($params['api.line_item.create'] as $key => $value) {
3571 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3572 $taxRate = $taxRates[$value['financial_type_id']];
3573 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3574 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3577 $params['tax_amount'] = array_sum($taxAmountArray);
3578 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3581 // update line item of contrbution
3582 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3583 $taxRate = $taxRates[$params['financial_type_id']];
3584 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3585 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);