3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 // Handle soft credit and / or link to personal campaign page
371 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
373 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
375 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
376 $softParams = array();
377 $softParams['contribution_id'] = $contribution->id
;
378 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
379 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
380 $pcp['pcp_made_through_id'], 'contact_id'
382 $softParams['currency'] = $contribution->currency
;
383 $softParams['amount'] = $contribution->total_amount
;
384 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
385 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
386 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
387 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
388 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
389 //Send notification to owner for PCP
390 if ($contributionSoft->pcp_id
) {
391 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
394 //Delete PCP against this contribution and create new on submitted PCP information
395 elseif (array_key_exists('pcp', $params) && $pcpId) {
396 $deleteParams = array('id' => $pcpId);
397 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
399 if (isset($params['soft_credit'])) {
400 $softParams = $params['soft_credit'];
402 if (!empty($softIDs)) {
403 foreach ($softIDs as $softID) {
404 if (!in_array($softID, $params['soft_credit_ids'])) {
405 $deleteParams = array('id' => $softID);
406 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
411 foreach ($softParams as $softParam) {
412 $softParam['contribution_id'] = $contribution->id
;
413 $softParam['currency'] = $contribution->currency
;
414 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
415 if (empty($softParam['amount'])) {
416 $softParam['amount'] = $contribution->total_amount
;
418 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
422 $transaction->commit();
424 // check if activity record exist for this contribution, if
426 $activity = new CRM_Activity_DAO_Activity();
427 $activity->source_record_id
= $contribution->id
;
428 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
432 if (!$activity->find(TRUE)) {
433 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
436 // CRM-13237 : if activity record found, update it with campaign id of contribution
437 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
440 // do not add to recent items for import, CRM-4399
441 if (empty($params['skipRecentView'])) {
442 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
443 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
445 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
446 $titleFields = array(
452 $retrieveRequired = 0;
453 foreach ($titleFields as $titleField) {
454 if (!isset($contribution->$titleField)) {
455 $retrieveRequired = 1;
459 if ($retrieveRequired == 1) {
460 $contribution->find(TRUE);
462 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
463 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
465 $recentOther = array();
466 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
467 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
468 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
472 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
473 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
474 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
478 // add the recently created Contribution
479 CRM_Utils_Recent
::add($title,
483 $contribution->contact_id
,
489 return $contribution;
493 * Get the values for pseudoconstants for name->value and reverse.
495 * @param array $defaults
496 * (reference) the default values, some of which need to be resolved.
497 * @param bool $reverse
498 * True if we want to resolve the values in the reverse direction (value -> name).
502 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
503 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
504 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
505 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
506 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
510 * Convert associative array names to values and vice-versa.
512 * This function is used by both the web form layer and the api. Note that
513 * the api needs the name => value conversion, also the view layer typically
514 * requires value => name conversion
516 * @param array $defaults
517 * @param string $property
518 * @param array $lookup
519 * @param bool $reverse
523 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
524 $id = $property . '_id';
526 $src = $reverse ?
$property : $id;
527 $dst = $reverse ?
$id : $property;
529 if (!array_key_exists($src, $defaults)) {
533 $look = $reverse ?
array_flip($lookup) : $lookup;
535 if (is_array($look)) {
536 if (!array_key_exists($defaults[$src], $look)) {
540 $defaults[$dst] = $look[$defaults[$src]];
545 * Retrieve DB object based on input parameters.
547 * It also stores all the retrieved values in the default array.
549 * @param array $params
550 * (reference ) an assoc array of name/value pairs.
551 * @param array $defaults
552 * (reference ) an assoc array to hold the name / value pairs.
553 * in a hierarchical manner
555 * (reference) the array that holds all the db ids.
557 * @return CRM_Contribute_BAO_Contribution
559 public static function retrieve(&$params, &$defaults, &$ids) {
560 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
561 return $contribution;
565 * Combine all the importable fields from the lower levels object.
567 * The ordering is important, since currently we do not have a weight
568 * scheme. Adding weight is super important and should be done in the
569 * next week or so, before this can be called complete.
571 * @param string $contactType
572 * @param bool $status
575 * array of importable Fields
577 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
578 if (!self
::$_importableFields) {
579 if (!self
::$_importableFields) {
580 self
::$_importableFields = array();
584 $fields = array('' => array('title' => ts('- do not import -')));
587 $fields = array('' => array('title' => ts('- Contribution Fields -')));
590 $note = CRM_Core_DAO_Note
::import();
591 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
592 unset($tmpFields['option_value']);
593 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
594 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
596 // Using new Dedupe rule.
598 'contact_type' => $contactType,
599 'used' => 'Unsupervised',
601 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
602 $tmpContactField = array();
603 if (is_array($fieldsArray)) {
604 foreach ($fieldsArray as $value) {
605 //skip if there is no dupe rule
606 if ($value == 'none') {
609 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
614 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
615 $tmpContactField[trim($value)] = $contactFields[trim($value)];
617 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
620 $title = $tmpContactField[trim($value)]['title'];
622 $tmpContactField[trim($value)]['title'] = $title;
626 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
627 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
628 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
629 $fields = array_merge($fields, $tmpContactField);
630 $fields = array_merge($fields, $tmpFields);
631 $fields = array_merge($fields, $note);
632 $fields = array_merge($fields, $optionFields);
633 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
634 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
635 self
::$_importableFields = $fields;
637 return self
::$_importableFields;
643 public static function &exportableFields() {
644 if (!self
::$_exportableFields) {
645 if (!self
::$_exportableFields) {
646 self
::$_exportableFields = array();
649 $impFields = CRM_Contribute_DAO_Contribution
::export();
650 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
651 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
652 $typeField = CRM_Financial_DAO_FinancialType
::export();
653 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
654 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
655 $contributionStatus = array(
656 'contribution_status' => array(
657 'title' => ts('Contribution Status'),
658 'name' => 'contribution_status',
659 'data_type' => CRM_Utils_Type
::T_STRING
,
663 $contributionPage = array(
664 'contribution_page' => array(
665 'title' => ts('Contribution Page'),
666 'name' => 'contribution_page',
667 'where' => 'civicrm_contribution_page.title',
668 'data_type' => CRM_Utils_Type
::T_STRING
,
672 $contributionNote = array(
673 'contribution_note' => array(
674 'title' => ts('Contribution Note'),
675 'name' => 'contribution_note',
676 'data_type' => CRM_Utils_Type
::T_TEXT
,
680 $contributionRecurId = array(
681 'contribution_recur_id' => array(
682 'title' => ts('Recurring Contributions ID'),
683 'name' => 'contribution_recur_id',
684 'where' => 'civicrm_contribution.contribution_recur_id',
685 'data_type' => CRM_Utils_Type
::T_INT
,
689 $extraFields = array(
690 'contribution_batch' => array(
691 'title' => ts('Batch Name'),
695 $softCreditFields = array(
696 'contribution_soft_credit_name' => array(
697 'name' => 'contribution_soft_credit_name',
698 'title' => 'Soft Credit For',
699 'where' => 'civicrm_contact_d.display_name',
700 'data_type' => CRM_Utils_Type
::T_STRING
,
702 'contribution_soft_credit_amount' => array(
703 'name' => 'contribution_soft_credit_amount',
704 'title' => 'Soft Credit Amount',
705 'where' => 'civicrm_contribution_soft.amount',
706 'data_type' => CRM_Utils_Type
::T_MONEY
,
708 'contribution_soft_credit_type' => array(
709 'name' => 'contribution_soft_credit_type',
710 'title' => 'Soft Credit Type',
711 'where' => 'contribution_softcredit_type.label',
712 'data_type' => CRM_Utils_Type
::T_STRING
,
714 'contribution_soft_credit_contribution_id' => array(
715 'name' => 'contribution_soft_credit_contribution_id',
716 'title' => 'Soft Credit For Contribution ID',
717 'where' => 'civicrm_contribution_soft.contribution_id',
718 'data_type' => CRM_Utils_Type
::T_INT
,
722 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
723 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
724 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
727 self
::$_exportableFields = $fields;
730 return self
::$_exportableFields;
734 * @param null $status
735 * @param null $startDate
736 * @param null $endDate
740 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
744 $where[] = 'contribution_status_id = 1';
748 $where[] = 'contribution_status_id = 3';
753 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
756 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
759 $whereCond = implode(' AND ', $where);
762 SELECT sum( total_amount ) as total_amount,
763 count( civicrm_contribution.id ) as total_count,
765 FROM civicrm_contribution
766 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
768 AND ( is_test = 0 OR is_test IS NULL )
769 AND contact.is_deleted = 0
773 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
776 while ($dao->fetch()) {
777 $count +
= $dao->total_count
;
778 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
782 'amount' => implode(', ', $amount),
790 * Delete the indirect records associated with this contribution first.
795 * $results no of deleted Contribution on success, false otherwise
797 public static function deleteContribution($id) {
798 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
800 $transaction = new CRM_Core_Transaction();
803 //delete activity record
805 'source_record_id' => $id,
806 // activity type id for contribution
807 'activity_type_id' => 6,
810 CRM_Activity_BAO_Activity
::deleteActivity($params);
812 //delete billing address if exists for this contribution.
813 self
::deleteAddress($id);
815 //update pledge and pledge payment, CRM-3961
816 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
818 // remove entry from civicrm_price_set_entity, CRM-5095
819 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
820 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
822 // cleanup line items.
823 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
825 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
826 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
828 if ($participantId) {
829 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
832 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
836 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
837 $noteId = key($note);
839 CRM_Core_BAO_Note
::del($noteId, FALSE);
842 $dao = new CRM_Contribute_DAO_Contribution();
845 $results = $dao->delete();
847 $transaction->commit();
849 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
851 // delete the recently created Contribution
852 $contributionRecent = array(
854 'type' => 'Contribution',
856 CRM_Utils_Recent
::del($contributionRecent);
862 * Check if there is a contribution with the same trxn_id or invoice_id.
864 * @param array $input
865 * An assoc array of name/value pairs.
866 * @param array $duplicates
867 * (reference) store ids of duplicate contribs.
871 * true if duplicate, false otherwise
873 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
875 $id = CRM_Utils_Array
::value('id', $input);
877 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
878 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
884 $clause[] = "trxn_id = %1";
885 $input[1] = array($trxn_id, 'String');
889 $clause[] = "invoice_id = %2";
890 $input[2] = array($invoice_id, 'String');
893 if (empty($clause)) {
897 $clause = implode(' OR ', $clause);
899 $clause = "( $clause ) AND id != %3";
900 $input[3] = array($id, 'Integer');
903 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
904 $dao = CRM_Core_DAO
::executeQuery($query, $input);
906 while ($dao->fetch()) {
907 $duplicates[] = $dao->id
;
914 * Takes an associative array and creates a contribution_product object.
916 * the function extract all the params it needs to initialize the create a
917 * contribution_product object. the params array could contain additional unused name/value
920 * @param array $params
921 * (reference) an assoc array of name/value pairs.
923 * @return CRM_Contribute_DAO_ContributionProduct
925 public static function addPremium(&$params) {
926 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
927 $contributionProduct->copyValues($params);
928 return $contributionProduct->save();
932 * Get list of contribution fields for profile.
933 * For now we only allow custom contribution fields to be in
936 * @param bool $addExtraFields
937 * True if special fields needs to be added.
940 * the list of contribution fields
942 public static function getContributionFields($addExtraFields = TRUE) {
943 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
944 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
946 if ($addExtraFields) {
947 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
950 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
952 foreach ($contributionFields as $key => $var) {
953 if ($key == 'contribution_contact_id') {
956 elseif ($key == 'contribution_campaign_id') {
957 $var['title'] = ts('Campaign');
959 $fields[$key] = $var;
962 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
967 * Add extra fields specific to contribution.
969 public static function getSpecialContributionFields() {
970 $extraFields = array(
971 'contribution_soft_credit_name' => array(
972 'name' => 'contribution_soft_credit_name',
973 'title' => 'Soft Credit Name',
974 'headerPattern' => '/^soft_credit_name$/i',
975 'where' => 'civicrm_contact_d.display_name',
977 'contribution_soft_credit_email' => array(
978 'name' => 'contribution_soft_credit_email',
979 'title' => 'Soft Credit Email',
980 'headerPattern' => '/^soft_credit_email$/i',
981 'where' => 'soft_email.email',
983 'contribution_soft_credit_phone' => array(
984 'name' => 'contribution_soft_credit_phone',
985 'title' => 'Soft Credit Phone',
986 'headerPattern' => '/^soft_credit_phone$/i',
987 'where' => 'soft_phone.phone',
989 'contribution_soft_credit_contact_id' => array(
990 'name' => 'contribution_soft_credit_contact_id',
991 'title' => 'Soft Credit Contact ID',
992 'headerPattern' => '/^soft_credit_contact_id$/i',
993 'where' => 'civicrm_contribution_soft.contact_id',
1001 * @param int $pageID
1005 public static function getCurrentandGoalAmount($pageID) {
1007 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1008 FROM civicrm_contribution_page p,
1009 civicrm_contribution c
1010 WHERE p.id = c.contribution_page_id
1012 AND c.cancel_date is null
1016 $config = CRM_Core_Config
::singleton();
1017 $params = array(1 => array($pageID, 'Integer'));
1018 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1020 if ($dao->fetch()) {
1021 return array($dao->goal
, $dao->total
);
1024 return array(NULL, NULL);
1029 * Get list of contribution In Honor of contact Ids.
1031 * @param int $honorId
1032 * In Honor of Contact ID.
1035 * list of contribution fields
1038 public static function getHonorContacts($honorId) {
1040 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1041 $honorDAO->contact_id
= $honorId;
1044 $type = CRM_Contribute_PseudoConstant
::financialType();
1046 while ($honorDAO->fetch()) {
1047 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1048 $contributionDAO->id
= $honorDAO->contribution_id
;
1050 if ($contributionDAO->find(TRUE)) {
1051 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1052 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1053 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1054 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1055 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1056 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1057 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1058 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1059 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1067 * Get the sort name of a contact for a particular contribution.
1070 * Id of the contribution.
1072 * @return null|string
1073 * sort name of the contact if found
1075 public static function sortName($id) {
1076 $id = CRM_Utils_Type
::escape($id, 'Integer');
1079 SELECT civicrm_contact.sort_name
1080 FROM civicrm_contribution, civicrm_contact
1081 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1082 AND civicrm_contribution.id = {$id}
1084 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1088 * @param int $contactID
1092 public static function annual($contactID) {
1093 if (is_array($contactID)) {
1094 $contactIDs = implode(',', $contactID);
1097 $contactIDs = $contactID;
1100 $config = CRM_Core_Config
::singleton();
1101 $startDate = $endDate = NULL;
1103 $currentMonth = date('m');
1104 $currentDay = date('d');
1105 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1106 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1107 (int ) $config->fiscalYearStart
['d'] > $currentDay
1110 $year = date('Y') - 1;
1115 $nextYear = $year +
1;
1117 if ($config->fiscalYearStart
) {
1118 if ($config->fiscalYearStart
['M'] < 10) {
1119 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1121 if ($config->fiscalYearStart
['d'] < 10) {
1122 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1124 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1129 $startDate = "$year$monthDay";
1130 $endDate = "$nextYear$monthDay";
1133 SELECT count(*) as count,
1134 sum(total_amount) as amount,
1135 avg(total_amount) as average,
1137 FROM civicrm_contribution b
1138 WHERE b.contact_id IN ( $contactIDs )
1139 AND b.contribution_status_id = 1
1141 AND b.receive_date >= $startDate
1142 AND b.receive_date < $endDate
1145 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1147 $amount = $average = array();
1148 while ($dao->fetch()) {
1149 if ($dao->count
> 0 && $dao->amount
> 0) {
1150 $count +
= $dao->count
;
1151 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1152 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1158 implode(', ', $amount),
1159 implode(', ', $average),
1162 return array(0, 0, 0);
1166 * Check if there is a contribution with the params passed in.
1167 * Used for trxn_id,invoice_id and contribution_id
1169 * @param array $params
1170 * An assoc array of name/value pairs.
1173 * contribution id if success else NULL
1175 public static function checkDuplicateIds($params) {
1176 $dao = new CRM_Contribute_DAO_Contribution();
1180 foreach ($params as $k => $v) {
1182 $clause[] = "$k = '$v'";
1185 $clause = implode(' AND ', $clause);
1186 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1187 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1189 while ($dao->fetch()) {
1197 * Get the contribution details for component export.
1199 * @param int $exportMode
1201 * @param string $componentIds
1208 public static function getContributionDetails($exportMode, $componentIds) {
1209 $paymentDetails = array();
1210 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1212 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1213 $componentSelect = " civicrm_participant_payment.participant_id id";
1214 $additionalClause = "
1215 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1216 AND civicrm_participant_payment.participant_id {$componentClause} )
1219 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1220 $componentSelect = " civicrm_membership_payment.membership_id id";
1221 $additionalClause = "
1222 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1223 AND civicrm_membership_payment.membership_id {$componentClause} )
1226 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1227 $componentSelect = " civicrm_pledge_payment.id id";
1228 $additionalClause = "
1229 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1230 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1234 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1235 trxn_id, {$componentSelect}
1236 FROM civicrm_contribution
1237 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1238 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1239 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1240 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1241 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1242 AND option_group_contribution_status.id = contribution_status.option_group_id )
1246 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1248 while ($dao->fetch()) {
1249 $paymentDetails[$dao->id
] = array(
1250 'total_amount' => $dao->total_amount
,
1251 'contribution_status' => $dao->status
,
1252 'receive_date' => $dao->receive_date
,
1253 'pay_instru' => $dao->payment_instrument
,
1254 'trxn_id' => $dao->trxn_id
,
1258 return $paymentDetails;
1262 * Create address associated with contribution record.
1264 * @param array $params
1265 * @param int $billingLocationTypeID
1270 public static function createAddress(&$params, $billingLocationTypeID) {
1271 $billingFields = array(
1274 'state_province_id',
1279 //build address array
1280 $addressParams = array();
1281 $addressParams['location_type_id'] = $billingLocationTypeID;
1282 $addressParams['is_billing'] = 1;
1284 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1285 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1286 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1287 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1289 foreach ($billingFields as $value) {
1290 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1293 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1295 return $address->id
;
1299 * Delete billing address record related contribution.
1301 * @param int $contributionId
1302 * @param int $contactId
1305 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1307 $contactJoin = NULL;
1309 if ($contributionId) {
1310 $clauses[] = "cc.id = {$contributionId}";
1314 $clauses[] = "cco.id = {$contactId}";
1315 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1318 if (empty($clauses)) {
1319 CRM_Core_Error
::fatal();
1322 $condition = implode(' OR ', $clauses);
1326 FROM civicrm_address ca
1327 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1331 $dao = CRM_Core_DAO
::executeQuery($query);
1333 while ($dao->fetch()) {
1334 $params = array('id' => $dao->id
);
1335 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1340 * This function check online pending contribution associated w/
1341 * Online Event Registration or Online Membership signup.
1343 * @param int $componentId
1344 * Participant/membership id.
1345 * @param string $componentName
1349 * pending contribution id.
1351 public static function checkOnlinePendingContribution($componentId, $componentName) {
1352 $contributionId = NULL;
1353 if (!$componentId ||
1354 !in_array($componentName, array('Event', 'Membership'))
1356 return $contributionId;
1359 if ($componentName == 'Event') {
1360 $idName = 'participant_id';
1361 $componentTable = 'civicrm_participant';
1362 $paymentTable = 'civicrm_participant_payment';
1363 $source = ts('Online Event Registration');
1366 if ($componentName == 'Membership') {
1367 $idName = 'membership_id';
1368 $componentTable = 'civicrm_membership';
1369 $paymentTable = 'civicrm_membership_payment';
1370 $source = ts('Online Contribution');
1373 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1376 SELECT component.id as {$idName},
1377 componentPayment.contribution_id as contribution_id,
1378 contribution.source source,
1379 contribution.contribution_status_id as contribution_status_id,
1380 contribution.is_pay_later as is_pay_later
1381 FROM $componentTable component
1382 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1383 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1384 WHERE component.id = {$componentId}";
1386 $dao = CRM_Core_DAO
::executeQuery($query);
1388 while ($dao->fetch()) {
1389 if ($dao->contribution_id
&&
1390 $dao->is_pay_later
&&
1391 $dao->contribution_status_id
== $pendingStatusId &&
1392 strpos($dao->source
, $source) !== FALSE
1394 $contributionId = $dao->contribution_id
;
1399 return $contributionId;
1403 * Update contribution as well as related objects.
1405 * @param array $params
1406 * @param bool $processContributionObject
1409 * @throws \Exception
1411 public static function transitionComponents($params, $processContributionObject = FALSE) {
1412 // get minimum required values.
1413 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1414 $componentId = CRM_Utils_Array
::value('component_id', $params);
1415 $componentName = CRM_Utils_Array
::value('componentName', $params);
1416 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1417 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1419 // if we already processed contribution object pass previous status id.
1420 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1422 $updateResult = array();
1424 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1426 // we process only ( Completed, Cancelled, or Failed ) contributions.
1427 if (!$contributionId ||
1428 !in_array($contributionStatusId, array(
1429 array_search('Completed', $contributionStatuses),
1430 array_search('Cancelled', $contributionStatuses),
1431 array_search('Failed', $contributionStatuses),
1434 return $updateResult;
1437 if (!$componentName ||
!$componentId) {
1438 // get the related component details.
1439 $componentDetails = self
::getComponentDetails($contributionId);
1442 $componentDetails['contact_id'] = $contactId;
1443 $componentDetails['component'] = $componentName;
1445 if ($componentName == 'event') {
1446 $componentDetails['participant'] = $componentId;
1449 $componentDetails['membership'] = $componentId;
1453 if (!empty($componentDetails['contact_id'])) {
1454 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1460 // do check for required ids.
1461 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1462 return $updateResult;
1465 //now we are ready w/ required ids, start processing.
1467 $baseIPN = new CRM_Core_Payment_BaseIPN();
1469 $input = $ids = $objects = array();
1471 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1472 $ids['contribution'] = $contributionId;
1473 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1474 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1475 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1476 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1477 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1478 $ids['contributionRecur'] = NULL;
1479 $ids['contributionPage'] = NULL;
1481 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1482 CRM_Core_Error
::fatal();
1485 $memberships = &$objects['membership'];
1486 $participant = &$objects['participant'];
1487 $pledgePayment = &$objects['pledge_payment'];
1488 $contribution = &$objects['contribution'];
1490 if ($pledgePayment) {
1491 $pledgePaymentIDs = array();
1492 foreach ($pledgePayment as $key => $object) {
1493 $pledgePaymentIDs[] = $object->id
;
1495 $pledgeID = $pledgePayment[0]->pledge_id
;
1498 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1501 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1502 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1507 // we might want to process contribution object.
1508 $processContribution = FALSE;
1509 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1510 if (is_array($memberships)) {
1511 foreach ($memberships as $membership) {
1513 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1514 $membership->save();
1516 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1517 if ($processContributionObject) {
1518 $processContribution = TRUE;
1525 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1526 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1528 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1529 if ($processContributionObject) {
1530 $processContribution = TRUE;
1534 if ($pledgePayment) {
1535 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1537 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1538 if ($processContributionObject) {
1539 $processContribution = TRUE;
1543 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1544 if (is_array($memberships)) {
1545 foreach ($memberships as $membership) {
1547 $membership->status_id
= array_search('Expired', $membershipStatuses);
1548 $membership->save();
1550 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1551 if ($processContributionObject) {
1552 $processContribution = TRUE;
1558 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1559 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1561 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1562 if ($processContributionObject) {
1563 $processContribution = TRUE;
1567 if ($pledgePayment) {
1568 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1570 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1571 if ($processContributionObject) {
1572 $processContribution = TRUE;
1576 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1578 // only pending contribution related object processed.
1579 if ($previousContriStatusId &&
1580 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1582 // this is case when we already processed contribution object.
1583 return $updateResult;
1585 elseif (!$previousContriStatusId &&
1586 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1588 // this is case when we are going to process contribution object later.
1589 return $updateResult;
1592 if (is_array($memberships)) {
1593 foreach ($memberships as $membership) {
1598 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1599 $membership->membership_type_id
,
1600 $membership->is_test
, $membership->id
1603 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1604 // this picks up membership type changes during renewals
1606 SELECT membership_type_id
1607 FROM civicrm_membership_log
1608 WHERE membership_id=$membership->id
1611 $dao = new CRM_Core_DAO();
1613 if ($dao->fetch()) {
1614 if (!empty($dao->membership_type_id
)) {
1615 $membership->membership_type_id
= $dao->membership_type_id
;
1616 $membership->save();
1619 // else fall back to using current membership type
1622 // Figure out number of terms
1624 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1625 foreach ($lineitems as $lineitem) {
1626 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1627 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1629 // in case membership_num_terms comes through as null or zero
1630 $numterms = $numterms >= 1 ?
$numterms : 1;
1635 // CRM-15735-to update the membership status as per the contribution receive date
1637 if (!empty($params['receive_date'])) {
1638 $joinDate = $params['receive_date'];
1639 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1640 $membership->end_date
,
1641 $membership->join_date
,
1642 $params['receive_date'],
1644 $membership->membership_type_id
,
1647 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1648 $membership->save();
1651 if ($currentMembership) {
1652 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1653 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1654 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1657 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1660 //get the status for membership.
1661 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1663 $dates['join_date'],
1666 $membership->membership_type_id
,
1670 $formattedParams = array(
1671 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1672 array_search('Current', $membershipStatuses)
1674 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1675 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1676 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1679 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1681 $membership->copyValues($formattedParams);
1682 $membership->save();
1684 //updating the membership log
1685 $membershipLog = array();
1686 $membershipLog = $formattedParams;
1687 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1688 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1690 $membershipLog['start_date'] = $logStartDate;
1691 $membershipLog['membership_id'] = $membership->id
;
1692 $membershipLog['modified_id'] = $membership->contact_id
;
1693 $membershipLog['modified_date'] = date('Ymd');
1694 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1696 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1698 //update related Memberships.
1699 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1701 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1704 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1705 if ($processContributionObject) {
1706 $processContribution = TRUE;
1709 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1715 $updatedStatusId = array_search('Registered', $participantStatuses);
1716 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1718 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1719 if ($processContributionObject) {
1720 $processContribution = TRUE;
1724 if ($pledgePayment) {
1725 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1727 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1728 if ($processContributionObject) {
1729 $processContribution = TRUE;
1734 // process contribution object.
1735 if ($processContribution) {
1736 $contributionParams = array();
1743 'payment_instrument_id',
1746 'financial_type_id',
1747 'contribution_status_id',
1748 'non_deductible_amount',
1752 foreach ($fields as $field) {
1753 if (empty($params[$field])) {
1756 $contributionParams[$field] = $params[$field];
1759 $ids = array('contribution' => $contributionId);
1760 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1763 return $updateResult;
1767 * Returns all contribution related object ids.
1769 * @param $contributionId
1773 public static function getComponentDetails($contributionId) {
1774 $componentDetails = $pledgePayment = array();
1775 if (!$contributionId) {
1776 return $componentDetails;
1780 SELECT c.id as contribution_id,
1781 c.contact_id as contact_id,
1782 c.contribution_recur_id,
1783 mp.membership_id as membership_id,
1784 m.membership_type_id as membership_type_id,
1785 pp.participant_id as participant_id,
1786 p.event_id as event_id,
1787 pgp.id as pledge_payment_id
1788 FROM civicrm_contribution c
1789 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1790 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1791 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1792 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1793 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1794 WHERE c.id = $contributionId";
1796 $dao = CRM_Core_DAO
::executeQuery($query);
1797 $componentDetails = array();
1799 while ($dao->fetch()) {
1800 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1801 $componentDetails['contact_id'] = $dao->contact_id
;
1802 if ($dao->event_id
) {
1803 $componentDetails['event'] = $dao->event_id
;
1805 if ($dao->participant_id
) {
1806 $componentDetails['participant'] = $dao->participant_id
;
1808 if ($dao->membership_id
) {
1809 if (!isset($componentDetails['membership'])) {
1810 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1812 $componentDetails['membership'][] = $dao->membership_id
;
1813 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1815 if ($dao->pledge_payment_id
) {
1816 $pledgePayment[] = $dao->pledge_payment_id
;
1818 if ($dao->contribution_recur_id
) {
1819 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1823 if ($pledgePayment) {
1824 $componentDetails['pledge_payment'] = $pledgePayment;
1827 return $componentDetails;
1831 * @param int $contactId
1832 * @param bool $includeSoftCredit
1834 * @return null|string
1836 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1841 $contactContributionsSQL = "
1842 SELECT contribution.id AS id
1843 FROM civicrm_contribution contribution
1844 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1846 $contactSoftCreditContributionsSQL = "
1847 SELECT contribution.id
1848 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1849 ON ( contribution.id = softContribution.contribution_id )
1850 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1851 $query = "SELECT count( x.id ) count FROM ( ";
1852 $query .= $contactContributionsSQL;
1854 if ($includeSoftCredit) {
1855 $query .= " UNION ";
1856 $query .= $contactSoftCreditContributionsSQL;
1861 return CRM_Core_DAO
::singleValueQuery($query);
1865 * Get individual id for onbehalf contribution.
1867 * @param int $contributionId
1869 * @param int $contributorId
1873 * containing organization id and individual id
1875 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1879 if (!$contributionId) {
1883 // fetch contributor id if null
1884 if (!$contributorId) {
1885 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1886 $contributionId, 'contact_id'
1890 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1891 $activityTypeId = array_search('Contribution', $activityTypeIds);
1893 if ($activityTypeId && $contributorId) {
1895 SELECT civicrm_activity_contact.contact_id
1896 FROM civicrm_activity_contact
1897 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1898 WHERE civicrm_activity.activity_type_id = %1
1899 AND civicrm_activity.source_record_id = %2
1900 AND civicrm_activity_contact.record_type_id = %3
1903 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1904 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1907 1 => array($activityTypeId, 'Integer'),
1908 2 => array($contributionId, 'Integer'),
1909 3 => array($sourceID, 'Integer'),
1912 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1914 // for on behalf contribution source is individual and contributor is organization
1915 if ($sourceContactId && $sourceContactId != $contributorId) {
1916 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1917 // get rel type id for employee of relation
1918 foreach ($relationshipTypeIds as $id => $typeVals) {
1919 if ($typeVals['name_a_b'] == 'Employee of') {
1920 $relationshipTypeId = $id;
1925 $rel = new CRM_Contact_DAO_Relationship();
1926 $rel->relationship_type_id
= $relationshipTypeId;
1927 $rel->contact_id_a
= $sourceContactId;
1928 $rel->contact_id_b
= $contributorId;
1929 if ($rel->find(TRUE)) {
1930 $ids['individual_id'] = $rel->contact_id_a
;
1931 $ids['organization_id'] = $rel->contact_id_b
;
1942 public static function getContributionDates() {
1943 $config = CRM_Core_Config
::singleton();
1944 $currentMonth = date('m');
1945 $currentDay = date('d');
1946 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1947 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1948 (int ) $config->fiscalYearStart
['d'] > $currentDay
1951 $year = date('Y') - 1;
1956 $year = array('Y' => $year);
1957 $yearDate = $config->fiscalYearStart
;
1958 $yearDate = array_merge($year, $yearDate);
1959 $yearDate = CRM_Utils_Date
::format($yearDate);
1961 $monthDate = date('Ym') . '01';
1967 'yearDate' => $yearDate,
1968 'monthDate' => $monthDate,
1973 * Load objects relations to contribution object.
1974 * Objects are stored in the $_relatedObjects property
1975 * In the first instance we are just moving functionality from BASEIpn -
1976 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1978 * Note that the unit test for the BaseIPN class tests this function
1980 * @param array $input
1981 * Input as delivered from Payment Processor.
1983 * Ids as Loaded by Payment Processor.
1984 * @param bool $required
1985 * Is Payment processor / contribution page required.
1986 * @param bool $loadAll
1987 * Load all related objects - even where id not passed in? (allows API to call this).
1992 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1994 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1995 if (empty($ids['contact']) && isset($this->contact_id
)) {
1996 $ids['contact'] = $this->contact_id
;
1999 if (empty($this->_component
)) {
2000 if (!empty($ids['event'])) {
2001 $this->_component
= 'event';
2004 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2007 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2008 $contributionType = new CRM_Financial_BAO_FinancialType();
2009 $contributionType->id
= $this->financial_type_id
;
2010 if (!$contributionType->find(TRUE)) {
2011 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2013 if (!empty($ids['contact'])) {
2014 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2015 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2016 $this->_relatedObjects
['contact']->find(TRUE);
2018 $this->_relatedObjects
['contributionType'] = $contributionType;
2020 if ($this->_component
== 'contribute') {
2021 // retrieve the other optional objects first so
2022 // stuff down the line can use this info and do things
2024 //in any case get the memberships associated with the contribution
2025 //because we now support multiple memberships w/ price set
2026 // see if there are any other memberships to be considered for same contribution.
2028 SELECT membership_id
2029 FROM civicrm_membership_payment
2030 WHERE contribution_id = %1 ";
2031 $params = array(1 => array($this->id
, 'Integer'));
2033 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2034 while ($dao->fetch()) {
2035 if ($dao->membership_id
) {
2036 if (!is_array($ids['membership'])) {
2037 $ids['membership'] = array();
2039 $ids['membership'][] = $dao->membership_id
;
2043 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2044 foreach ($ids['membership'] as $id) {
2046 $membership = new CRM_Member_BAO_Membership();
2047 $membership->id
= $id;
2048 if (!$membership->find(TRUE)) {
2049 throw new Exception("Could not find membership record: $id");
2051 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2052 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2053 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2054 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2055 $membership->free();
2060 if (!empty($ids['pledge_payment'])) {
2062 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2063 if (empty($paymentID)) {
2066 $payment = new CRM_Pledge_BAO_PledgePayment();
2067 $payment->id
= $paymentID;
2068 if (!$payment->find(TRUE)) {
2069 throw new Exception("Could not find pledge payment record: " . $paymentID);
2071 $this->_relatedObjects
['pledge_payment'][] = $payment;
2075 if (!empty($ids['contributionRecur'])) {
2076 $recur = new CRM_Contribute_BAO_ContributionRecur();
2077 $recur->id
= $ids['contributionRecur'];
2078 if (!$recur->find(TRUE)) {
2079 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2081 $this->_relatedObjects
['contributionRecur'] = &$recur;
2082 //get payment processor id from recur object.
2083 $paymentProcessorID = $recur->payment_processor_id
;
2085 //for normal contribution get the payment processor id.
2086 if (!$paymentProcessorID) {
2087 if ($this->contribution_page_id
) {
2088 // get the payment processor id from contribution page
2089 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2090 $this->contribution_page_id
,
2094 //fail to load payment processor id.
2095 elseif (empty($ids['pledge_payment'])) {
2096 $loadObjectSuccess = TRUE;
2098 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2100 return $loadObjectSuccess;
2105 // we are in event mode
2106 // make sure event exists and is valid
2107 $event = new CRM_Event_BAO_Event();
2108 $event->id
= $ids['event'];
2109 if ($ids['event'] &&
2112 throw new Exception("Could not find event: " . $ids['event']);
2115 $this->_relatedObjects
['event'] = &$event;
2117 $participant = new CRM_Event_BAO_Participant();
2118 $participant->id
= $ids['participant'];
2119 if ($ids['participant'] &&
2120 !$participant->find(TRUE)
2122 throw new Exception("Could not find participant: " . $ids['participant']);
2124 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2126 $this->_relatedObjects
['participant'] = &$participant;
2128 if (!$paymentProcessorID) {
2129 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2133 if ($paymentProcessorID) {
2134 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2135 $this->is_test ?
'test' : 'live'
2137 $ids['paymentProcessor'] = $paymentProcessorID;
2138 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2140 elseif ($required) {
2141 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2148 * Create array of message information - ie. return html version, txt version, to field
2150 * @param array $input
2151 * Incoming information.
2152 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2153 * just check presence of recur object but maintaining legacy approach
2156 * IDs of related objects.
2157 * @param array $values
2158 * Any values that may have already been compiled by calling process.
2159 * This is augmented by values 'gathered' by gatherMessageValues
2160 * @param bool $recur
2161 * @param bool $returnMessageText
2162 * Distinguishes between whether to send message or return.
2163 * message text. We are working towards this function ALWAYS returning message text & calling
2164 * function doing emails / pdfs with it
2170 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2171 if (empty($this->_relatedObjects
)) {
2172 $this->loadRelatedObjects($input, $ids);
2174 if (empty($this->_component
)) {
2175 $this->_component
= CRM_Utils_Array
::value('component', $input);
2178 //not really sure what params might be passed in but lets merge em into values
2179 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2180 $template = CRM_Core_Smarty
::singleton();
2181 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2182 //what does recur 'mean here - to do with payment processor return functionality but
2183 // what is the importance
2184 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2185 $paymentObject = &CRM_Core_Payment
::singleton(
2186 $this->is_test ?
'test' : 'live',
2187 $this->_relatedObjects
['paymentProcessor']
2190 $entityID = $entity = NULL;
2191 if (isset($ids['contribution'])) {
2192 $entity = 'contribution';
2193 $entityID = $ids['contribution'];
2195 if (!empty($ids['membership'])) {
2196 //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
2197 // 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
2198 // line having loaded an array
2199 $ids['membership'] = (array) $ids['membership'];
2200 $entity = 'membership';
2201 $entityID = $ids['membership'][0];
2204 $url = $paymentObject->subscriptionURL($entityID, $entity);
2205 $template->assign('cancelSubscriptionUrl', $url);
2207 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2208 $template->assign('updateSubscriptionBillingUrl', $url);
2210 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2211 $template->assign('updateSubscriptionUrl', $url);
2213 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2214 //direct mode showing billing block, so use directIPN for temporary
2215 $template->assign('contributeMode', 'directIPN');
2218 // todo remove strtolower - check consistency
2219 if (strtolower($this->_component
) == 'event') {
2220 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2221 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2225 $values['contribution_id'] = $this->id
;
2226 if (!empty($ids['related_contact'])) {
2227 $values['related_contact'] = $ids['related_contact'];
2228 if (isset($ids['onbehalf_dupe_alert'])) {
2229 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2231 $entityBlock = array(
2232 'contact_id' => $ids['contact'],
2233 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2234 'Home', 'id', 'name'
2237 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2238 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2241 if ($this->is_test
) {
2244 if (!empty($this->_relatedObjects
['membership'])) {
2245 foreach ($this->_relatedObjects
['membership'] as $membership) {
2246 if ($membership->id
) {
2247 $values['isMembership'] = TRUE;
2249 // need to set the membership values here
2250 $template->assign('membership_assign', 1);
2251 $template->assign('membership_name',
2252 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2254 $template->assign('mem_start_date', $membership->start_date
);
2255 $template->assign('mem_join_date', $membership->join_date
);
2256 $template->assign('mem_end_date', $membership->end_date
);
2257 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2258 $template->assign('mem_status', $membership_status);
2259 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2260 $template->assign('is_pay_later', 1);
2263 // if separate payment there are two contributions recorded and the
2264 // admin will need to send a receipt for each of them separately.
2265 // we dont link the two in the db (but can potentially infer it if needed)
2266 $template->assign('is_separate_payment', 0);
2268 if ($recur && $paymentObject) {
2269 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2270 $template->assign('cancelSubscriptionUrl', $url);
2271 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2272 $template->assign('updateSubscriptionBillingUrl', $url);
2273 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2274 $template->assign('updateSubscriptionUrl', $url);
2277 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2280 // otherwise if its about sending emails, continue sending without return, as we
2281 // don't want to exit the loop.
2286 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2292 * Gather values for contribution mail - this function has been created
2293 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2294 * Values related to the contribution in question are gathered
2296 * @param array $input
2297 * Input into function (probably from payment processor).
2298 * @param array $values
2300 * The set of ids related to the input.
2304 public function _gatherMessageValues($input, &$values, $ids = array()) {
2305 // set display address of contributor
2306 if ($this->address_id
) {
2307 $addressParams = array('id' => $this->address_id
);
2308 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2309 $addressDetails = array_values($addressDetails);
2310 $values['address'] = $addressDetails[0]['display'];
2312 if ($this->_component
== 'contribute') {
2313 if (isset($this->contribution_page_id
)) {
2314 CRM_Contribute_BAO_ContributionPage
::setValues(
2315 $this->contribution_page_id
,
2318 if ($this->contribution_page_id
) {
2319 // CRM-8254 - override default currency if applicable
2320 $config = CRM_Core_Config
::singleton();
2321 $config->defaultCurrency
= CRM_Utils_Array
::value(
2324 $config->defaultCurrency
2328 // no contribution page -probably back office
2330 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2331 $values['is_email_receipt'] = 1;
2332 $values['title'] = 'Contribution';
2334 // set lineItem for contribution
2336 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2337 if (!empty($lineItem)) {
2338 $itemId = key($lineItem);
2339 foreach ($lineItem as &$eachItem) {
2340 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2341 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2342 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2343 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2346 $values['lineItem'][0] = $lineItem;
2347 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2351 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2355 // if this is onbehalf of contribution then set related contact
2356 if (!empty($relatedContact['individual_id'])) {
2357 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2362 $eventParams = array(
2363 'id' => $this->_relatedObjects
['event']->id
,
2365 $values['event'] = array();
2367 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2369 //get location details
2370 $locationParams = array(
2371 'entity_id' => $this->_relatedObjects
['event']->id
,
2372 'entity_table' => 'civicrm_event',
2374 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2376 $ufJoinParams = array(
2377 'entity_table' => 'civicrm_event',
2378 'entity_id' => $ids['event'],
2379 'module' => 'CiviEvent',
2382 list($custom_pre_id,
2384 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2386 $values['custom_pre_id'] = $custom_pre_id;
2387 $values['custom_post_id'] = $custom_post_ids;
2389 // set lineItem for event contribution
2391 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2392 if (!empty($participantIds)) {
2393 foreach ($participantIds as $pIDs) {
2394 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2395 if (!CRM_Utils_System
::isNull($lineItem)) {
2396 $values['lineItem'][] = $lineItem;
2407 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2408 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2409 * Note we send directly from this function in some cases because it is only partly refactored
2410 * Don't call this function directly as the signature will change
2414 * @param CRM_Core_SMARTY $template
2415 * @param bool $recur
2416 * @param bool $returnMessageText
2420 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2421 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2422 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2423 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2424 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2425 $template->assign('useForMember', TRUE);
2427 //assign honor information to receipt message
2428 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2430 if (isset($softRecord['soft_credit'])) {
2431 //if id of contribution page is present
2432 if (!empty($values['id'])) {
2433 $values['honor'] = array(
2434 'honor_profile_values' => array(),
2435 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2436 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2438 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2440 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2441 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2444 //offline contribution
2445 $softCreditTypes = $softCredits = array();
2446 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2447 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2448 $softCredits[$key] = array(
2449 'Name' => $softCredit['contact_name'],
2450 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2453 $template->assign('softCreditTypes', $softCreditTypes);
2454 $template->assign('softCredits', $softCredits);
2458 $dao = new CRM_Contribute_DAO_ContributionProduct();
2459 $dao->contribution_id
= $this->id
;
2460 if ($dao->find(TRUE)) {
2461 $premiumId = $dao->product_id
;
2462 $template->assign('option', $dao->product_option
);
2464 $productDAO = new CRM_Contribute_DAO_Product();
2465 $productDAO->id
= $premiumId;
2466 $productDAO->find(TRUE);
2467 $template->assign('selectPremium', TRUE);
2468 $template->assign('product_name', $productDAO->name
);
2469 $template->assign('price', $productDAO->price
);
2470 $template->assign('sku', $productDAO->sku
);
2472 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2473 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2474 if (empty($amount) && isset($this->total_amount
)) {
2475 $amount = $this->total_amount
;
2477 $template->assign('amount', $amount);
2478 // add the new contribution values
2479 if (strtolower($this->_component
) == 'contribute') {
2481 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2482 $softDAO->contribution_id
= $this->id
;
2483 if ($softDAO->find(TRUE)) {
2484 $template->assign('pcpBlock', TRUE);
2485 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2486 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2487 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2489 //assign the pcp page title for email subject
2490 $pcpDAO = new CRM_PCP_DAO_PCP();
2491 $pcpDAO->id
= $softDAO->pcp_id
;
2492 if ($pcpDAO->find(TRUE)) {
2493 $template->assign('title', $pcpDAO->title
);
2498 if ($this->financial_type_id
) {
2499 $values['financial_type_id'] = $this->financial_type_id
;
2502 $template->assign('trxn_id', $this->trxn_id
);
2503 $template->assign('receive_date',
2504 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2506 $template->assign('contributeMode', 'notify');
2507 $template->assign('action', $this->is_test ?
1024 : 1);
2508 $template->assign('receipt_text',
2509 CRM_Utils_Array
::value('receipt_text',
2513 $template->assign('is_monetary', 1);
2514 $template->assign('is_recur', (bool) $recur);
2515 $template->assign('currency', $this->currency
);
2516 $template->assign('address', CRM_Utils_Address
::format($input));
2517 if ($this->_component
== 'event') {
2518 $template->assign('title', $values['event']['title']);
2519 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2520 $viewRoles = array();
2521 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2522 $viewRoles[] = $participantRoles[$v];
2524 $values['event']['participant_role'] = implode(', ', $viewRoles);
2525 $template->assign('event', $values['event']);
2526 $template->assign('location', $values['location']);
2527 $template->assign('customPre', $values['custom_pre_id']);
2528 $template->assign('customPost', $values['custom_post_id']);
2531 if ($this->_relatedObjects
['participant']->is_test
) {
2535 $values['params'] = array();
2536 //to get email of primary participant.
2537 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2538 $primaryAmount[] = array(
2539 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2540 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2542 //build an array of cId/pId of participants
2543 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2544 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2545 //send receipt to additional participant if exists
2546 if (count($additionalIDs)) {
2547 $template->assign('isPrimary', 0);
2548 $template->assign('customProfile', NULL);
2549 //set additionalParticipant true
2550 $values['params']['additionalParticipant'] = TRUE;
2551 foreach ($additionalIDs as $pId => $cId) {
2553 //to change the status pending to completed
2554 $additional = new CRM_Event_DAO_Participant();
2555 $additional->id
= $pId;
2556 $additional->contact_id
= $cId;
2557 $additional->find(TRUE);
2558 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2559 $additional->status_id
= 1;
2560 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2561 //if additional participant dont have email
2563 if (!$additionalParticipantInfo) {
2564 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2566 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2567 $primaryAmount[] = array(
2568 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2569 'amount' => $additional->fee_amount
,
2571 $additional->save();
2572 $additional->free();
2573 $template->assign('amount', $amount);
2574 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2578 //build an array of custom profile and assigning it to template
2579 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2581 if (count($customProfile)) {
2582 $template->assign('customProfile', $customProfile);
2585 // for primary contact
2586 $values['params']['additionalParticipant'] = FALSE;
2587 $template->assign('isPrimary', 1);
2588 $template->assign('amount', $primaryAmount);
2589 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2590 if ($this->payment_instrument_id
) {
2591 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2592 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2594 // carry paylater, since we did not created billing,
2595 // so need to pull email from primary location, CRM-4395
2596 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2602 * Check whether payment processor supports
2603 * cancellation of contribution subscription
2605 * @param int $contributionId
2608 * @param bool $isNotCancelled
2612 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2613 $cacheKeyString = "$contributionId";
2614 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2616 static $supportsCancel = array();
2618 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2619 $supportsCancel[$cacheKeyString] = FALSE;
2620 $isCancelled = FALSE;
2622 if ($isNotCancelled) {
2623 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2626 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2627 if (!empty($paymentObject)) {
2628 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2631 return $supportsCancel[$cacheKeyString];
2635 * Check whether subscription is already cancelled.
2637 * @param int $contributionId
2641 * contribution status
2643 public static function isSubscriptionCancelled($contributionId) {
2645 SELECT cr.contribution_status_id
2646 FROM civicrm_contribution_recur cr
2647 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2648 WHERE con.id = %1 LIMIT 1";
2649 $params = array(1 => array($contributionId, 'Integer'));
2650 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2651 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2652 if ($status == 'Cancelled') {
2659 * Create all financial accounts entry.
2661 * @param array $params
2662 * Contribution object, line item array and params for trxn.
2665 * @param array $financialTrxnValues
2667 * @return null|object
2669 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2670 $skipRecords = $update = $return = $isRelatedId = FALSE;
2672 $additionalParticipantId = array();
2673 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2675 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2676 $entityId = $params['participant_id'];
2677 $entityTable = 'civicrm_participant';
2678 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2680 elseif (!empty($params['membership_id'])) {
2681 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2682 // are created off one contribution should be handled elsewhere
2683 $entityId = $params['membership_id'];
2684 $entityTable = 'civicrm_membership';
2687 $entityId = $params['contribution']->id
;
2688 $entityTable = 'civicrm_contribution';
2691 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2692 $isRelatedId = TRUE;
2695 $entityID[] = $entityId;
2696 if (!empty($additionalParticipantId)) {
2697 $entityID +
= $additionalParticipantId;
2699 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2700 if (empty($params['prevContribution'])) {
2707 $statusId = $params['contribution']->contribution_status_id
;
2708 // CRM-13964 partial payment
2709 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2710 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2712 $partialAmtPay = $params['partial_amount_pay'];
2713 $partialAmtTotal = $params['partial_payment_total'];
2715 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2716 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2717 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2718 $params['total_amount'] = $partialAmtPay;
2720 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2721 if (empty($balanceTrxnInfo['trxn_id'])) {
2722 // create new balance transaction record
2723 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2724 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2726 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2727 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2728 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2729 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2730 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2731 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2732 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2733 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2734 $balanceTrxnParams['status_id'] = $statusId;
2735 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2736 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2737 if (!empty($params['payment_processor'])) {
2738 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2740 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2744 // build line item array if its not set in $params
2745 if (empty($params['line_item']) ||
$additionalParticipantId) {
2746 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2749 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2750 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2752 $skipRecords = TRUE;
2753 $pendingStatus = array(
2754 array_search('Pending', $contributionStatuses),
2755 array_search('In Progress', $contributionStatuses),
2757 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2758 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2759 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2761 elseif (!empty($params['payment_processor'])) {
2762 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2764 elseif (!empty($params['payment_instrument_id'])) {
2765 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2768 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2769 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2770 $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);
2773 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2774 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2775 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2778 //build financial transaction params
2779 $trxnParams = array(
2780 'contribution_id' => $params['contribution']->id
,
2781 'to_financial_account_id' => $params['to_financial_account_id'],
2782 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2783 'total_amount' => $totalAmount,
2784 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2785 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2786 'currency' => $params['contribution']->currency
,
2787 'trxn_id' => $params['contribution']->trxn_id
,
2788 'status_id' => $statusId,
2789 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2790 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2793 if (!empty($params['payment_processor'])) {
2794 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2797 if (isset($fromFinancialAccountId)) {
2798 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2801 // consider external values passed for recording transaction entry
2802 if (!empty($financialTrxnValues)) {
2803 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2806 $params['trxnParams'] = $trxnParams;
2808 if (!empty($params['prevContribution'])) {
2809 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2810 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2811 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2812 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2813 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2815 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2816 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2817 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2819 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2820 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2823 //if financial type is changed
2824 if (!empty($params['financial_type_id']) &&
2825 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2827 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2828 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2829 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2830 if ($oldFinancialAccount != $newFinancialAccount) {
2831 $params['total_amount'] = 0;
2832 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2833 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2834 $params['prevContribution']->financial_type_id
, $relationTypeId);
2837 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2838 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2839 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2842 self
::updateFinancialAccounts($params, 'changeFinancialType');
2843 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2844 $params['financial_account_id'] = $newFinancialAccount;
2845 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2846 self
::updateFinancialAccounts($params);
2847 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2851 //Update contribution status
2852 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2853 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2854 if (!empty($params['contribution_status_id']) &&
2855 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2857 //Update Financial Records
2858 self
::updateFinancialAccounts($params, 'changedStatus');
2861 // change Payment Instrument for a Completed contribution
2862 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2863 // instrument is null and now new payment instrument is added along with the payment
2864 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2865 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2866 if (array_key_exists('payment_instrument_id', $params)) {
2867 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2868 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2869 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2871 //check if status is changed from Pending to Completed
2872 // do not update payment instrument changes for Pending to Completed
2873 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2874 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2876 // for all other statuses create new financial records
2877 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2878 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2879 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2882 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2883 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2884 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2886 // for any other payment instrument changes create new financial records
2887 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2888 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2889 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2891 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2892 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2894 // another special case when check number is changed, create new financial records
2895 // create financial trxn with negative amount
2896 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2897 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2898 // create financial trxn with positive amount
2899 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2900 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2901 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2905 //if Change contribution amount
2906 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2907 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2908 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2909 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2910 if (isset($totalAmount) &&
2911 $totalAmount != $params['prevContribution']->total_amount
2913 //Update Financial Records
2914 $params['trxnParams']['from_financial_account_id'] = NULL;
2915 self
::updateFinancialAccounts($params, 'changedAmount');
2920 // records finanical trxn and entity financial trxn
2921 // also make it available as return value
2922 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2923 $params['entity_id'] = $financialTxn->id
;
2926 // record line items and finacial items
2927 if (empty($params['skipLineItem'])) {
2928 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2931 // create batch entry if batch_id is passed and
2932 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
2933 if (!empty($params['batch_id']) && !empty($financialTxn)) {
2934 $entityParams = array(
2935 'batch_id' => $params['batch_id'],
2936 'entity_table' => 'civicrm_financial_trxn',
2937 'entity_id' => $financialTxn->id
,
2939 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2942 // when a fee is charged
2943 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2944 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2947 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2948 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2950 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2951 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2952 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2954 unset($params['line_item']);
2960 * Update all financial accounts entry.
2962 * @param array $params
2963 * Contribution object, line item array and params for trxn.
2965 * @param string $context
2968 * @param null $skipTrxn
2971 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2972 $itemAmount = $trxnID = NULL;
2973 //get all the statuses
2974 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2975 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2976 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2977 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2978 && $context == 'changePaymentInstrument'
2982 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2983 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2985 if ($context == 'changedStatus') {
2986 //get all the statuses
2987 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2989 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2990 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2991 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2993 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2995 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2996 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2998 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2999 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3000 $params['trxnParams']['to_financial_account_id'] = NULL;
3001 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3003 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3004 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3005 $financialTypeID, $relationTypeId);
3007 $itemAmount = $params['trxnParams']['total_amount'];
3009 elseif ($context == 'changePaymentInstrument') {
3010 if ($params['trxnParams']['total_amount'] < 0) {
3011 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3012 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3013 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3014 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3018 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3019 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3022 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3023 $params['entity_id'] = $trxn->id
;
3025 if ($context == 'changedStatus') {
3026 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3027 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3028 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3030 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3031 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3033 $entityParams = array(
3034 'entity_table' => 'civicrm_financial_item',
3035 'financial_trxn_id' => $trxn->id
,
3037 if (empty($params['line_item'])) {
3039 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3040 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3041 // & this can be removed
3044 foreach ($params['line_item'] as $fieldId => $fields) {
3045 foreach ($fields as $fieldValueId => $fieldValues) {
3047 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3048 2 => array($fieldValues['id'], 'Integer'),
3050 CRM_Core_DAO
::executeQuery($query, $fparams);
3052 1 => array($fieldValues['id'], 'Integer'),
3054 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3055 while ($financialItem->fetch()) {
3056 $entityParams['entity_id'] = $financialItem->id
;
3057 $entityParams['amount'] = $financialItem->amount
;
3058 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3065 if ($context != 'changePaymentInstrument') {
3066 $itemParams['entity_table'] = 'civicrm_line_item';
3067 $trxnIds['id'] = $params['entity_id'];
3068 foreach ($params['line_item'] as $fieldId => $fields) {
3069 foreach ($fields as $fieldValueId => $fieldValues) {
3070 $prevParams['entity_id'] = $fieldValues['id'];
3071 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3073 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3074 if ($params['contribution']->receive_date
) {
3075 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3078 $financialAccount = $prevfinancialItem->financial_account_id
;
3079 if (!empty($params['financial_account_id'])) {
3080 $financialAccount = $params['financial_account_id'];
3083 $currency = $params['prevContribution']->currency
;
3084 if ($params['contribution']->currency
) {
3085 $currency = $params['contribution']->currency
;
3088 if (!empty($params['is_quick_config'])) {
3089 $amount = $itemAmount;
3091 $amount = $params['total_amount'];
3095 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3096 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3100 $amount = $diff * $fieldValues['line_total'];
3103 $itemParams = array(
3104 'transaction_date' => $receiveDate,
3105 'contact_id' => $params['prevContribution']->contact_id
,
3106 'currency' => $currency,
3107 'amount' => $amount,
3108 'description' => $prevfinancialItem->description
,
3109 'status_id' => $prevfinancialItem->status_id
,
3110 'financial_account_id' => $financialAccount,
3111 'entity_table' => 'civicrm_line_item',
3112 'entity_id' => $fieldValues['id'],
3114 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3116 if ($fieldValues['tax_amount']) {
3117 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3118 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3119 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3120 $itemParams['description'] = $taxTerm;
3121 if ($fieldValues['financial_type_id']) {
3122 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3124 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3129 if ($context == 'changeFinancialType') {
3130 $params['skipLineItem'] = FALSE;
3131 foreach ($params['line_item'] as &$lineItems) {
3132 foreach ($lineItems as &$line) {
3133 $line['financial_type_id'] = $params['financial_type_id'];
3140 * Check status validation on update of a contribution.
3142 * @param array $values
3143 * Previous form values before submit.
3145 * @param array $fields
3146 * The input form values.
3148 * @param array $errors
3153 public static function checkStatusValidation($values, &$fields, &$errors) {
3154 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3155 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3156 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3160 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3161 $checkStatus = array(
3162 'Cancelled' => array('Completed', 'Refunded'),
3163 'Completed' => array('Cancelled', 'Refunded'),
3164 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3165 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3166 'Refunded' => array('Cancelled', 'Completed'),
3169 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3170 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3171 1 => $contributionStatuses[$values['contribution_status_id']],
3172 2 => $contributionStatuses[$fields['contribution_status_id']],
3178 * Delete contribution of contact.
3182 * @param int $contactId
3186 public static function deleteContactContribution($contactId) {
3187 $contribution = new CRM_Contribute_DAO_Contribution();
3188 $contribution->contact_id
= $contactId;
3189 $contribution->find();
3190 while ($contribution->fetch()) {
3191 self
::deleteContribution($contribution->id
);
3196 * Get options for a given contribution field.
3197 * @see CRM_Core_DAO::buildOptions
3199 * @param string $fieldName
3200 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3201 * @param array $props whatever is known about this dao object.
3203 * @return array|bool
3205 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3206 $className = __CLASS__
;
3208 switch ($fieldName) {
3209 // This field is not part of this object but the api supports it
3210 case 'payment_processor':
3211 $className = 'CRM_Contribute_BAO_ContributionPage';
3212 // Filter results by contribution page
3213 if (!empty($props['contribution_page_id'])) {
3214 $page = civicrm_api('contribution_page', 'getsingle', array(
3216 'id' => ($props['contribution_page_id']),
3218 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3219 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3223 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3224 case 'honor_type_id':
3225 $className = 'CRM_Contribute_BAO_ContributionSoft';
3226 $fieldName = 'soft_credit_type_id';
3227 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3230 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3234 * Validate financial type.
3238 * @param int $financialTypeId
3239 * Financial Type id.
3241 * @param string $relationName
3243 * @return array|bool
3245 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3246 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3247 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3249 if (!$financialAccount) {
3250 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3257 * Function to record additional payment for partial and refund contributions.
3259 * @param int $contributionId
3260 * is the invoice contribution id (got created after processing participant payment).
3261 * @param array $trxnsData
3262 * to take user provided input of transaction details.
3263 * @param string $paymentType
3264 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3265 * @param int $participantId
3267 * @return null|object
3269 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3270 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3271 $getInfoOf['id'] = $contributionId;
3272 $defaults = array();
3273 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3275 if ($paymentType == 'owed') {
3276 // build params for recording financial trxn entry
3277 $params['contribution'] = $contributionDAO;
3278 $params = array_merge($defaults, $params);
3279 $params['skipLineItem'] = TRUE;
3280 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3281 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3282 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3283 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3286 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3287 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3288 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3290 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3291 if (!empty($trxnId)) {
3292 $trxnId = $trxnId['trxn_id'];
3294 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3295 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3298 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3299 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3300 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3304 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3305 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3306 FROM civicrm_financial_trxn ft
3307 LEFT JOIN civicrm_entity_financial_trxn eft
3308 ON (ft.id = eft.financial_trxn_id)
3309 WHERE eft.entity_table = 'civicrm_contribution'
3310 AND eft.entity_id = {$contributionId}
3311 AND ft.to_financial_account_id != {$toFinancialAccount}
3312 AND ft.status_id = {$statusId}
3314 $query = CRM_Core_DAO
::executeQuery($sql);
3316 $sumOfPayments = $query->sum_of_payments
;
3319 if ($contributionDAO->total_amount
== $sumOfPayments) {
3320 // update contribution status and
3321 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3322 $contributionDAO->contribution_status_id
= $statusId;
3323 $contributionDAO->cancel_date
= 'null';
3324 $contributionDAO->cancel_reason
= NULL;
3325 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3326 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3327 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3328 $contributionDAO->save();
3330 //Change status of financial record too
3331 $financialTrxn->status_id
= $statusId;
3332 $financialTrxn->save();
3334 // note : not using the self::add method,
3335 // the reason because it performs 'status change' related code execution for financial records
3336 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3337 // are coded below i.e. just updating financial_item status to 'Paid'
3339 if ($participantId) {
3340 // update participant status
3341 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3342 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3343 foreach ($ids as $val) {
3344 $participantUpdate['id'] = $val;
3345 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3346 CRM_Event_BAO_Participant
::add($participantUpdate);
3350 // update financial item statuses
3351 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3352 $paidStatus = array_search('Paid', $financialItemStatus);
3354 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3355 $sqlFinancialItemUpdate = "
3356 UPDATE civicrm_financial_item fi
3357 LEFT JOIN civicrm_entity_financial_trxn eft
3358 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3359 SET status_id = {$paidStatus}
3360 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3362 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3365 elseif ($paymentType == 'refund') {
3366 // build params for recording financial trxn entry
3367 $params['contribution'] = $contributionDAO;
3368 $params = array_merge($defaults, $params);
3369 $params['skipLineItem'] = TRUE;
3370 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3371 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3373 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3374 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3375 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3377 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3379 // note : not using the self::add method,
3380 // the reason because it performs 'status change' related code execution for financial records
3381 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3382 // are coded below i.e. just updating financial_item status to 'Paid'
3383 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3385 // add financial item entry
3386 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3387 $getLine['entity_id'] = $contributionDAO->id
;
3388 $getLine['entity_table'] = 'civicrm_contribution';
3389 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3390 if (!empty($lineItemId->id
)) {
3391 $addFinancialEntry = array(
3392 'transaction_date' => $financialTrxn->trxn_date
,
3393 'contact_id' => $contributionDAO->contact_id
,
3394 'amount' => $financialTrxn->total_amount
,
3395 'status_id' => array_search('Paid', $financialItemStatus),
3396 'entity_id' => $lineItemId->id
,
3397 'entity_table' => 'civicrm_line_item',
3399 $trxnIds['id'] = $financialTrxn->id
;
3400 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3402 if ($participantId) {
3403 // update participant status
3404 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3405 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3406 foreach ($ids as $val) {
3407 $participantUpdate['id'] = $val;
3408 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3409 CRM_Event_BAO_Participant
::add($participantUpdate);
3414 // activity creation
3415 if (!empty($financialTrxn)) {
3416 if ($participantId) {
3417 $inputParams['id'] = $participantId;
3420 $component = 'event';
3421 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3422 $entityObj = $entityObj[$participantId];
3424 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3426 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3428 return $financialTrxn;
3434 * @param $activityType
3436 * @param int $contributionId
3438 * @throws CRM_Core_Exception
3440 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3441 if ($component == 'event') {
3442 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3443 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3444 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3445 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3446 $targetCid = $entityObj->contact_id
;
3447 // source record id would be the contribution id
3448 $srcRecId = $contributionId;
3452 $activityParams = array(
3453 'source_contact_id' => $targetCid,
3454 'source_record_id' => $srcRecId,
3455 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3459 'subject' => $subject,
3460 'activity_date_time' => $date,
3461 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3465 'skipRecentView' => TRUE,
3468 // create activity with target contacts
3469 $session = CRM_Core_Session
::singleton();
3470 $id = $session->get('userID');
3472 $activityParams['source_contact_id'] = $id;
3473 $activityParams['target_contact_id'][] = $targetCid;
3475 CRM_Activity_BAO_Activity
::create($activityParams);
3479 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3483 * @param bool $getTrxnInfo
3484 * @param bool $usingLineTotal
3488 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3489 if ($component == 'event') {
3490 $entity = 'participant';
3491 $entityTable = 'civicrm_participant';
3492 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3494 if (!$contributionId) {
3495 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3496 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3497 $id = $primaryParticipantId;
3499 if (!$contributionId) {
3504 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3505 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3511 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3512 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3515 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3516 // for additional participants
3517 if ($entityTable == 'civicrm_participant') {
3518 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3520 foreach ($ids as $val) {
3521 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3525 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3529 $baseTrxnId = $total['trxn_id'];
3530 $total = $total['total_amount'];
3533 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3534 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3536 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3537 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3538 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3540 if ($paymentBalance == 0 && $contributionIsPayLater) {
3541 $paymentBalance = $total;
3544 $info['total'] = $total;
3545 $info['paid'] = $total - $paymentBalance;
3546 $info['balance'] = $paymentBalance;
3548 $info['component'] = $component;
3549 $info['payLater'] = $contributionIsPayLater;
3551 if ($getTrxnInfo && $baseTrxnId) {
3552 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3554 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3555 FROM civicrm_contribution con
3556 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3557 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3558 WHERE con.id = {$contributionId}
3561 // conditioned WHERE clause
3563 // if balance trxn exists don't include details of it in transaction info
3564 $sql .= " AND ft.id != {$baseTrxnId} ";
3566 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3568 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3569 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3570 while ($resultDAO->fetch()) {
3571 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3572 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3574 'total_amount' => $resultDAO->total_amount
,
3575 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3576 'payment_instrument' => $paidByLabel,
3577 'receive_date' => $resultDAO->trxn_date
,
3578 'trxn_id' => $resultDAO->trxn_id
,
3579 'status' => $statuses[$resultDAO->status_id
],
3581 if ($paidByName == 'Check') {
3582 $val['check_number'] = $resultDAO->check_number
;
3586 $info['transaction'] = $rows;
3592 * Get financial account id has 'Sales Tax Account is'
3593 * account relationship with financial type
3595 * @param int $financialTypeId
3597 * @return FinancialAccountId
3599 public static function getFinancialAccountId($financialTypeId) {
3600 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3601 $searchParams = array(
3602 'entity_table' => 'civicrm_financial_type',
3603 'entity_id' => $financialTypeId,
3604 'account_relationship' => $accountRel,
3607 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3609 return CRM_Utils_Array
::value('financial_account_id', $result);
3615 * @param array $params
3616 * @param bool $isLineItem
3620 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3621 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3623 // Update contribution.
3624 if (!empty($params['id'])) {
3625 $id = $params['id'];
3626 $values = $ids = array();
3627 $contrbutionParams = array('id' => $id);
3628 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3630 // To assign pervious finantial type on update of contribution
3631 if (!isset($params['financial_type_id'])) {
3632 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3634 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3635 // Assisn tax Amount on update of contrbution
3636 if (!empty($prevContributionValue->tax_amount
)) {
3637 $params['tax_amount'] = 'null';
3638 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3639 foreach ($params['line_item'] as $setID => $priceField) {
3640 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3641 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3648 // New Contrbution and update of contribution with tax rate financial type
3649 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3650 empty($params['skipLineItem']) && !$isLineItem
3652 $taxRateParams = $taxRates[$params['financial_type_id']];
3653 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3654 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3656 // Get Line Item on update of contribution
3657 if (isset($params['id'])) {
3658 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3661 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3663 foreach ($params['line_item'] as $setID => $priceField) {
3664 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3665 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3668 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3670 elseif (isset($params['api.line_item.create'])) {
3671 // Update total amount of contribution using lineItem
3672 $taxAmountArray = array();
3673 foreach ($params['api.line_item.create'] as $key => $value) {
3674 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3675 $taxRate = $taxRates[$value['financial_type_id']];
3676 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3677 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3680 $params['tax_amount'] = array_sum($taxAmountArray);
3681 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3684 // update line item of contrbution
3685 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3686 $taxRate = $taxRates[$params['financial_type_id']];
3687 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3688 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3695 * Check financial type validation on update of a contribution.
3697 * @param Integer $financialTypeId
3698 * Value of latest Financial Type.
3700 * @param Integer $contributionId
3703 * @param array $errors
3708 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3709 if (!empty($financialTypeId)) {
3710 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3711 if ($oldFinancialTypeId == $financialTypeId) {
3715 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3717 '1' => array($contributionId, 'Integer'),
3719 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3720 if ($result->N
> 1) {
3721 $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.');