3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * Static field for all the contribution information that we can potentially import
42 static $_importableFields = NULL;
45 * Static field for all the contribution information that we can potentially export
49 static $_exportableFields = NULL;
52 * Field for all the objects related to this contribution
53 * @var array of objects (e.g membership object, participant object)
55 public $_relatedObjects = array();
58 * Field for the component - either 'event' (participant) or 'contribute'
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
63 * @var string component or event
65 public $_component = NULL;
68 * Possibly obsolete variable.
70 * If you use it please explain why it is set in the create function here.
74 public $trxn_result_code;
79 * @return \CRM_Contribute_DAO_Contribution
83 public function __construct() {
84 parent
::__construct();
88 * Takes an associative array and creates a contribution object.
90 * the function extract all the params it needs to initialize the create a
91 * contribution object. the params array could contain additional unused name/value
94 * @param array $params
95 * (reference ) an assoc array of name/value pairs.
97 * The array that holds all the db ids.
99 * @return CRM_Contribute_BAO_Contribution|void
101 public static function add(&$params, $ids = array()) {
102 if (empty($params)) {
105 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
106 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
107 $duplicates = array();
108 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
109 $error = CRM_Core_Error
::singleton();
110 $d = implode(', ', $duplicates);
111 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
114 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
119 // first clean up all the money fields
120 $moneyFields = array(
124 'non_deductible_amount',
127 //if priceset is used, no need to cleanup money
128 if (!empty($params['skipCleanMoney'])) {
129 unset($moneyFields[0]);
132 foreach ($moneyFields as $field) {
133 if (isset($params[$field])) {
134 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
138 //set defaults in create mode
139 if (!$contributionID) {
140 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
141 self
::calculateMissingAmountParams($params);
144 if (!empty($params['payment_instrument_id'])) {
145 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
146 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
147 $params['check_number'] = 'null';
151 $setPrevContribution = TRUE;
152 // CRM-13964 partial payment
153 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
154 $partialAmtTotal = $params['partial_payment_total'];
155 $partialAmtPay = $params['partial_amount_pay'];
156 $params['total_amount'] = $partialAmtTotal;
157 if ($partialAmtPay < $partialAmtTotal) {
158 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
159 $params['is_pay_later'] = 0;
160 $setPrevContribution = FALSE;
164 if ($contributionID) {
165 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
168 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
170 $contribution = new CRM_Contribute_BAO_Contribution();
171 $contribution->copyValues($params);
173 $contribution->id
= $contributionID;
175 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
176 $config = CRM_Core_Config
::singleton();
177 $contribution->currency
= $config->defaultCurrency
;
180 if ($contributionID && $setPrevContribution) {
181 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
184 $result = $contribution->save();
186 // Add financial_trxn details as part of fix for CRM-4724
187 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
188 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
190 //add Account details
191 $params['contribution'] = $contribution;
192 self
::recordFinancialAccounts($params);
194 // reset the group contact cache for this group
195 CRM_Contact_BAO_GroupContactCache
::remove();
197 if ($contributionID) {
198 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
201 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
208 * Get defaults for new entity.
211 public static function getDefaults() {
213 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
214 FALSE, FALSE, FALSE, 'AND is_default = 1')
216 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
221 * Given the list of params in the params array, fetch the object
222 * and store the values in the values array
224 * @param array $params
225 * Input parameters to find object.
226 * @param array $values
227 * Output values of the object.
229 * The array that holds all the db ids.
231 * @return CRM_Contribute_BAO_Contribution|null the found object or null
233 public static function &getValues($params, &$values, &$ids) {
234 if (empty($params)) {
237 $contribution = new CRM_Contribute_BAO_Contribution();
239 $contribution->copyValues($params);
241 if ($contribution->find(TRUE)) {
242 $ids['contribution'] = $contribution->id
;
244 CRM_Core_DAO
::storeValues($contribution, $values);
246 return $contribution;
248 $null = NULL; // return by reference
253 * Calculate net_amount & fee_amount if they are not set.
255 * Net amount should be total - fee.
256 * This should only be called for new contributions.
258 * @param array $params
259 * Params for a new contribution before they are saved.
261 public static function calculateMissingAmountParams(&$params) {
262 if (!isset($params['fee_amount'])) {
263 if (isset($params['total_amount']) && isset($params['net_amount'])) {
264 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
267 $params['fee_amount'] = 0;
270 if (!isset($params['net_amount'])) {
271 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
276 * Get the number of terms for this contribution for a given membership type
277 * based on querying the line item table and relevant price field values
278 * Note that any one contribution should only be able to have one line item relating to a particular membership
281 * @param int $membershipTypeID
283 * @param int $contributionID
287 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
288 $numTerms = CRM_Core_DAO
::singleValueQuery("
289 SELECT membership_num_terms FROM civicrm_line_item li
290 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
291 WHERE contribution_id = %1 AND membership_type_id = %2",
292 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
294 // default of 1 is precautionary
295 return empty($numTerms) ?
1 : $numTerms;
299 * Takes an associative array and creates a contribution object.
301 * @param array $params
302 * (reference ) an assoc array of name/value pairs.
304 * The array that holds all the db ids.
306 * @return CRM_Contribute_BAO_Contribution
308 public static function create(&$params, $ids = array()) {
309 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
310 foreach ($dateFields as $df) {
311 if (isset($params[$df])) {
312 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
316 $transaction = new CRM_Core_Transaction();
318 $contribution = self
::add($params, $ids);
320 if (is_a($contribution, 'CRM_Core_Error')) {
321 $transaction->rollback();
322 return $contribution;
325 $params['contribution_id'] = $contribution->id
;
327 if (!empty($params['custom']) &&
328 is_array($params['custom'])
330 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
333 $session = CRM_Core_Session
::singleton();
335 if (!empty($params['note'])) {
337 'entity_table' => 'civicrm_contribution',
338 'note' => $params['note'],
339 'entity_id' => $contribution->id
,
340 'contact_id' => $session->get('userID'),
341 'modified_date' => date('Ymd'),
343 if (!$noteParams['contact_id']) {
344 $noteParams['contact_id'] = $params['contact_id'];
346 CRM_Core_BAO_Note
::add($noteParams);
349 // make entry in batch entity batch table
350 if (!empty($params['batch_id'])) {
351 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
352 $titleFields = array(
358 $retrieveRequired = 0;
359 foreach ($titleFields as $titleField) {
360 if (!isset($contribution->$titleField)) {
361 $retrieveRequired = 1;
365 if ($retrieveRequired == 1) {
366 $contribution->find(TRUE);
370 // check if activity record exist for this contribution, if
372 $activity = new CRM_Activity_DAO_Activity();
373 $activity->source_record_id
= $contribution->id
;
374 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
378 if (!$activity->find(TRUE)) {
379 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
382 // CRM-13237 : if activity record found, update it with campaign id of contribution
383 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
386 // Handle soft credit and / or link to personal campaign page
387 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
389 //Delete PCP against this contribution and create new on submitted PCP information
390 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
392 $deleteParams = array('id' => $pcpId);
393 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
395 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
396 $softParams = array();
397 $softParams['contribution_id'] = $contribution->id
;
398 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
399 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
400 $pcp['pcp_made_through_id'], 'contact_id'
402 $softParams['currency'] = $contribution->currency
;
403 $softParams['amount'] = $contribution->total_amount
;
404 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
405 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
406 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
407 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
408 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
409 //Send notification to owner for PCP
410 if ($contributionSoft->pcp_id
) {
411 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
414 if (isset($params['soft_credit'])) {
415 $softParams = $params['soft_credit'];
417 if (!empty($softIDs)) {
418 foreach ($softIDs as $softID) {
419 if (!in_array($softID, $params['soft_credit_ids'])) {
420 $deleteParams = array('id' => $softID);
421 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
426 foreach ($softParams as $softParam) {
427 $softParam['contribution_id'] = $contribution->id
;
428 $softParam['currency'] = $contribution->currency
;
429 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
430 if (empty($softParam['amount'])) {
431 $softParam['amount'] = $contribution->total_amount
;
433 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
437 $transaction->commit();
439 // do not add to recent items for import, CRM-4399
440 if (empty($params['skipRecentView'])) {
441 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
442 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
444 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
445 $titleFields = array(
451 $retrieveRequired = 0;
452 foreach ($titleFields as $titleField) {
453 if (!isset($contribution->$titleField)) {
454 $retrieveRequired = 1;
458 if ($retrieveRequired == 1) {
459 $contribution->find(TRUE);
461 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
462 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
464 $recentOther = array();
465 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
466 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
467 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
471 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
472 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
473 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
477 // add the recently created Contribution
478 CRM_Utils_Recent
::add($title,
482 $contribution->contact_id
,
488 return $contribution;
492 * Get the values for pseudoconstants for name->value and reverse.
494 * @param array $defaults
495 * (reference) the default values, some of which need to be resolved.
496 * @param bool $reverse
497 * True if we want to resolve the values in the reverse direction (value -> name).
501 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
502 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
503 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
504 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
505 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
509 * Convert associative array names to values and vice-versa.
511 * This function is used by both the web form layer and the api. Note that
512 * the api needs the name => value conversion, also the view layer typically
513 * requires value => name conversion
515 * @param array $defaults
516 * @param string $property
517 * @param array $lookup
518 * @param bool $reverse
522 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
523 $id = $property . '_id';
525 $src = $reverse ?
$property : $id;
526 $dst = $reverse ?
$id : $property;
528 if (!array_key_exists($src, $defaults)) {
532 $look = $reverse ?
array_flip($lookup) : $lookup;
534 if (is_array($look)) {
535 if (!array_key_exists($defaults[$src], $look)) {
539 $defaults[$dst] = $look[$defaults[$src]];
544 * Retrieve DB object based on input parameters.
546 * It also stores all the retrieved values in the default array.
548 * @param array $params
549 * (reference ) an assoc array of name/value pairs.
550 * @param array $defaults
551 * (reference ) an assoc array to hold the name / value pairs.
552 * in a hierarchical manner
554 * (reference) the array that holds all the db ids.
556 * @return CRM_Contribute_BAO_Contribution
558 public static function retrieve(&$params, &$defaults, &$ids) {
559 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
560 return $contribution;
564 * Combine all the importable fields from the lower levels object.
566 * The ordering is important, since currently we do not have a weight
567 * scheme. Adding weight is super important and should be done in the
568 * next week or so, before this can be called complete.
570 * @param string $contactType
571 * @param bool $status
574 * array of importable Fields
576 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
577 if (!self
::$_importableFields) {
578 if (!self
::$_importableFields) {
579 self
::$_importableFields = array();
583 $fields = array('' => array('title' => ts('- do not import -')));
586 $fields = array('' => array('title' => ts('- Contribution Fields -')));
589 $note = CRM_Core_DAO_Note
::import();
590 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
591 unset($tmpFields['option_value']);
592 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
593 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
595 // Using new Dedupe rule.
597 'contact_type' => $contactType,
598 'used' => 'Unsupervised',
600 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
601 $tmpContactField = array();
602 if (is_array($fieldsArray)) {
603 foreach ($fieldsArray as $value) {
604 //skip if there is no dupe rule
605 if ($value == 'none') {
608 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
613 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
614 $tmpContactField[trim($value)] = $contactFields[trim($value)];
616 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
619 $title = $tmpContactField[trim($value)]['title'];
621 $tmpContactField[trim($value)]['title'] = $title;
625 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
626 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
627 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
628 $fields = array_merge($fields, $tmpContactField);
629 $fields = array_merge($fields, $tmpFields);
630 $fields = array_merge($fields, $note);
631 $fields = array_merge($fields, $optionFields);
632 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
633 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
634 self
::$_importableFields = $fields;
636 return self
::$_importableFields;
642 public static function &exportableFields() {
643 if (!self
::$_exportableFields) {
644 if (!self
::$_exportableFields) {
645 self
::$_exportableFields = array();
648 $impFields = CRM_Contribute_DAO_Contribution
::export();
649 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
650 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
651 $typeField = CRM_Financial_DAO_FinancialType
::export();
652 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
653 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
654 $contributionStatus = array(
655 'contribution_status' => array(
656 'title' => ts('Contribution Status'),
657 'name' => 'contribution_status',
658 'data_type' => CRM_Utils_Type
::T_STRING
,
662 $contributionPage = array(
663 'contribution_page' => array(
664 'title' => ts('Contribution Page'),
665 'name' => 'contribution_page',
666 'where' => 'civicrm_contribution_page.title',
667 'data_type' => CRM_Utils_Type
::T_STRING
,
671 $contributionNote = array(
672 'contribution_note' => array(
673 'title' => ts('Contribution Note'),
674 'name' => 'contribution_note',
675 'data_type' => CRM_Utils_Type
::T_TEXT
,
679 $contributionRecurId = array(
680 'contribution_recur_id' => array(
681 'title' => ts('Recurring Contributions ID'),
682 'name' => 'contribution_recur_id',
683 'where' => 'civicrm_contribution.contribution_recur_id',
684 'data_type' => CRM_Utils_Type
::T_INT
,
688 $extraFields = array(
689 'contribution_batch' => array(
690 'title' => ts('Batch Name'),
694 $softCreditFields = array(
695 'contribution_soft_credit_name' => array(
696 'name' => 'contribution_soft_credit_name',
697 'title' => 'Soft Credit For',
698 'where' => 'civicrm_contact_d.display_name',
699 'data_type' => CRM_Utils_Type
::T_STRING
,
701 'contribution_soft_credit_amount' => array(
702 'name' => 'contribution_soft_credit_amount',
703 'title' => 'Soft Credit Amount',
704 'where' => 'civicrm_contribution_soft.amount',
705 'data_type' => CRM_Utils_Type
::T_MONEY
,
707 'contribution_soft_credit_type' => array(
708 'name' => 'contribution_soft_credit_type',
709 'title' => 'Soft Credit Type',
710 'where' => 'contribution_softcredit_type.label',
711 'data_type' => CRM_Utils_Type
::T_STRING
,
713 'contribution_soft_credit_contribution_id' => array(
714 'name' => 'contribution_soft_credit_contribution_id',
715 'title' => 'Soft Credit For Contribution ID',
716 'where' => 'civicrm_contribution_soft.contribution_id',
717 'data_type' => CRM_Utils_Type
::T_INT
,
721 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
722 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
723 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
726 self
::$_exportableFields = $fields;
729 return self
::$_exportableFields;
733 * @param null $status
734 * @param null $startDate
735 * @param null $endDate
739 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
743 $where[] = 'contribution_status_id = 1';
747 $where[] = 'contribution_status_id = 3';
752 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
755 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
758 $whereCond = implode(' AND ', $where);
761 SELECT sum( total_amount ) as total_amount,
762 count( civicrm_contribution.id ) as total_count,
764 FROM civicrm_contribution
765 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
767 AND ( is_test = 0 OR is_test IS NULL )
768 AND contact.is_deleted = 0
772 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
775 while ($dao->fetch()) {
776 $count +
= $dao->total_count
;
777 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
781 'amount' => implode(', ', $amount),
789 * Delete the indirect records associated with this contribution first.
794 * $results no of deleted Contribution on success, false otherwise
796 public static function deleteContribution($id) {
797 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
799 $transaction = new CRM_Core_Transaction();
802 //delete activity record
804 'source_record_id' => $id,
805 // activity type id for contribution
806 'activity_type_id' => 6,
809 CRM_Activity_BAO_Activity
::deleteActivity($params);
811 //delete billing address if exists for this contribution.
812 self
::deleteAddress($id);
814 //update pledge and pledge payment, CRM-3961
815 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
817 // remove entry from civicrm_price_set_entity, CRM-5095
818 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
819 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
821 // cleanup line items.
822 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
824 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
825 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
827 if ($participantId) {
828 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
831 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
835 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
836 $noteId = key($note);
838 CRM_Core_BAO_Note
::del($noteId, FALSE);
841 $dao = new CRM_Contribute_DAO_Contribution();
844 $results = $dao->delete();
846 $transaction->commit();
848 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
850 // delete the recently created Contribution
851 $contributionRecent = array(
853 'type' => 'Contribution',
855 CRM_Utils_Recent
::del($contributionRecent);
861 * Check if there is a contribution with the same trxn_id or invoice_id.
863 * @param array $input
864 * An assoc array of name/value pairs.
865 * @param array $duplicates
866 * (reference) store ids of duplicate contribs.
870 * true if duplicate, false otherwise
872 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
874 $id = CRM_Utils_Array
::value('id', $input);
876 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
877 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
883 $clause[] = "trxn_id = %1";
884 $input[1] = array($trxn_id, 'String');
888 $clause[] = "invoice_id = %2";
889 $input[2] = array($invoice_id, 'String');
892 if (empty($clause)) {
896 $clause = implode(' OR ', $clause);
898 $clause = "( $clause ) AND id != %3";
899 $input[3] = array($id, 'Integer');
902 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
903 $dao = CRM_Core_DAO
::executeQuery($query, $input);
905 while ($dao->fetch()) {
906 $duplicates[] = $dao->id
;
913 * Takes an associative array and creates a contribution_product object.
915 * the function extract all the params it needs to initialize the create a
916 * contribution_product object. the params array could contain additional unused name/value
919 * @param array $params
920 * (reference) an assoc array of name/value pairs.
922 * @return CRM_Contribute_DAO_ContributionProduct
924 public static function addPremium(&$params) {
925 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
926 $contributionProduct->copyValues($params);
927 return $contributionProduct->save();
931 * Get list of contribution fields for profile.
932 * For now we only allow custom contribution fields to be in
935 * @param bool $addExtraFields
936 * True if special fields needs to be added.
939 * the list of contribution fields
941 public static function getContributionFields($addExtraFields = TRUE) {
942 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
943 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
945 if ($addExtraFields) {
946 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
949 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
951 foreach ($contributionFields as $key => $var) {
952 if ($key == 'contribution_contact_id') {
955 elseif ($key == 'contribution_campaign_id') {
956 $var['title'] = ts('Campaign');
958 $fields[$key] = $var;
961 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
966 * Add extra fields specific to contribution.
968 public static function getSpecialContributionFields() {
969 $extraFields = array(
970 'contribution_soft_credit_name' => array(
971 'name' => 'contribution_soft_credit_name',
972 'title' => 'Soft Credit Name',
973 'headerPattern' => '/^soft_credit_name$/i',
974 'where' => 'civicrm_contact_d.display_name',
976 'contribution_soft_credit_email' => array(
977 'name' => 'contribution_soft_credit_email',
978 'title' => 'Soft Credit Email',
979 'headerPattern' => '/^soft_credit_email$/i',
980 'where' => 'soft_email.email',
982 'contribution_soft_credit_phone' => array(
983 'name' => 'contribution_soft_credit_phone',
984 'title' => 'Soft Credit Phone',
985 'headerPattern' => '/^soft_credit_phone$/i',
986 'where' => 'soft_phone.phone',
988 'contribution_soft_credit_contact_id' => array(
989 'name' => 'contribution_soft_credit_contact_id',
990 'title' => 'Soft Credit Contact ID',
991 'headerPattern' => '/^soft_credit_contact_id$/i',
992 'where' => 'civicrm_contribution_soft.contact_id',
1000 * @param int $pageID
1004 public static function getCurrentandGoalAmount($pageID) {
1006 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1007 FROM civicrm_contribution_page p,
1008 civicrm_contribution c
1009 WHERE p.id = c.contribution_page_id
1011 AND c.cancel_date is null
1015 $config = CRM_Core_Config
::singleton();
1016 $params = array(1 => array($pageID, 'Integer'));
1017 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1019 if ($dao->fetch()) {
1020 return array($dao->goal
, $dao->total
);
1023 return array(NULL, NULL);
1028 * Get list of contribution In Honor of contact Ids.
1030 * @param int $honorId
1031 * In Honor of Contact ID.
1034 * list of contribution fields
1037 public static function getHonorContacts($honorId) {
1039 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1040 $honorDAO->contact_id
= $honorId;
1043 $type = CRM_Contribute_PseudoConstant
::financialType();
1045 while ($honorDAO->fetch()) {
1046 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1047 $contributionDAO->id
= $honorDAO->contribution_id
;
1049 if ($contributionDAO->find(TRUE)) {
1050 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1051 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1052 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1053 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1054 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1055 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1056 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1057 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1058 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1066 * Get the sort name of a contact for a particular contribution.
1069 * Id of the contribution.
1071 * @return null|string
1072 * sort name of the contact if found
1074 public static function sortName($id) {
1075 $id = CRM_Utils_Type
::escape($id, 'Integer');
1078 SELECT civicrm_contact.sort_name
1079 FROM civicrm_contribution, civicrm_contact
1080 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1081 AND civicrm_contribution.id = {$id}
1083 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1087 * @param int $contactID
1091 public static function annual($contactID) {
1092 if (is_array($contactID)) {
1093 $contactIDs = implode(',', $contactID);
1096 $contactIDs = $contactID;
1099 $config = CRM_Core_Config
::singleton();
1100 $startDate = $endDate = NULL;
1102 $currentMonth = date('m');
1103 $currentDay = date('d');
1104 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1105 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1106 (int ) $config->fiscalYearStart
['d'] > $currentDay
1109 $year = date('Y') - 1;
1114 $nextYear = $year +
1;
1116 if ($config->fiscalYearStart
) {
1117 if ($config->fiscalYearStart
['M'] < 10) {
1118 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1120 if ($config->fiscalYearStart
['d'] < 10) {
1121 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1123 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1128 $startDate = "$year$monthDay";
1129 $endDate = "$nextYear$monthDay";
1132 SELECT count(*) as count,
1133 sum(total_amount) as amount,
1134 avg(total_amount) as average,
1136 FROM civicrm_contribution b
1137 WHERE b.contact_id IN ( $contactIDs )
1138 AND b.contribution_status_id = 1
1140 AND b.receive_date >= $startDate
1141 AND b.receive_date < $endDate
1144 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1146 $amount = $average = array();
1147 while ($dao->fetch()) {
1148 if ($dao->count
> 0 && $dao->amount
> 0) {
1149 $count +
= $dao->count
;
1150 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1151 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1157 implode(', ', $amount),
1158 implode(', ', $average),
1161 return array(0, 0, 0);
1165 * Check if there is a contribution with the params passed in.
1166 * Used for trxn_id,invoice_id and contribution_id
1168 * @param array $params
1169 * An assoc array of name/value pairs.
1172 * contribution id if success else NULL
1174 public static function checkDuplicateIds($params) {
1175 $dao = new CRM_Contribute_DAO_Contribution();
1179 foreach ($params as $k => $v) {
1181 $clause[] = "$k = '$v'";
1184 $clause = implode(' AND ', $clause);
1185 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1186 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1188 while ($dao->fetch()) {
1196 * Get the contribution details for component export.
1198 * @param int $exportMode
1200 * @param string $componentIds
1207 public static function getContributionDetails($exportMode, $componentIds) {
1208 $paymentDetails = array();
1209 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1211 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1212 $componentSelect = " civicrm_participant_payment.participant_id id";
1213 $additionalClause = "
1214 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1215 AND civicrm_participant_payment.participant_id {$componentClause} )
1218 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1219 $componentSelect = " civicrm_membership_payment.membership_id id";
1220 $additionalClause = "
1221 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1222 AND civicrm_membership_payment.membership_id {$componentClause} )
1225 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1226 $componentSelect = " civicrm_pledge_payment.id id";
1227 $additionalClause = "
1228 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1229 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1233 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1234 trxn_id, {$componentSelect}
1235 FROM civicrm_contribution
1236 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1237 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1238 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1239 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1240 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1241 AND option_group_contribution_status.id = contribution_status.option_group_id )
1245 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1247 while ($dao->fetch()) {
1248 $paymentDetails[$dao->id
] = array(
1249 'total_amount' => $dao->total_amount
,
1250 'contribution_status' => $dao->status
,
1251 'receive_date' => $dao->receive_date
,
1252 'pay_instru' => $dao->payment_instrument
,
1253 'trxn_id' => $dao->trxn_id
,
1257 return $paymentDetails;
1261 * Create address associated with contribution record.
1263 * @param array $params
1264 * @param int $billingLocationTypeID
1269 public static function createAddress(&$params, $billingLocationTypeID) {
1270 $billingFields = array(
1273 'state_province_id',
1278 //build address array
1279 $addressParams = array();
1280 $addressParams['location_type_id'] = $billingLocationTypeID;
1281 $addressParams['is_billing'] = 1;
1283 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1284 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1285 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1286 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1288 foreach ($billingFields as $value) {
1289 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1292 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1294 return $address->id
;
1298 * Delete billing address record related contribution.
1300 * @param int $contributionId
1301 * @param int $contactId
1304 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1306 $contactJoin = NULL;
1308 if ($contributionId) {
1309 $clauses[] = "cc.id = {$contributionId}";
1313 $clauses[] = "cco.id = {$contactId}";
1314 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1317 if (empty($clauses)) {
1318 CRM_Core_Error
::fatal();
1321 $condition = implode(' OR ', $clauses);
1325 FROM civicrm_address ca
1326 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1330 $dao = CRM_Core_DAO
::executeQuery($query);
1332 while ($dao->fetch()) {
1333 $params = array('id' => $dao->id
);
1334 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1339 * This function check online pending contribution associated w/
1340 * Online Event Registration or Online Membership signup.
1342 * @param int $componentId
1343 * Participant/membership id.
1344 * @param string $componentName
1348 * pending contribution id.
1350 public static function checkOnlinePendingContribution($componentId, $componentName) {
1351 $contributionId = NULL;
1352 if (!$componentId ||
1353 !in_array($componentName, array('Event', 'Membership'))
1355 return $contributionId;
1358 if ($componentName == 'Event') {
1359 $idName = 'participant_id';
1360 $componentTable = 'civicrm_participant';
1361 $paymentTable = 'civicrm_participant_payment';
1362 $source = ts('Online Event Registration');
1365 if ($componentName == 'Membership') {
1366 $idName = 'membership_id';
1367 $componentTable = 'civicrm_membership';
1368 $paymentTable = 'civicrm_membership_payment';
1369 $source = ts('Online Contribution');
1372 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1375 SELECT component.id as {$idName},
1376 componentPayment.contribution_id as contribution_id,
1377 contribution.source source,
1378 contribution.contribution_status_id as contribution_status_id,
1379 contribution.is_pay_later as is_pay_later
1380 FROM $componentTable component
1381 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1382 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1383 WHERE component.id = {$componentId}";
1385 $dao = CRM_Core_DAO
::executeQuery($query);
1387 while ($dao->fetch()) {
1388 if ($dao->contribution_id
&&
1389 $dao->is_pay_later
&&
1390 $dao->contribution_status_id
== $pendingStatusId &&
1391 strpos($dao->source
, $source) !== FALSE
1393 $contributionId = $dao->contribution_id
;
1398 return $contributionId;
1402 * Update contribution as well as related objects.
1404 * @param array $params
1405 * @param bool $processContributionObject
1408 * @throws \Exception
1410 public static function transitionComponents($params, $processContributionObject = FALSE) {
1411 // get minimum required values.
1412 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1413 $componentId = CRM_Utils_Array
::value('component_id', $params);
1414 $componentName = CRM_Utils_Array
::value('componentName', $params);
1415 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1416 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1418 // if we already processed contribution object pass previous status id.
1419 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1421 $updateResult = array();
1423 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1425 // we process only ( Completed, Cancelled, or Failed ) contributions.
1426 if (!$contributionId ||
1427 !in_array($contributionStatusId, array(
1428 array_search('Completed', $contributionStatuses),
1429 array_search('Cancelled', $contributionStatuses),
1430 array_search('Failed', $contributionStatuses),
1433 return $updateResult;
1436 if (!$componentName ||
!$componentId) {
1437 // get the related component details.
1438 $componentDetails = self
::getComponentDetails($contributionId);
1441 $componentDetails['contact_id'] = $contactId;
1442 $componentDetails['component'] = $componentName;
1444 if ($componentName == 'event') {
1445 $componentDetails['participant'] = $componentId;
1448 $componentDetails['membership'] = $componentId;
1452 if (!empty($componentDetails['contact_id'])) {
1453 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1459 // do check for required ids.
1460 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1461 return $updateResult;
1464 //now we are ready w/ required ids, start processing.
1466 $baseIPN = new CRM_Core_Payment_BaseIPN();
1468 $input = $ids = $objects = array();
1470 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1471 $ids['contribution'] = $contributionId;
1472 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1473 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1474 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1475 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1476 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1477 $ids['contributionRecur'] = NULL;
1478 $ids['contributionPage'] = NULL;
1480 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1481 CRM_Core_Error
::fatal();
1484 $memberships = &$objects['membership'];
1485 $participant = &$objects['participant'];
1486 $pledgePayment = &$objects['pledge_payment'];
1487 $contribution = &$objects['contribution'];
1489 if ($pledgePayment) {
1490 $pledgePaymentIDs = array();
1491 foreach ($pledgePayment as $key => $object) {
1492 $pledgePaymentIDs[] = $object->id
;
1494 $pledgeID = $pledgePayment[0]->pledge_id
;
1497 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1500 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1501 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1506 // we might want to process contribution object.
1507 $processContribution = FALSE;
1508 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1509 if (is_array($memberships)) {
1510 foreach ($memberships as $membership) {
1512 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1513 $membership->save();
1515 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1516 if ($processContributionObject) {
1517 $processContribution = TRUE;
1524 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1525 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1527 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1528 if ($processContributionObject) {
1529 $processContribution = TRUE;
1533 if ($pledgePayment) {
1534 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1536 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1537 if ($processContributionObject) {
1538 $processContribution = TRUE;
1542 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1543 if (is_array($memberships)) {
1544 foreach ($memberships as $membership) {
1546 $membership->status_id
= array_search('Expired', $membershipStatuses);
1547 $membership->save();
1549 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1550 if ($processContributionObject) {
1551 $processContribution = TRUE;
1557 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1558 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1560 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1561 if ($processContributionObject) {
1562 $processContribution = TRUE;
1566 if ($pledgePayment) {
1567 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1569 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1570 if ($processContributionObject) {
1571 $processContribution = TRUE;
1575 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1577 // only pending contribution related object processed.
1578 if ($previousContriStatusId &&
1579 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1581 // this is case when we already processed contribution object.
1582 return $updateResult;
1584 elseif (!$previousContriStatusId &&
1585 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1587 // this is case when we are going to process contribution object later.
1588 return $updateResult;
1591 if (is_array($memberships)) {
1592 foreach ($memberships as $membership) {
1597 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1598 $membership->membership_type_id
,
1599 $membership->is_test
, $membership->id
1602 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1603 // this picks up membership type changes during renewals
1605 SELECT membership_type_id
1606 FROM civicrm_membership_log
1607 WHERE membership_id=$membership->id
1610 $dao = new CRM_Core_DAO();
1612 if ($dao->fetch()) {
1613 if (!empty($dao->membership_type_id
)) {
1614 $membership->membership_type_id
= $dao->membership_type_id
;
1615 $membership->save();
1618 // else fall back to using current membership type
1621 // Figure out number of terms
1623 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1624 foreach ($lineitems as $lineitem) {
1625 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1626 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1628 // in case membership_num_terms comes through as null or zero
1629 $numterms = $numterms >= 1 ?
$numterms : 1;
1634 // CRM-15735-to update the membership status as per the contribution receive date
1635 if (!empty($params['receive_date'])) {
1636 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1637 $membership->end_date
,
1638 $membership->join_date
,
1639 $params['receive_date'],
1641 $membership->membership_type_id
,
1644 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1645 $membership->save();
1648 if ($currentMembership) {
1649 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1650 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1651 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1654 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1657 //get the status for membership.
1658 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1660 $dates['join_date'],
1663 $membership->membership_type_id
,
1667 $formattedParams = array(
1668 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1669 array_search('Current', $membershipStatuses)
1671 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1672 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1673 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1676 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1678 $membership->copyValues($formattedParams);
1679 $membership->save();
1681 //updating the membership log
1682 $membershipLog = array();
1683 $membershipLog = $formattedParams;
1684 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1685 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1687 $membershipLog['start_date'] = $logStartDate;
1688 $membershipLog['membership_id'] = $membership->id
;
1689 $membershipLog['modified_id'] = $membership->contact_id
;
1690 $membershipLog['modified_date'] = date('Ymd');
1691 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1693 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1695 //update related Memberships.
1696 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1698 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1701 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1702 if ($processContributionObject) {
1703 $processContribution = TRUE;
1706 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1712 $updatedStatusId = array_search('Registered', $participantStatuses);
1713 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1715 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1716 if ($processContributionObject) {
1717 $processContribution = TRUE;
1721 if ($pledgePayment) {
1722 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1724 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1725 if ($processContributionObject) {
1726 $processContribution = TRUE;
1731 // process contribution object.
1732 if ($processContribution) {
1733 $contributionParams = array();
1740 'payment_instrument_id',
1743 'financial_type_id',
1744 'contribution_status_id',
1745 'non_deductible_amount',
1749 foreach ($fields as $field) {
1750 if (empty($params[$field])) {
1753 $contributionParams[$field] = $params[$field];
1756 $ids = array('contribution' => $contributionId);
1757 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1760 return $updateResult;
1764 * Returns all contribution related object ids.
1766 * @param $contributionId
1770 public static function getComponentDetails($contributionId) {
1771 $componentDetails = $pledgePayment = array();
1772 if (!$contributionId) {
1773 return $componentDetails;
1777 SELECT c.id as contribution_id,
1778 c.contact_id as contact_id,
1779 c.contribution_recur_id,
1780 mp.membership_id as membership_id,
1781 m.membership_type_id as membership_type_id,
1782 pp.participant_id as participant_id,
1783 p.event_id as event_id,
1784 pgp.id as pledge_payment_id
1785 FROM civicrm_contribution c
1786 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1787 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1788 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1789 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1790 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1791 WHERE c.id = $contributionId";
1793 $dao = CRM_Core_DAO
::executeQuery($query);
1794 $componentDetails = array();
1796 while ($dao->fetch()) {
1797 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1798 $componentDetails['contact_id'] = $dao->contact_id
;
1799 if ($dao->event_id
) {
1800 $componentDetails['event'] = $dao->event_id
;
1802 if ($dao->participant_id
) {
1803 $componentDetails['participant'] = $dao->participant_id
;
1805 if ($dao->membership_id
) {
1806 if (!isset($componentDetails['membership'])) {
1807 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1809 $componentDetails['membership'][] = $dao->membership_id
;
1810 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1812 if ($dao->pledge_payment_id
) {
1813 $pledgePayment[] = $dao->pledge_payment_id
;
1815 if ($dao->contribution_recur_id
) {
1816 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1820 if ($pledgePayment) {
1821 $componentDetails['pledge_payment'] = $pledgePayment;
1824 return $componentDetails;
1828 * @param int $contactId
1829 * @param bool $includeSoftCredit
1831 * @return null|string
1833 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1838 $contactContributionsSQL = "
1839 SELECT contribution.id AS id
1840 FROM civicrm_contribution contribution
1841 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1843 $contactSoftCreditContributionsSQL = "
1844 SELECT contribution.id
1845 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1846 ON ( contribution.id = softContribution.contribution_id )
1847 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1848 $query = "SELECT count( x.id ) count FROM ( ";
1849 $query .= $contactContributionsSQL;
1851 if ($includeSoftCredit) {
1852 $query .= " UNION ";
1853 $query .= $contactSoftCreditContributionsSQL;
1858 return CRM_Core_DAO
::singleValueQuery($query);
1862 * Get individual id for onbehalf contribution.
1864 * @param int $contributionId
1866 * @param int $contributorId
1870 * containing organization id and individual id
1872 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1876 if (!$contributionId) {
1880 // fetch contributor id if null
1881 if (!$contributorId) {
1882 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1883 $contributionId, 'contact_id'
1887 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1888 $activityTypeId = array_search('Contribution', $activityTypeIds);
1890 if ($activityTypeId && $contributorId) {
1892 SELECT civicrm_activity_contact.contact_id
1893 FROM civicrm_activity_contact
1894 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1895 WHERE civicrm_activity.activity_type_id = %1
1896 AND civicrm_activity.source_record_id = %2
1897 AND civicrm_activity_contact.record_type_id = %3
1900 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1901 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1904 1 => array($activityTypeId, 'Integer'),
1905 2 => array($contributionId, 'Integer'),
1906 3 => array($sourceID, 'Integer'),
1909 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1911 // for on behalf contribution source is individual and contributor is organization
1912 if ($sourceContactId && $sourceContactId != $contributorId) {
1913 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1914 // get rel type id for employee of relation
1915 foreach ($relationshipTypeIds as $id => $typeVals) {
1916 if ($typeVals['name_a_b'] == 'Employee of') {
1917 $relationshipTypeId = $id;
1922 $rel = new CRM_Contact_DAO_Relationship();
1923 $rel->relationship_type_id
= $relationshipTypeId;
1924 $rel->contact_id_a
= $sourceContactId;
1925 $rel->contact_id_b
= $contributorId;
1926 if ($rel->find(TRUE)) {
1927 $ids['individual_id'] = $rel->contact_id_a
;
1928 $ids['organization_id'] = $rel->contact_id_b
;
1939 public static function getContributionDates() {
1940 $config = CRM_Core_Config
::singleton();
1941 $currentMonth = date('m');
1942 $currentDay = date('d');
1943 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1944 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1945 (int ) $config->fiscalYearStart
['d'] > $currentDay
1948 $year = date('Y') - 1;
1953 $year = array('Y' => $year);
1954 $yearDate = $config->fiscalYearStart
;
1955 $yearDate = array_merge($year, $yearDate);
1956 $yearDate = CRM_Utils_Date
::format($yearDate);
1958 $monthDate = date('Ym') . '01';
1964 'yearDate' => $yearDate,
1965 'monthDate' => $monthDate,
1970 * Load objects relations to contribution object.
1971 * Objects are stored in the $_relatedObjects property
1972 * In the first instance we are just moving functionality from BASEIpn -
1973 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1975 * Note that the unit test for the BaseIPN class tests this function
1977 * @param array $input
1978 * Input as delivered from Payment Processor.
1980 * Ids as Loaded by Payment Processor.
1981 * @param bool $required
1982 * Is Payment processor / contribution page required.
1983 * @param bool $loadAll
1984 * Load all related objects - even where id not passed in? (allows API to call this).
1989 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1991 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1992 if (empty($ids['contact']) && isset($this->contact_id
)) {
1993 $ids['contact'] = $this->contact_id
;
1996 if (empty($this->_component
)) {
1997 if (!empty($ids['event'])) {
1998 $this->_component
= 'event';
2001 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2004 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2005 $contributionType = new CRM_Financial_BAO_FinancialType();
2006 $contributionType->id
= $this->financial_type_id
;
2007 if (!$contributionType->find(TRUE)) {
2008 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2010 if (!empty($ids['contact'])) {
2011 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2012 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2013 $this->_relatedObjects
['contact']->find(TRUE);
2015 $this->_relatedObjects
['contributionType'] = $contributionType;
2017 if ($this->_component
== 'contribute') {
2018 // retrieve the other optional objects first so
2019 // stuff down the line can use this info and do things
2021 //in any case get the memberships associated with the contribution
2022 //because we now support multiple memberships w/ price set
2023 // see if there are any other memberships to be considered for same contribution.
2025 SELECT membership_id
2026 FROM civicrm_membership_payment
2027 WHERE contribution_id = %1 ";
2028 $params = array(1 => array($this->id
, 'Integer'));
2030 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2031 while ($dao->fetch()) {
2032 if ($dao->membership_id
) {
2033 if (!is_array($ids['membership'])) {
2034 $ids['membership'] = array();
2036 $ids['membership'][] = $dao->membership_id
;
2040 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2041 foreach ($ids['membership'] as $id) {
2043 $membership = new CRM_Member_BAO_Membership();
2044 $membership->id
= $id;
2045 if (!$membership->find(TRUE)) {
2046 throw new Exception("Could not find membership record: $id");
2048 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2049 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2050 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2051 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2052 $membership->free();
2057 if (!empty($ids['pledge_payment'])) {
2059 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2060 if (empty($paymentID)) {
2063 $payment = new CRM_Pledge_BAO_PledgePayment();
2064 $payment->id
= $paymentID;
2065 if (!$payment->find(TRUE)) {
2066 throw new Exception("Could not find pledge payment record: " . $paymentID);
2068 $this->_relatedObjects
['pledge_payment'][] = $payment;
2072 if (!empty($ids['contributionRecur'])) {
2073 $recur = new CRM_Contribute_BAO_ContributionRecur();
2074 $recur->id
= $ids['contributionRecur'];
2075 if (!$recur->find(TRUE)) {
2076 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2078 $this->_relatedObjects
['contributionRecur'] = &$recur;
2079 //get payment processor id from recur object.
2080 $paymentProcessorID = $recur->payment_processor_id
;
2082 //for normal contribution get the payment processor id.
2083 if (!$paymentProcessorID) {
2084 if ($this->contribution_page_id
) {
2085 // get the payment processor id from contribution page
2086 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2087 $this->contribution_page_id
,
2091 //fail to load payment processor id.
2092 elseif (empty($ids['pledge_payment'])) {
2093 $loadObjectSuccess = TRUE;
2095 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2097 return $loadObjectSuccess;
2102 // we are in event mode
2103 // make sure event exists and is valid
2104 $event = new CRM_Event_BAO_Event();
2105 $event->id
= $ids['event'];
2106 if ($ids['event'] &&
2109 throw new Exception("Could not find event: " . $ids['event']);
2112 $this->_relatedObjects
['event'] = &$event;
2114 $participant = new CRM_Event_BAO_Participant();
2115 $participant->id
= $ids['participant'];
2116 if ($ids['participant'] &&
2117 !$participant->find(TRUE)
2119 throw new Exception("Could not find participant: " . $ids['participant']);
2121 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2123 $this->_relatedObjects
['participant'] = &$participant;
2125 if (!$paymentProcessorID) {
2126 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2130 if ($paymentProcessorID) {
2131 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2132 $this->is_test ?
'test' : 'live'
2134 $ids['paymentProcessor'] = $paymentProcessorID;
2135 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2137 elseif ($required) {
2138 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2145 * Create array of message information - ie. return html version, txt version, to field
2147 * @param array $input
2148 * Incoming information.
2149 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2150 * just check presence of recur object but maintaining legacy approach
2153 * IDs of related objects.
2154 * @param array $values
2155 * Any values that may have already been compiled by calling process.
2156 * This is augmented by values 'gathered' by gatherMessageValues
2157 * @param bool $recur
2158 * @param bool $returnMessageText
2159 * Distinguishes between whether to send message or return.
2160 * message text. We are working towards this function ALWAYS returning message text & calling
2161 * function doing emails / pdfs with it
2167 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2168 if (empty($this->_relatedObjects
)) {
2169 $this->loadRelatedObjects($input, $ids);
2171 if (empty($this->_component
)) {
2172 $this->_component
= CRM_Utils_Array
::value('component', $input);
2175 //not really sure what params might be passed in but lets merge em into values
2176 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2177 $template = CRM_Core_Smarty
::singleton();
2178 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2179 //what does recur 'mean here - to do with payment processor return functionality but
2180 // what is the importance
2181 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2182 $paymentObject = &CRM_Core_Payment
::singleton(
2183 $this->is_test ?
'test' : 'live',
2184 $this->_relatedObjects
['paymentProcessor']
2187 $entityID = $entity = NULL;
2188 if (isset($ids['contribution'])) {
2189 $entity = 'contribution';
2190 $entityID = $ids['contribution'];
2192 if (!empty($ids['membership'])) {
2193 //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
2194 // 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
2195 // line having loaded an array
2196 $ids['membership'] = (array) $ids['membership'];
2197 $entity = 'membership';
2198 $entityID = $ids['membership'][0];
2201 $url = $paymentObject->subscriptionURL($entityID, $entity);
2202 $template->assign('cancelSubscriptionUrl', $url);
2204 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2205 $template->assign('updateSubscriptionBillingUrl', $url);
2207 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2208 $template->assign('updateSubscriptionUrl', $url);
2210 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2211 //direct mode showing billing block, so use directIPN for temporary
2212 $template->assign('contributeMode', 'directIPN');
2215 // todo remove strtolower - check consistency
2216 if (strtolower($this->_component
) == 'event') {
2217 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2218 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2222 $values['contribution_id'] = $this->id
;
2223 if (!empty($ids['related_contact'])) {
2224 $values['related_contact'] = $ids['related_contact'];
2225 if (isset($ids['onbehalf_dupe_alert'])) {
2226 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2228 $entityBlock = array(
2229 'contact_id' => $ids['contact'],
2230 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2231 'Home', 'id', 'name'
2234 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2235 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2238 if ($this->is_test
) {
2241 if (!empty($this->_relatedObjects
['membership'])) {
2242 foreach ($this->_relatedObjects
['membership'] as $membership) {
2243 if ($membership->id
) {
2244 $values['isMembership'] = TRUE;
2246 // need to set the membership values here
2247 $template->assign('membership_assign', 1);
2248 $template->assign('membership_name',
2249 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2251 $template->assign('mem_start_date', $membership->start_date
);
2252 $template->assign('mem_join_date', $membership->join_date
);
2253 $template->assign('mem_end_date', $membership->end_date
);
2254 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2255 $template->assign('mem_status', $membership_status);
2256 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2257 $template->assign('is_pay_later', 1);
2260 // if separate payment there are two contributions recorded and the
2261 // admin will need to send a receipt for each of them separately.
2262 // we dont link the two in the db (but can potentially infer it if needed)
2263 $template->assign('is_separate_payment', 0);
2265 if ($recur && $paymentObject) {
2266 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2267 $template->assign('cancelSubscriptionUrl', $url);
2268 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2269 $template->assign('updateSubscriptionBillingUrl', $url);
2270 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2271 $template->assign('updateSubscriptionUrl', $url);
2274 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2277 // otherwise if its about sending emails, continue sending without return, as we
2278 // don't want to exit the loop.
2283 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2289 * Gather values for contribution mail - this function has been created
2290 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2291 * Values related to the contribution in question are gathered
2293 * @param array $input
2294 * Input into function (probably from payment processor).
2295 * @param array $values
2297 * The set of ids related to the input.
2301 public function _gatherMessageValues($input, &$values, $ids = array()) {
2302 // set display address of contributor
2303 if ($this->address_id
) {
2304 $addressParams = array('id' => $this->address_id
);
2305 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2306 $addressDetails = array_values($addressDetails);
2307 $values['address'] = $addressDetails[0]['display'];
2309 if ($this->_component
== 'contribute') {
2310 if (isset($this->contribution_page_id
)) {
2311 CRM_Contribute_BAO_ContributionPage
::setValues(
2312 $this->contribution_page_id
,
2315 if ($this->contribution_page_id
) {
2316 // CRM-8254 - override default currency if applicable
2317 $config = CRM_Core_Config
::singleton();
2318 $config->defaultCurrency
= CRM_Utils_Array
::value(
2321 $config->defaultCurrency
2325 // no contribution page -probably back office
2327 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2328 $values['is_email_receipt'] = 1;
2329 $values['title'] = 'Contribution';
2331 // set lineItem for contribution
2333 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2334 if (!empty($lineItem)) {
2335 $itemId = key($lineItem);
2336 foreach ($lineItem as &$eachItem) {
2337 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2338 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2339 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2340 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2343 $values['lineItem'][0] = $lineItem;
2344 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2348 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2352 // if this is onbehalf of contribution then set related contact
2353 if (!empty($relatedContact['individual_id'])) {
2354 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2359 $eventParams = array(
2360 'id' => $this->_relatedObjects
['event']->id
,
2362 $values['event'] = array();
2364 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2366 //get location details
2367 $locationParams = array(
2368 'entity_id' => $this->_relatedObjects
['event']->id
,
2369 'entity_table' => 'civicrm_event',
2371 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2373 $ufJoinParams = array(
2374 'entity_table' => 'civicrm_event',
2375 'entity_id' => $ids['event'],
2376 'module' => 'CiviEvent',
2379 list($custom_pre_id,
2381 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2383 $values['custom_pre_id'] = $custom_pre_id;
2384 $values['custom_post_id'] = $custom_post_ids;
2386 // set lineItem for event contribution
2388 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2389 if (!empty($participantIds)) {
2390 foreach ($participantIds as $pIDs) {
2391 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2392 if (!CRM_Utils_System
::isNull($lineItem)) {
2393 $values['lineItem'][] = $lineItem;
2404 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2405 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2406 * Note we send directly from this function in some cases because it is only partly refactored
2407 * Don't call this function directly as the signature will change
2411 * @param CRM_Core_SMARTY $template
2412 * @param bool $recur
2413 * @param bool $returnMessageText
2417 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2418 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2419 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2420 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2421 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2422 $template->assign('useForMember', TRUE);
2424 //assign honor information to receipt message
2425 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2427 if (isset($softRecord['soft_credit'])) {
2428 //if id of contribution page is present
2429 if (!empty($values['id'])) {
2430 $values['honor'] = array(
2431 'honor_profile_values' => array(),
2432 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2433 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2435 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2437 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2438 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2441 //offline contribution
2442 $softCreditTypes = $softCredits = array();
2443 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2444 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2445 $softCredits[$key] = array(
2446 'Name' => $softCredit['contact_name'],
2447 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2450 $template->assign('softCreditTypes', $softCreditTypes);
2451 $template->assign('softCredits', $softCredits);
2455 $dao = new CRM_Contribute_DAO_ContributionProduct();
2456 $dao->contribution_id
= $this->id
;
2457 if ($dao->find(TRUE)) {
2458 $premiumId = $dao->product_id
;
2459 $template->assign('option', $dao->product_option
);
2461 $productDAO = new CRM_Contribute_DAO_Product();
2462 $productDAO->id
= $premiumId;
2463 $productDAO->find(TRUE);
2464 $template->assign('selectPremium', TRUE);
2465 $template->assign('product_name', $productDAO->name
);
2466 $template->assign('price', $productDAO->price
);
2467 $template->assign('sku', $productDAO->sku
);
2469 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2470 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2471 if (empty($amount) && isset($this->total_amount
)) {
2472 $amount = $this->total_amount
;
2474 $template->assign('amount', $amount);
2475 // add the new contribution values
2476 if (strtolower($this->_component
) == 'contribute') {
2478 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2479 $softDAO->contribution_id
= $this->id
;
2480 if ($softDAO->find(TRUE)) {
2481 $template->assign('pcpBlock', TRUE);
2482 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2483 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2484 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2486 //assign the pcp page title for email subject
2487 $pcpDAO = new CRM_PCP_DAO_PCP();
2488 $pcpDAO->id
= $softDAO->pcp_id
;
2489 if ($pcpDAO->find(TRUE)) {
2490 $template->assign('title', $pcpDAO->title
);
2495 if ($this->financial_type_id
) {
2496 $values['financial_type_id'] = $this->financial_type_id
;
2499 $template->assign('trxn_id', $this->trxn_id
);
2500 $template->assign('receive_date',
2501 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2503 $template->assign('contributeMode', 'notify');
2504 $template->assign('action', $this->is_test ?
1024 : 1);
2505 $template->assign('receipt_text',
2506 CRM_Utils_Array
::value('receipt_text',
2510 $template->assign('is_monetary', 1);
2511 $template->assign('is_recur', (bool) $recur);
2512 $template->assign('currency', $this->currency
);
2513 $template->assign('address', CRM_Utils_Address
::format($input));
2514 if ($this->_component
== 'event') {
2515 $template->assign('title', $values['event']['title']);
2516 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2517 $viewRoles = array();
2518 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2519 $viewRoles[] = $participantRoles[$v];
2521 $values['event']['participant_role'] = implode(', ', $viewRoles);
2522 $template->assign('event', $values['event']);
2523 $template->assign('location', $values['location']);
2524 $template->assign('customPre', $values['custom_pre_id']);
2525 $template->assign('customPost', $values['custom_post_id']);
2528 if ($this->_relatedObjects
['participant']->is_test
) {
2532 $values['params'] = array();
2533 //to get email of primary participant.
2534 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2535 $primaryAmount[] = array(
2536 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2537 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2539 //build an array of cId/pId of participants
2540 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2541 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2542 //send receipt to additional participant if exists
2543 if (count($additionalIDs)) {
2544 $template->assign('isPrimary', 0);
2545 $template->assign('customProfile', NULL);
2546 //set additionalParticipant true
2547 $values['params']['additionalParticipant'] = TRUE;
2548 foreach ($additionalIDs as $pId => $cId) {
2550 //to change the status pending to completed
2551 $additional = new CRM_Event_DAO_Participant();
2552 $additional->id
= $pId;
2553 $additional->contact_id
= $cId;
2554 $additional->find(TRUE);
2555 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2556 $additional->status_id
= 1;
2557 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2558 //if additional participant dont have email
2560 if (!$additionalParticipantInfo) {
2561 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2563 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2564 $primaryAmount[] = array(
2565 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2566 'amount' => $additional->fee_amount
,
2568 $additional->save();
2569 $additional->free();
2570 $template->assign('amount', $amount);
2571 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2575 //build an array of custom profile and assigning it to template
2576 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2578 if (count($customProfile)) {
2579 $template->assign('customProfile', $customProfile);
2582 // for primary contact
2583 $values['params']['additionalParticipant'] = FALSE;
2584 $template->assign('isPrimary', 1);
2585 $template->assign('amount', $primaryAmount);
2586 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2587 if ($this->payment_instrument_id
) {
2588 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2589 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2591 // carry paylater, since we did not created billing,
2592 // so need to pull email from primary location, CRM-4395
2593 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2599 * Check whether payment processor supports
2600 * cancellation of contribution subscription
2602 * @param int $contributionId
2605 * @param bool $isNotCancelled
2609 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2610 $cacheKeyString = "$contributionId";
2611 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2613 static $supportsCancel = array();
2615 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2616 $supportsCancel[$cacheKeyString] = FALSE;
2617 $isCancelled = FALSE;
2619 if ($isNotCancelled) {
2620 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2623 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2624 if (!empty($paymentObject)) {
2625 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2628 return $supportsCancel[$cacheKeyString];
2632 * Check whether subscription is already cancelled.
2634 * @param int $contributionId
2638 * contribution status
2640 public static function isSubscriptionCancelled($contributionId) {
2642 SELECT cr.contribution_status_id
2643 FROM civicrm_contribution_recur cr
2644 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2645 WHERE con.id = %1 LIMIT 1";
2646 $params = array(1 => array($contributionId, 'Integer'));
2647 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2648 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2649 if ($status == 'Cancelled') {
2656 * Create all financial accounts entry.
2658 * @param array $params
2659 * Contribution object, line item array and params for trxn.
2662 * @param array $financialTrxnValues
2664 * @return null|object
2666 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2667 $skipRecords = $update = $return = $isRelatedId = FALSE;
2669 $additionalParticipantId = array();
2670 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2672 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2673 $entityId = $params['participant_id'];
2674 $entityTable = 'civicrm_participant';
2675 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2677 elseif (!empty($params['membership_id'])) {
2678 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2679 // are created off one contribution should be handled elsewhere
2680 $entityId = $params['membership_id'];
2681 $entityTable = 'civicrm_membership';
2684 $entityId = $params['contribution']->id
;
2685 $entityTable = 'civicrm_contribution';
2688 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2689 $isRelatedId = TRUE;
2692 $entityID[] = $entityId;
2693 if (!empty($additionalParticipantId)) {
2694 $entityID +
= $additionalParticipantId;
2696 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2697 if (empty($params['prevContribution'])) {
2704 $statusId = $params['contribution']->contribution_status_id
;
2705 // CRM-13964 partial payment
2706 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2707 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2709 $partialAmtPay = $params['partial_amount_pay'];
2710 $partialAmtTotal = $params['partial_payment_total'];
2712 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2713 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2714 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2715 $params['total_amount'] = $partialAmtPay;
2717 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2718 if (empty($balanceTrxnInfo['trxn_id'])) {
2719 // create new balance transaction record
2720 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2721 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2723 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2724 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2725 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2726 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2727 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2728 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2729 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2730 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2731 $balanceTrxnParams['status_id'] = $statusId;
2732 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2733 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2734 if (!empty($params['payment_processor'])) {
2735 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2737 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2741 // build line item array if its not set in $params
2742 if (empty($params['line_item']) ||
$additionalParticipantId) {
2743 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2746 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2747 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2749 $skipRecords = TRUE;
2750 $pendingStatus = array(
2751 array_search('Pending', $contributionStatuses),
2752 array_search('In Progress', $contributionStatuses),
2754 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2755 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2756 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2758 elseif (!empty($params['payment_processor'])) {
2759 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2761 elseif (!empty($params['payment_instrument_id'])) {
2762 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2765 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2766 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2767 $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);
2770 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2771 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2772 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2775 //build financial transaction params
2776 $trxnParams = array(
2777 'contribution_id' => $params['contribution']->id
,
2778 'to_financial_account_id' => $params['to_financial_account_id'],
2779 'trxn_date' => date('YmdHis'),
2780 'total_amount' => $totalAmount,
2781 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2782 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2783 'currency' => $params['contribution']->currency
,
2784 'trxn_id' => $params['contribution']->trxn_id
,
2785 'status_id' => $statusId,
2786 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2787 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2790 if (!empty($params['payment_processor'])) {
2791 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2794 if (isset($fromFinancialAccountId)) {
2795 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2798 // consider external values passed for recording transaction entry
2799 if (!empty($financialTrxnValues)) {
2800 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2803 $params['trxnParams'] = $trxnParams;
2805 if (!empty($params['prevContribution'])) {
2806 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2807 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2808 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2809 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2810 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2812 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2813 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2814 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2816 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2817 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2820 //if financial type is changed
2821 if (!empty($params['financial_type_id']) &&
2822 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2824 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2825 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2826 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2827 if ($oldFinancialAccount != $newFinancialAccount) {
2828 $params['total_amount'] = 0;
2829 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2830 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2831 $params['prevContribution']->financial_type_id
, $relationTypeId);
2834 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2835 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2836 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2839 self
::updateFinancialAccounts($params, 'changeFinancialType');
2840 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2841 $params['financial_account_id'] = $newFinancialAccount;
2842 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2843 self
::updateFinancialAccounts($params);
2844 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2848 //Update contribution status
2849 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2850 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2851 if (!empty($params['contribution_status_id']) &&
2852 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2854 //Update Financial Records
2855 self
::updateFinancialAccounts($params, 'changedStatus');
2858 // change Payment Instrument for a Completed contribution
2859 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2860 // instrument is null and now new payment instrument is added along with the payment
2861 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2862 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2863 if (array_key_exists('payment_instrument_id', $params)) {
2864 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2865 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2866 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2868 //check if status is changed from Pending to Completed
2869 // do not update payment instrument changes for Pending to Completed
2870 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2871 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2873 // for all other statuses create new financial records
2874 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2875 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2876 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2879 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2880 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2881 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2883 // for any other payment instrument changes create new financial records
2884 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2885 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2886 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2888 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2889 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2891 // another special case when check number is changed, create new financial records
2892 // create financial trxn with negative amount
2893 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2894 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2895 // create financial trxn with positive amount
2896 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2897 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2898 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2902 //if Change contribution amount
2903 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2904 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2905 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2906 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2907 if (isset($totalAmount) &&
2908 $totalAmount != $params['prevContribution']->total_amount
2910 //Update Financial Records
2911 $params['trxnParams']['from_financial_account_id'] = NULL;
2912 self
::updateFinancialAccounts($params, 'changedAmount');
2917 // records finanical trxn and entity financial trxn
2918 // also make it available as return value
2919 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2920 $params['entity_id'] = $financialTxn->id
;
2923 // record line items and finacial items
2924 if (empty($params['skipLineItem'])) {
2925 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2928 // create batch entry if batch_id is passed
2929 if (!empty($params['batch_id'])) {
2930 $entityParams = array(
2931 'batch_id' => $params['batch_id'],
2932 'entity_table' => 'civicrm_financial_trxn',
2933 'entity_id' => $financialTxn->id
,
2935 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2938 // when a fee is charged
2939 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2940 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2943 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2944 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2946 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2947 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2948 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2950 unset($params['line_item']);
2956 * Update all financial accounts entry.
2958 * @param array $params
2959 * Contribution object, line item array and params for trxn.
2961 * @param string $context
2964 * @param null $skipTrxn
2967 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2968 $itemAmount = $trxnID = NULL;
2969 //get all the statuses
2970 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2971 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2972 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2973 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2974 && $context == 'changePaymentInstrument'
2978 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2979 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2981 if ($context == 'changedStatus') {
2982 //get all the statuses
2983 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2985 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2986 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2987 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2989 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2991 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2992 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2994 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2995 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2996 $params['trxnParams']['to_financial_account_id'] = NULL;
2997 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2999 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3000 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3001 $financialTypeID, $relationTypeId);
3003 $itemAmount = $params['trxnParams']['total_amount'];
3005 elseif ($context == 'changePaymentInstrument') {
3006 if ($params['trxnParams']['total_amount'] < 0) {
3007 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3008 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3009 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3010 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3014 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3015 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3018 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3019 $params['entity_id'] = $trxn->id
;
3021 if ($context == 'changedStatus') {
3022 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3023 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3024 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3026 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3027 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3029 $entityParams = array(
3030 'entity_table' => 'civicrm_financial_item',
3031 'financial_trxn_id' => $trxn->id
,
3033 if (empty($params['line_item'])) {
3035 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3036 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3037 // & this can be removed
3040 foreach ($params['line_item'] as $fieldId => $fields) {
3041 foreach ($fields as $fieldValueId => $fieldValues) {
3043 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3044 2 => array($fieldValues['id'], 'Integer'),
3046 CRM_Core_DAO
::executeQuery($query, $fparams);
3048 1 => array($fieldValues['id'], 'Integer'),
3050 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3051 while ($financialItem->fetch()) {
3052 $entityParams['entity_id'] = $financialItem->id
;
3053 $entityParams['amount'] = $financialItem->amount
;
3054 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3061 if ($context != 'changePaymentInstrument') {
3062 $itemParams['entity_table'] = 'civicrm_line_item';
3063 $trxnIds['id'] = $params['entity_id'];
3064 foreach ($params['line_item'] as $fieldId => $fields) {
3065 foreach ($fields as $fieldValueId => $fieldValues) {
3066 $prevParams['entity_id'] = $fieldValues['id'];
3067 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3069 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3070 if ($params['contribution']->receive_date
) {
3071 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3074 $financialAccount = $prevfinancialItem->financial_account_id
;
3075 if (!empty($params['financial_account_id'])) {
3076 $financialAccount = $params['financial_account_id'];
3079 $currency = $params['prevContribution']->currency
;
3080 if ($params['contribution']->currency
) {
3081 $currency = $params['contribution']->currency
;
3084 if (!empty($params['is_quick_config'])) {
3085 $amount = $itemAmount;
3087 $amount = $params['total_amount'];
3091 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3092 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3096 $amount = $diff * $fieldValues['line_total'];
3099 $itemParams = array(
3100 'transaction_date' => $receiveDate,
3101 'contact_id' => $params['prevContribution']->contact_id
,
3102 'currency' => $currency,
3103 'amount' => $amount,
3104 'description' => $prevfinancialItem->description
,
3105 'status_id' => $prevfinancialItem->status_id
,
3106 'financial_account_id' => $financialAccount,
3107 'entity_table' => 'civicrm_line_item',
3108 'entity_id' => $fieldValues['id'],
3110 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3112 if ($fieldValues['tax_amount']) {
3113 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3114 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3115 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3116 $itemParams['description'] = $taxTerm;
3117 if ($fieldValues['financial_type_id']) {
3118 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3120 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3128 * Check status validation on update of a contribution.
3130 * @param array $values
3131 * Previous form values before submit.
3133 * @param array $fields
3134 * The input form values.
3136 * @param array $errors
3141 public static function checkStatusValidation($values, &$fields, &$errors) {
3142 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3143 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3144 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3148 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3149 $checkStatus = array(
3150 'Cancelled' => array('Completed', 'Refunded'),
3151 'Completed' => array('Cancelled', 'Refunded'),
3152 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3153 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3154 'Refunded' => array('Cancelled', 'Completed'),
3157 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3158 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3159 1 => $contributionStatuses[$values['contribution_status_id']],
3160 2 => $contributionStatuses[$fields['contribution_status_id']],
3166 * Delete contribution of contact.
3170 * @param int $contactId
3174 public static function deleteContactContribution($contactId) {
3175 $contribution = new CRM_Contribute_DAO_Contribution();
3176 $contribution->contact_id
= $contactId;
3177 $contribution->find();
3178 while ($contribution->fetch()) {
3179 self
::deleteContribution($contribution->id
);
3184 * Get options for a given contribution field.
3185 * @see CRM_Core_DAO::buildOptions
3187 * @param string $fieldName
3188 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3189 * @param array $props whatever is known about this dao object.
3191 * @return array|bool
3193 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3194 $className = __CLASS__
;
3196 switch ($fieldName) {
3197 // This field is not part of this object but the api supports it
3198 case 'payment_processor':
3199 $className = 'CRM_Contribute_BAO_ContributionPage';
3200 // Filter results by contribution page
3201 if (!empty($props['contribution_page_id'])) {
3202 $page = civicrm_api('contribution_page', 'getsingle', array(
3204 'id' => ($props['contribution_page_id']),
3206 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3207 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3211 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3212 case 'honor_type_id':
3213 $className = 'CRM_Contribute_BAO_ContributionSoft';
3214 $fieldName = 'soft_credit_type_id';
3215 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3218 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3222 * Validate financial type.
3226 * @param int $financialTypeId
3227 * Financial Type id.
3229 * @param string $relationName
3231 * @return array|bool
3233 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3234 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3235 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3237 if (!$financialAccount) {
3238 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3245 * Function to record additional payment for partial and refund contributions.
3247 * @param int $contributionId
3248 * is the invoice contribution id (got created after processing participant payment).
3249 * @param array $trxnsData
3250 * to take user provided input of transaction details.
3251 * @param string $paymentType
3252 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3253 * @param int $participantId
3255 * @return null|object
3257 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3258 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3259 $getInfoOf['id'] = $contributionId;
3260 $defaults = array();
3261 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3263 if ($paymentType == 'owed') {
3264 // build params for recording financial trxn entry
3265 $params['contribution'] = $contributionDAO;
3266 $params = array_merge($defaults, $params);
3267 $params['skipLineItem'] = TRUE;
3268 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3269 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3270 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3273 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3274 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3275 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3277 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3278 if (!empty($trxnId)) {
3279 $trxnId = $trxnId['trxn_id'];
3281 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3282 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3285 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3286 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3287 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3291 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3292 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3293 FROM civicrm_financial_trxn ft
3294 LEFT JOIN civicrm_entity_financial_trxn eft
3295 ON (ft.id = eft.financial_trxn_id)
3296 WHERE eft.entity_table = 'civicrm_contribution'
3297 AND eft.entity_id = {$contributionId}
3298 AND ft.to_financial_account_id != {$toFinancialAccount}
3299 AND ft.status_id = {$statusId}
3301 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3304 if ($contributionDAO->total_amount
== $sumOfPayments) {
3305 // update contribution status and
3306 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3307 $contributionDAO->contribution_status_id
= $statusId;
3308 $contributionDAO->cancel_date
= 'null';
3309 $contributionDAO->cancel_reason
= NULL;
3310 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3311 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3312 $contributionDAO->save();
3314 //Change status of financial record too
3315 $financialTrxn->status_id
= $statusId;
3316 $financialTrxn->save();
3318 // note : not using the self::add method,
3319 // the reason because it performs 'status change' related code execution for financial records
3320 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3321 // are coded below i.e. just updating financial_item status to 'Paid'
3323 if ($participantId) {
3324 // update participant status
3325 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3326 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3327 foreach ($ids as $val) {
3328 $participantUpdate['id'] = $val;
3329 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3330 CRM_Event_BAO_Participant
::add($participantUpdate);
3334 // update financial item statuses
3335 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3336 $paidStatus = array_search('Paid', $financialItemStatus);
3338 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3339 $sqlFinancialItemUpdate = "
3340 UPDATE civicrm_financial_item fi
3341 LEFT JOIN civicrm_entity_financial_trxn eft
3342 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3343 SET status_id = {$paidStatus}
3344 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3346 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3349 elseif ($paymentType == 'refund') {
3350 // build params for recording financial trxn entry
3351 $params['contribution'] = $contributionDAO;
3352 $params = array_merge($defaults, $params);
3353 $params['skipLineItem'] = TRUE;
3354 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3355 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3357 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3358 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3359 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3361 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3363 // note : not using the self::add method,
3364 // the reason because it performs 'status change' related code execution for financial records
3365 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3366 // are coded below i.e. just updating financial_item status to 'Paid'
3367 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3369 // add financial item entry
3370 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3371 $getLine['entity_id'] = $contributionDAO->id
;
3372 $getLine['entity_table'] = 'civicrm_contribution';
3373 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3374 if (!empty($lineItemId->id
)) {
3375 $addFinancialEntry = array(
3376 'transaction_date' => $financialTrxn->trxn_date
,
3377 'contact_id' => $contributionDAO->contact_id
,
3378 'amount' => $financialTrxn->total_amount
,
3379 'status_id' => array_search('Paid', $financialItemStatus),
3380 'entity_id' => $lineItemId->id
,
3381 'entity_table' => 'civicrm_line_item',
3383 $trxnIds['id'] = $financialTrxn->id
;
3384 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3386 if ($participantId) {
3387 // update participant status
3388 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3389 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3390 foreach ($ids as $val) {
3391 $participantUpdate['id'] = $val;
3392 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3393 CRM_Event_BAO_Participant
::add($participantUpdate);
3398 // activity creation
3399 if (!empty($financialTrxn)) {
3400 if ($participantId) {
3401 $inputParams['id'] = $participantId;
3404 $component = 'event';
3405 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3406 $entityObj = $entityObj[$participantId];
3408 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3410 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3412 return $financialTrxn;
3418 * @param $activityType
3420 * @param int $contributionId
3422 * @throws CRM_Core_Exception
3424 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3425 if ($component == 'event') {
3426 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3427 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3428 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3429 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3430 $targetCid = $entityObj->contact_id
;
3431 // source record id would be the contribution id
3432 $srcRecId = $contributionId;
3436 $activityParams = array(
3437 'source_contact_id' => $targetCid,
3438 'source_record_id' => $srcRecId,
3439 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3443 'subject' => $subject,
3444 'activity_date_time' => $date,
3445 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3449 'skipRecentView' => TRUE,
3452 // create activity with target contacts
3453 $session = CRM_Core_Session
::singleton();
3454 $id = $session->get('userID');
3456 $activityParams['source_contact_id'] = $id;
3457 $activityParams['target_contact_id'][] = $targetCid;
3459 CRM_Activity_BAO_Activity
::create($activityParams);
3463 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3467 * @param bool $getTrxnInfo
3468 * @param bool $usingLineTotal
3472 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3473 if ($component == 'event') {
3474 $entity = 'participant';
3475 $entityTable = 'civicrm_participant';
3476 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3478 if (!$contributionId) {
3479 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3480 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3481 $id = $primaryParticipantId;
3483 if (!$contributionId) {
3488 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3489 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3495 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3496 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3499 if (empty($total) ||
$usingLineTotal) {
3500 // for additional participants
3501 if ($entityTable == 'civicrm_participant') {
3502 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3504 foreach ($ids as $val) {
3505 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3509 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3513 $baseTrxnId = $total['trxn_id'];
3514 $total = $total['total_amount'];
3517 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3518 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3520 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3521 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3522 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3524 if ($paymentBalance == 0 && $contributionIsPayLater) {
3525 $paymentBalance = $total;
3528 $info['total'] = $total;
3529 $info['paid'] = $total - $paymentBalance;
3530 $info['balance'] = $paymentBalance;
3532 $info['component'] = $component;
3533 $info['payLater'] = $contributionIsPayLater;
3535 if ($getTrxnInfo && $baseTrxnId) {
3536 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3538 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3539 FROM civicrm_contribution con
3540 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3541 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3542 WHERE con.id = {$contributionId}
3545 // conditioned WHERE clause
3547 // if balance trxn exists don't include details of it in transaction info
3548 $sql .= " AND ft.id != {$baseTrxnId} ";
3550 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3552 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3553 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3554 while ($resultDAO->fetch()) {
3555 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3556 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3558 'total_amount' => $resultDAO->total_amount
,
3559 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3560 'payment_instrument' => $paidByLabel,
3561 'receive_date' => $resultDAO->trxn_date
,
3562 'trxn_id' => $resultDAO->trxn_id
,
3563 'status' => $statuses[$resultDAO->status_id
],
3565 if ($paidByName == 'Check') {
3566 $val['check_number'] = $resultDAO->check_number
;
3570 $info['transaction'] = $rows;
3576 * Get financial account id has 'Sales Tax Account is'
3577 * account relationship with financial type
3579 * @param int $financialTypeId
3581 * @return FinancialAccountId
3583 public static function getFinancialAccountId($financialTypeId) {
3584 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3585 $searchParams = array(
3586 'entity_table' => 'civicrm_financial_type',
3587 'entity_id' => $financialTypeId,
3588 'account_relationship' => $accountRel,
3591 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3593 return CRM_Utils_Array
::value('financial_account_id', $result);
3599 * @param array $params
3600 * @param bool $isLineItem
3604 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3605 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3607 // Update contribution.
3608 if (!empty($params['id'])) {
3609 $id = $params['id'];
3610 $values = $ids = array();
3611 $contrbutionParams = array('id' => $id);
3612 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3614 // To assign pervious finantial type on update of contribution
3615 if (!isset($params['financial_type_id'])) {
3616 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3618 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3619 // Assisn tax Amount on update of contrbution
3620 if (!empty($prevContributionValue->tax_amount
)) {
3621 $params['tax_amount'] = 'null';
3622 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3623 foreach ($params['line_item'] as $setID => $priceField) {
3624 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3625 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3632 // New Contrbution and update of contribution with tax rate financial type
3633 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3634 empty($params['skipLineItem']) && !$isLineItem
3636 $taxRateParams = $taxRates[$params['financial_type_id']];
3637 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3638 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3640 // Get Line Item on update of contribution
3641 if (isset($params['id'])) {
3642 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3645 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3647 foreach ($params['line_item'] as $setID => $priceField) {
3648 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3649 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3652 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3654 elseif (isset($params['api.line_item.create'])) {
3655 // Update total amount of contribution using lineItem
3656 $taxAmountArray = array();
3657 foreach ($params['api.line_item.create'] as $key => $value) {
3658 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3659 $taxRate = $taxRates[$value['financial_type_id']];
3660 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3661 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3664 $params['tax_amount'] = array_sum($taxAmountArray);
3665 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3668 // update line item of contrbution
3669 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3670 $taxRate = $taxRates[$params['financial_type_id']];
3671 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3672 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3679 * Check financial type validation on update of a contribution.
3681 * @param Integer $financialTypeId
3682 * Value of latest Financial Type.
3687 * @param array $errors
3692 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3693 if (!empty($financialTypeId)) {
3694 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3695 if ($oldFinancialTypeId == $financialTypeId) {
3699 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3701 '1' => array($contributionId, 'Integer')
3703 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3704 if ($result->N
> 1) {
3705 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');