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;
163 if ($contributionID && $setPrevContribution) {
164 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
167 if ($contributionID) {
168 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
171 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
173 $contribution = new CRM_Contribute_BAO_Contribution();
174 $contribution->copyValues($params);
176 $contribution->id
= $contributionID;
178 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
179 $config = CRM_Core_Config
::singleton();
180 $contribution->currency
= $config->defaultCurrency
;
183 $result = $contribution->save();
185 // Add financial_trxn details as part of fix for CRM-4724
186 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
187 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
189 //add Account details
190 $params['contribution'] = $contribution;
191 self
::recordFinancialAccounts($params);
193 // reset the group contact cache for this group
194 CRM_Contact_BAO_GroupContactCache
::remove();
196 if ($contributionID) {
197 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
200 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
207 * Get defaults for new entity.
210 public static function getDefaults() {
212 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
213 FALSE, FALSE, FALSE, 'AND is_default = 1')
215 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
220 * Given the list of params in the params array, fetch the object
221 * and store the values in the values array
223 * @param array $params
224 * Input parameters to find object.
225 * @param array $values
226 * Output values of the object.
228 * The array that holds all the db ids.
230 * @return CRM_Contribute_BAO_Contribution|null the found object or null
232 public static function &getValues($params, &$values, &$ids) {
233 if (empty($params)) {
236 $contribution = new CRM_Contribute_BAO_Contribution();
238 $contribution->copyValues($params);
240 if ($contribution->find(TRUE)) {
241 $ids['contribution'] = $contribution->id
;
243 CRM_Core_DAO
::storeValues($contribution, $values);
245 return $contribution;
247 $null = NULL; // return by reference
252 * Calculate net_amount & fee_amount if they are not set.
254 * Net amount should be total - fee.
255 * This should only be called for new contributions.
257 * @param array $params
258 * Params for a new contribution before they are saved.
260 public static function calculateMissingAmountParams(&$params) {
261 if (!isset($params['fee_amount'])) {
262 if (isset($params['total_amount']) && isset($params['net_amount'])) {
263 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
266 $params['fee_amount'] = 0;
269 if (!isset($params['net_amount'])) {
270 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
275 * Get the number of terms for this contribution for a given membership type
276 * based on querying the line item table and relevant price field values
277 * Note that any one contribution should only be able to have one line item relating to a particular membership
280 * @param int $membershipTypeID
282 * @param int $contributionID
286 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
287 $numTerms = CRM_Core_DAO
::singleValueQuery("
288 SELECT membership_num_terms FROM civicrm_line_item li
289 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
290 WHERE contribution_id = %1 AND membership_type_id = %2",
291 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
293 // default of 1 is precautionary
294 return empty($numTerms) ?
1 : $numTerms;
298 * Takes an associative array and creates a contribution object.
300 * @param array $params
301 * (reference ) an assoc array of name/value pairs.
303 * The array that holds all the db ids.
305 * @return CRM_Contribute_BAO_Contribution
307 public static function create(&$params, $ids = array()) {
308 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
309 foreach ($dateFields as $df) {
310 if (isset($params[$df])) {
311 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
315 $transaction = new CRM_Core_Transaction();
317 $contribution = self
::add($params, $ids);
319 if (is_a($contribution, 'CRM_Core_Error')) {
320 $transaction->rollback();
321 return $contribution;
324 $params['contribution_id'] = $contribution->id
;
326 if (!empty($params['custom']) &&
327 is_array($params['custom'])
329 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
332 $session = CRM_Core_Session
::singleton();
334 if (!empty($params['note'])) {
336 'entity_table' => 'civicrm_contribution',
337 'note' => $params['note'],
338 'entity_id' => $contribution->id
,
339 'contact_id' => $session->get('userID'),
340 'modified_date' => date('Ymd'),
342 if (!$noteParams['contact_id']) {
343 $noteParams['contact_id'] = $params['contact_id'];
345 CRM_Core_BAO_Note
::add($noteParams);
348 // make entry in batch entity batch table
349 if (!empty($params['batch_id'])) {
350 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
351 $titleFields = array(
357 $retrieveRequired = 0;
358 foreach ($titleFields as $titleField) {
359 if (!isset($contribution->$titleField)) {
360 $retrieveRequired = 1;
364 if ($retrieveRequired == 1) {
365 $contribution->find(TRUE);
369 // Handle soft credit and / or link to personal campaign page
370 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
372 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
374 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
375 $softParams = array();
376 $softParams['id'] = $pcpId ?
$pcpId : NULL;
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
&& empty($pcpId)) {
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'];
401 foreach ($softParams as $softParam) {
402 if (!empty($softIDs)) {
403 $key = key($softIDs);
404 $softParam['id'] = $softIDs[$key];
405 unset($softIDs[$key]);
407 $softParam['contribution_id'] = $contribution->id
;
408 $softParam['currency'] = $contribution->currency
;
409 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
410 if (empty($softParam['amount'])) {
411 $softParam['amount'] = $contribution->total_amount
;
413 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
416 if (!empty($softIDs)) {
417 foreach ($softIDs as $softID) {
418 if (!in_array($softID, $params['soft_credit_ids'])) {
419 $deleteParams = array('id' => $softID);
420 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
426 $transaction->commit();
428 // check if activity record exist for this contribution, if
430 $activity = new CRM_Activity_DAO_Activity();
431 $activity->source_record_id
= $contribution->id
;
432 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
436 if (!$activity->find(TRUE)) {
437 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
440 // CRM-13237 : if activity record found, update it with campaign id of contribution
441 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
444 // do not add to recent items for import, CRM-4399
445 if (empty($params['skipRecentView'])) {
446 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
447 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
449 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
450 $titleFields = array(
456 $retrieveRequired = 0;
457 foreach ($titleFields as $titleField) {
458 if (!isset($contribution->$titleField)) {
459 $retrieveRequired = 1;
463 if ($retrieveRequired == 1) {
464 $contribution->find(TRUE);
466 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
467 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
469 $recentOther = array();
470 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
471 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
472 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
476 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
477 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
478 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
482 // add the recently created Contribution
483 CRM_Utils_Recent
::add($title,
487 $contribution->contact_id
,
493 return $contribution;
497 * Get the values for pseudoconstants for name->value and reverse.
499 * @param array $defaults
500 * (reference) the default values, some of which need to be resolved.
501 * @param bool $reverse
502 * True if we want to resolve the values in the reverse direction (value -> name).
506 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
507 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
508 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
509 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
510 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
514 * Convert associative array names to values and vice-versa.
516 * This function is used by both the web form layer and the api. Note that
517 * the api needs the name => value conversion, also the view layer typically
518 * requires value => name conversion
520 * @param array $defaults
521 * @param string $property
522 * @param array $lookup
523 * @param bool $reverse
527 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
528 $id = $property . '_id';
530 $src = $reverse ?
$property : $id;
531 $dst = $reverse ?
$id : $property;
533 if (!array_key_exists($src, $defaults)) {
537 $look = $reverse ?
array_flip($lookup) : $lookup;
539 if (is_array($look)) {
540 if (!array_key_exists($defaults[$src], $look)) {
544 $defaults[$dst] = $look[$defaults[$src]];
549 * Retrieve DB object based on input parameters.
551 * It also stores all the retrieved values in the default array.
553 * @param array $params
554 * (reference ) an assoc array of name/value pairs.
555 * @param array $defaults
556 * (reference ) an assoc array to hold the name / value pairs.
557 * in a hierarchical manner
559 * (reference) the array that holds all the db ids.
561 * @return CRM_Contribute_BAO_Contribution
563 public static function retrieve(&$params, &$defaults, &$ids) {
564 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
565 return $contribution;
569 * Combine all the importable fields from the lower levels object.
571 * The ordering is important, since currently we do not have a weight
572 * scheme. Adding weight is super important and should be done in the
573 * next week or so, before this can be called complete.
575 * @param string $contactType
576 * @param bool $status
579 * array of importable Fields
581 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
582 if (!self
::$_importableFields) {
583 if (!self
::$_importableFields) {
584 self
::$_importableFields = array();
588 $fields = array('' => array('title' => ts('- do not import -')));
591 $fields = array('' => array('title' => ts('- Contribution Fields -')));
594 $note = CRM_Core_DAO_Note
::import();
595 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
596 unset($tmpFields['option_value']);
597 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
598 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
600 // Using new Dedupe rule.
602 'contact_type' => $contactType,
603 'used' => 'Unsupervised',
605 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
606 $tmpContactField = array();
607 if (is_array($fieldsArray)) {
608 foreach ($fieldsArray as $value) {
609 //skip if there is no dupe rule
610 if ($value == 'none') {
613 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
618 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
619 $tmpContactField[trim($value)] = $contactFields[trim($value)];
621 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
624 $title = $tmpContactField[trim($value)]['title'];
626 $tmpContactField[trim($value)]['title'] = $title;
630 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
631 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
632 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
633 $fields = array_merge($fields, $tmpContactField);
634 $fields = array_merge($fields, $tmpFields);
635 $fields = array_merge($fields, $note);
636 $fields = array_merge($fields, $optionFields);
637 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
638 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
639 self
::$_importableFields = $fields;
641 return self
::$_importableFields;
647 public static function &exportableFields() {
648 if (!self
::$_exportableFields) {
649 if (!self
::$_exportableFields) {
650 self
::$_exportableFields = array();
653 $impFields = CRM_Contribute_DAO_Contribution
::export();
654 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
655 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
656 $typeField = CRM_Financial_DAO_FinancialType
::export();
657 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
658 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
659 $contributionStatus = array(
660 'contribution_status' => array(
661 'title' => ts('Contribution Status'),
662 'name' => 'contribution_status',
663 'data_type' => CRM_Utils_Type
::T_STRING
,
667 $contributionPage = array(
668 'contribution_page' => array(
669 'title' => ts('Contribution Page'),
670 'name' => 'contribution_page',
671 'where' => 'civicrm_contribution_page.title',
672 'data_type' => CRM_Utils_Type
::T_STRING
,
676 $contributionNote = array(
677 'contribution_note' => array(
678 'title' => ts('Contribution Note'),
679 'name' => 'contribution_note',
680 'data_type' => CRM_Utils_Type
::T_TEXT
,
684 $contributionRecurId = array(
685 'contribution_recur_id' => array(
686 'title' => ts('Recurring Contributions ID'),
687 'name' => 'contribution_recur_id',
688 'where' => 'civicrm_contribution.contribution_recur_id',
689 'data_type' => CRM_Utils_Type
::T_INT
,
693 $extraFields = array(
694 'contribution_batch' => array(
695 'title' => ts('Batch Name'),
699 $softCreditFields = array(
700 'contribution_soft_credit_name' => array(
701 'name' => 'contribution_soft_credit_name',
702 'title' => 'Soft Credit For',
703 'where' => 'civicrm_contact_d.display_name',
704 'data_type' => CRM_Utils_Type
::T_STRING
,
706 'contribution_soft_credit_amount' => array(
707 'name' => 'contribution_soft_credit_amount',
708 'title' => 'Soft Credit Amount',
709 'where' => 'civicrm_contribution_soft.amount',
710 'data_type' => CRM_Utils_Type
::T_MONEY
,
712 'contribution_soft_credit_type' => array(
713 'name' => 'contribution_soft_credit_type',
714 'title' => 'Soft Credit Type',
715 'where' => 'contribution_softcredit_type.label',
716 'data_type' => CRM_Utils_Type
::T_STRING
,
718 'contribution_soft_credit_contribution_id' => array(
719 'name' => 'contribution_soft_credit_contribution_id',
720 'title' => 'Soft Credit For Contribution ID',
721 'where' => 'civicrm_contribution_soft.contribution_id',
722 'data_type' => CRM_Utils_Type
::T_INT
,
726 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
727 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
728 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
731 self
::$_exportableFields = $fields;
734 return self
::$_exportableFields;
738 * @param null $status
739 * @param null $startDate
740 * @param null $endDate
744 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
748 $where[] = 'contribution_status_id = 1';
752 $where[] = 'contribution_status_id = 3';
757 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
760 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
763 $whereCond = implode(' AND ', $where);
766 SELECT sum( total_amount ) as total_amount,
767 count( civicrm_contribution.id ) as total_count,
769 FROM civicrm_contribution
770 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
772 AND ( is_test = 0 OR is_test IS NULL )
773 AND contact.is_deleted = 0
777 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
780 while ($dao->fetch()) {
781 $count +
= $dao->total_count
;
782 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
786 'amount' => implode(', ', $amount),
794 * Delete the indirect records associated with this contribution first.
799 * $results no of deleted Contribution on success, false otherwise
801 public static function deleteContribution($id) {
802 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
804 $transaction = new CRM_Core_Transaction();
807 //delete activity record
809 'source_record_id' => $id,
810 // activity type id for contribution
811 'activity_type_id' => 6,
814 CRM_Activity_BAO_Activity
::deleteActivity($params);
816 //delete billing address if exists for this contribution.
817 self
::deleteAddress($id);
819 //update pledge and pledge payment, CRM-3961
820 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
822 // remove entry from civicrm_price_set_entity, CRM-5095
823 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
824 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
826 // cleanup line items.
827 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
829 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
830 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
832 if ($participantId) {
833 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
836 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
840 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
841 $noteId = key($note);
843 CRM_Core_BAO_Note
::del($noteId, FALSE);
846 $dao = new CRM_Contribute_DAO_Contribution();
849 $results = $dao->delete();
851 $transaction->commit();
853 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
855 // delete the recently created Contribution
856 $contributionRecent = array(
858 'type' => 'Contribution',
860 CRM_Utils_Recent
::del($contributionRecent);
866 * Check if there is a contribution with the same trxn_id or invoice_id.
868 * @param array $input
869 * An assoc array of name/value pairs.
870 * @param array $duplicates
871 * (reference) store ids of duplicate contribs.
875 * true if duplicate, false otherwise
877 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
879 $id = CRM_Utils_Array
::value('id', $input);
881 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
882 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
888 $clause[] = "trxn_id = %1";
889 $input[1] = array($trxn_id, 'String');
893 $clause[] = "invoice_id = %2";
894 $input[2] = array($invoice_id, 'String');
897 if (empty($clause)) {
901 $clause = implode(' OR ', $clause);
903 $clause = "( $clause ) AND id != %3";
904 $input[3] = array($id, 'Integer');
907 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
908 $dao = CRM_Core_DAO
::executeQuery($query, $input);
910 while ($dao->fetch()) {
911 $duplicates[] = $dao->id
;
918 * Takes an associative array and creates a contribution_product object.
920 * the function extract all the params it needs to initialize the create a
921 * contribution_product object. the params array could contain additional unused name/value
924 * @param array $params
925 * (reference) an assoc array of name/value pairs.
927 * @return CRM_Contribute_DAO_ContributionProduct
929 public static function addPremium(&$params) {
930 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
931 $contributionProduct->copyValues($params);
932 return $contributionProduct->save();
936 * Get list of contribution fields for profile.
937 * For now we only allow custom contribution fields to be in
940 * @param bool $addExtraFields
941 * True if special fields needs to be added.
944 * the list of contribution fields
946 public static function getContributionFields($addExtraFields = TRUE) {
947 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
948 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
950 if ($addExtraFields) {
951 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
954 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
956 foreach ($contributionFields as $key => $var) {
957 if ($key == 'contribution_contact_id') {
960 elseif ($key == 'contribution_campaign_id') {
961 $var['title'] = ts('Campaign');
963 $fields[$key] = $var;
966 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
971 * Add extra fields specific to contribution.
973 public static function getSpecialContributionFields() {
974 $extraFields = array(
975 'contribution_soft_credit_name' => array(
976 'name' => 'contribution_soft_credit_name',
977 'title' => 'Soft Credit Name',
978 'headerPattern' => '/^soft_credit_name$/i',
979 'where' => 'civicrm_contact_d.display_name',
981 'contribution_soft_credit_email' => array(
982 'name' => 'contribution_soft_credit_email',
983 'title' => 'Soft Credit Email',
984 'headerPattern' => '/^soft_credit_email$/i',
985 'where' => 'soft_email.email',
987 'contribution_soft_credit_phone' => array(
988 'name' => 'contribution_soft_credit_phone',
989 'title' => 'Soft Credit Phone',
990 'headerPattern' => '/^soft_credit_phone$/i',
991 'where' => 'soft_phone.phone',
993 'contribution_soft_credit_contact_id' => array(
994 'name' => 'contribution_soft_credit_contact_id',
995 'title' => 'Soft Credit Contact ID',
996 'headerPattern' => '/^soft_credit_contact_id$/i',
997 'where' => 'civicrm_contribution_soft.contact_id',
1001 return $extraFields;
1005 * @param int $pageID
1009 public static function getCurrentandGoalAmount($pageID) {
1011 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1012 FROM civicrm_contribution_page p,
1013 civicrm_contribution c
1014 WHERE p.id = c.contribution_page_id
1016 AND c.cancel_date is null
1020 $config = CRM_Core_Config
::singleton();
1021 $params = array(1 => array($pageID, 'Integer'));
1022 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1024 if ($dao->fetch()) {
1025 return array($dao->goal
, $dao->total
);
1028 return array(NULL, NULL);
1033 * Get list of contribution In Honor of contact Ids.
1035 * @param int $honorId
1036 * In Honor of Contact ID.
1039 * list of contribution fields
1042 public static function getHonorContacts($honorId) {
1044 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1045 $honorDAO->contact_id
= $honorId;
1048 $type = CRM_Contribute_PseudoConstant
::financialType();
1050 while ($honorDAO->fetch()) {
1051 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1052 $contributionDAO->id
= $honorDAO->contribution_id
;
1054 if ($contributionDAO->find(TRUE)) {
1055 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1056 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1057 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1058 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1059 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1060 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1061 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1062 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1063 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1071 * Get the sort name of a contact for a particular contribution.
1074 * Id of the contribution.
1076 * @return null|string
1077 * sort name of the contact if found
1079 public static function sortName($id) {
1080 $id = CRM_Utils_Type
::escape($id, 'Integer');
1083 SELECT civicrm_contact.sort_name
1084 FROM civicrm_contribution, civicrm_contact
1085 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1086 AND civicrm_contribution.id = {$id}
1088 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1092 * @param int $contactID
1096 public static function annual($contactID) {
1097 if (is_array($contactID)) {
1098 $contactIDs = implode(',', $contactID);
1101 $contactIDs = $contactID;
1104 $config = CRM_Core_Config
::singleton();
1105 $startDate = $endDate = NULL;
1107 $currentMonth = date('m');
1108 $currentDay = date('d');
1109 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1110 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1111 (int ) $config->fiscalYearStart
['d'] > $currentDay
1114 $year = date('Y') - 1;
1119 $nextYear = $year +
1;
1121 if ($config->fiscalYearStart
) {
1122 if ($config->fiscalYearStart
['M'] < 10) {
1123 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1125 if ($config->fiscalYearStart
['d'] < 10) {
1126 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1128 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1133 $startDate = "$year$monthDay";
1134 $endDate = "$nextYear$monthDay";
1137 SELECT count(*) as count,
1138 sum(total_amount) as amount,
1139 avg(total_amount) as average,
1141 FROM civicrm_contribution b
1142 WHERE b.contact_id IN ( $contactIDs )
1143 AND b.contribution_status_id = 1
1145 AND b.receive_date >= $startDate
1146 AND b.receive_date < $endDate
1149 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1151 $amount = $average = array();
1152 while ($dao->fetch()) {
1153 if ($dao->count
> 0 && $dao->amount
> 0) {
1154 $count +
= $dao->count
;
1155 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1156 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1162 implode(', ', $amount),
1163 implode(', ', $average),
1166 return array(0, 0, 0);
1170 * Check if there is a contribution with the params passed in.
1171 * Used for trxn_id,invoice_id and contribution_id
1173 * @param array $params
1174 * An assoc array of name/value pairs.
1177 * contribution id if success else NULL
1179 public static function checkDuplicateIds($params) {
1180 $dao = new CRM_Contribute_DAO_Contribution();
1184 foreach ($params as $k => $v) {
1186 $clause[] = "$k = '$v'";
1189 $clause = implode(' AND ', $clause);
1190 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1191 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1193 while ($dao->fetch()) {
1201 * Get the contribution details for component export.
1203 * @param int $exportMode
1205 * @param string $componentIds
1212 public static function getContributionDetails($exportMode, $componentIds) {
1213 $paymentDetails = array();
1214 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1216 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1217 $componentSelect = " civicrm_participant_payment.participant_id id";
1218 $additionalClause = "
1219 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1220 AND civicrm_participant_payment.participant_id {$componentClause} )
1223 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1224 $componentSelect = " civicrm_membership_payment.membership_id id";
1225 $additionalClause = "
1226 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1227 AND civicrm_membership_payment.membership_id {$componentClause} )
1230 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1231 $componentSelect = " civicrm_pledge_payment.id id";
1232 $additionalClause = "
1233 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1234 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1238 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1239 trxn_id, {$componentSelect}
1240 FROM civicrm_contribution
1241 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1242 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1243 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1244 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1245 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1246 AND option_group_contribution_status.id = contribution_status.option_group_id )
1250 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1252 while ($dao->fetch()) {
1253 $paymentDetails[$dao->id
] = array(
1254 'total_amount' => $dao->total_amount
,
1255 'contribution_status' => $dao->status
,
1256 'receive_date' => $dao->receive_date
,
1257 'pay_instru' => $dao->payment_instrument
,
1258 'trxn_id' => $dao->trxn_id
,
1262 return $paymentDetails;
1266 * Create address associated with contribution record.
1268 * @param array $params
1269 * @param int $billingLocationTypeID
1274 public static function createAddress(&$params, $billingLocationTypeID) {
1275 $billingFields = array(
1278 'state_province_id',
1283 //build address array
1284 $addressParams = array();
1285 $addressParams['location_type_id'] = $billingLocationTypeID;
1286 $addressParams['is_billing'] = 1;
1288 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1289 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1290 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1291 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1293 foreach ($billingFields as $value) {
1294 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1297 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1299 return $address->id
;
1303 * Delete billing address record related contribution.
1305 * @param int $contributionId
1306 * @param int $contactId
1309 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1311 $contactJoin = NULL;
1313 if ($contributionId) {
1314 $clauses[] = "cc.id = {$contributionId}";
1318 $clauses[] = "cco.id = {$contactId}";
1319 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1322 if (empty($clauses)) {
1323 CRM_Core_Error
::fatal();
1326 $condition = implode(' OR ', $clauses);
1330 FROM civicrm_address ca
1331 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1335 $dao = CRM_Core_DAO
::executeQuery($query);
1337 while ($dao->fetch()) {
1338 $params = array('id' => $dao->id
);
1339 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1344 * This function check online pending contribution associated w/
1345 * Online Event Registration or Online Membership signup.
1347 * @param int $componentId
1348 * Participant/membership id.
1349 * @param string $componentName
1353 * pending contribution id.
1355 public static function checkOnlinePendingContribution($componentId, $componentName) {
1356 $contributionId = NULL;
1357 if (!$componentId ||
1358 !in_array($componentName, array('Event', 'Membership'))
1360 return $contributionId;
1363 if ($componentName == 'Event') {
1364 $idName = 'participant_id';
1365 $componentTable = 'civicrm_participant';
1366 $paymentTable = 'civicrm_participant_payment';
1367 $source = ts('Online Event Registration');
1370 if ($componentName == 'Membership') {
1371 $idName = 'membership_id';
1372 $componentTable = 'civicrm_membership';
1373 $paymentTable = 'civicrm_membership_payment';
1374 $source = ts('Online Contribution');
1377 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1380 SELECT component.id as {$idName},
1381 componentPayment.contribution_id as contribution_id,
1382 contribution.source source,
1383 contribution.contribution_status_id as contribution_status_id,
1384 contribution.is_pay_later as is_pay_later
1385 FROM $componentTable component
1386 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1387 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1388 WHERE component.id = {$componentId}";
1390 $dao = CRM_Core_DAO
::executeQuery($query);
1392 while ($dao->fetch()) {
1393 if ($dao->contribution_id
&&
1394 $dao->is_pay_later
&&
1395 $dao->contribution_status_id
== $pendingStatusId &&
1396 strpos($dao->source
, $source) !== FALSE
1398 $contributionId = $dao->contribution_id
;
1403 return $contributionId;
1407 * Update contribution as well as related objects.
1409 * @param array $params
1410 * @param bool $processContributionObject
1413 * @throws \Exception
1415 public static function transitionComponents($params, $processContributionObject = FALSE) {
1416 // get minimum required values.
1417 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1418 $componentId = CRM_Utils_Array
::value('component_id', $params);
1419 $componentName = CRM_Utils_Array
::value('componentName', $params);
1420 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1421 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1423 // if we already processed contribution object pass previous status id.
1424 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1426 $updateResult = array();
1428 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1430 // we process only ( Completed, Cancelled, or Failed ) contributions.
1431 if (!$contributionId ||
1432 !in_array($contributionStatusId, array(
1433 array_search('Completed', $contributionStatuses),
1434 array_search('Cancelled', $contributionStatuses),
1435 array_search('Failed', $contributionStatuses),
1438 return $updateResult;
1441 if (!$componentName ||
!$componentId) {
1442 // get the related component details.
1443 $componentDetails = self
::getComponentDetails($contributionId);
1446 $componentDetails['contact_id'] = $contactId;
1447 $componentDetails['component'] = $componentName;
1449 if ($componentName == 'event') {
1450 $componentDetails['participant'] = $componentId;
1453 $componentDetails['membership'] = $componentId;
1457 if (!empty($componentDetails['contact_id'])) {
1458 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1464 // do check for required ids.
1465 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1466 return $updateResult;
1469 //now we are ready w/ required ids, start processing.
1471 $baseIPN = new CRM_Core_Payment_BaseIPN();
1473 $input = $ids = $objects = array();
1475 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1476 $ids['contribution'] = $contributionId;
1477 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1478 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1479 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1480 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1481 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1482 $ids['contributionRecur'] = NULL;
1483 $ids['contributionPage'] = NULL;
1485 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1486 CRM_Core_Error
::fatal();
1489 $memberships = &$objects['membership'];
1490 $participant = &$objects['participant'];
1491 $pledgePayment = &$objects['pledge_payment'];
1492 $contribution = &$objects['contribution'];
1494 if ($pledgePayment) {
1495 $pledgePaymentIDs = array();
1496 foreach ($pledgePayment as $key => $object) {
1497 $pledgePaymentIDs[] = $object->id
;
1499 $pledgeID = $pledgePayment[0]->pledge_id
;
1502 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1505 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1506 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1511 // we might want to process contribution object.
1512 $processContribution = FALSE;
1513 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1514 if (is_array($memberships)) {
1515 foreach ($memberships as $membership) {
1517 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1518 $membership->save();
1520 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1521 if ($processContributionObject) {
1522 $processContribution = TRUE;
1529 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1530 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1532 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1533 if ($processContributionObject) {
1534 $processContribution = TRUE;
1538 if ($pledgePayment) {
1539 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1541 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1542 if ($processContributionObject) {
1543 $processContribution = TRUE;
1547 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1548 if (is_array($memberships)) {
1549 foreach ($memberships as $membership) {
1551 $membership->status_id
= array_search('Expired', $membershipStatuses);
1552 $membership->save();
1554 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1555 if ($processContributionObject) {
1556 $processContribution = TRUE;
1562 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1563 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1565 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1566 if ($processContributionObject) {
1567 $processContribution = TRUE;
1571 if ($pledgePayment) {
1572 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1574 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1575 if ($processContributionObject) {
1576 $processContribution = TRUE;
1580 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1582 // only pending contribution related object processed.
1583 if ($previousContriStatusId &&
1584 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1586 // this is case when we already processed contribution object.
1587 return $updateResult;
1589 elseif (!$previousContriStatusId &&
1590 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1592 // this is case when we are going to process contribution object later.
1593 return $updateResult;
1596 if (is_array($memberships)) {
1597 foreach ($memberships as $membership) {
1602 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1603 $membership->membership_type_id
,
1604 $membership->is_test
, $membership->id
1607 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1608 // this picks up membership type changes during renewals
1610 SELECT membership_type_id
1611 FROM civicrm_membership_log
1612 WHERE membership_id=$membership->id
1615 $dao = new CRM_Core_DAO();
1617 if ($dao->fetch()) {
1618 if (!empty($dao->membership_type_id
)) {
1619 $membership->membership_type_id
= $dao->membership_type_id
;
1620 $membership->save();
1623 // else fall back to using current membership type
1626 // Figure out number of terms
1628 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1629 foreach ($lineitems as $lineitem) {
1630 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1631 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1633 // in case membership_num_terms comes through as null or zero
1634 $numterms = $numterms >= 1 ?
$numterms : 1;
1639 // CRM-15735-to update the membership status as per the contribution receive date
1641 if (!empty($params['receive_date'])) {
1642 $joinDate = $params['receive_date'];
1643 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1644 $membership->end_date
,
1645 $membership->join_date
,
1646 $params['receive_date'],
1648 $membership->membership_type_id
,
1651 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1652 $membership->save();
1655 if ($currentMembership) {
1656 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1657 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1658 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1661 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1664 //get the status for membership.
1665 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1667 $dates['join_date'],
1670 $membership->membership_type_id
,
1674 $formattedParams = array(
1675 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1676 array_search('Current', $membershipStatuses)
1678 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1679 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1680 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1683 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1685 $membership->copyValues($formattedParams);
1686 $membership->save();
1688 //updating the membership log
1689 $membershipLog = array();
1690 $membershipLog = $formattedParams;
1691 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1692 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1694 $membershipLog['start_date'] = $logStartDate;
1695 $membershipLog['membership_id'] = $membership->id
;
1696 $membershipLog['modified_id'] = $membership->contact_id
;
1697 $membershipLog['modified_date'] = date('Ymd');
1698 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1700 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1702 //update related Memberships.
1703 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1705 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1708 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1709 if ($processContributionObject) {
1710 $processContribution = TRUE;
1713 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1719 $updatedStatusId = array_search('Registered', $participantStatuses);
1720 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1722 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1723 if ($processContributionObject) {
1724 $processContribution = TRUE;
1728 if ($pledgePayment) {
1729 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1731 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1732 if ($processContributionObject) {
1733 $processContribution = TRUE;
1738 // process contribution object.
1739 if ($processContribution) {
1740 $contributionParams = array();
1747 'payment_instrument_id',
1750 'financial_type_id',
1751 'contribution_status_id',
1752 'non_deductible_amount',
1756 foreach ($fields as $field) {
1757 if (empty($params[$field])) {
1760 $contributionParams[$field] = $params[$field];
1763 $ids = array('contribution' => $contributionId);
1764 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1767 return $updateResult;
1771 * Returns all contribution related object ids.
1773 * @param $contributionId
1777 public static function getComponentDetails($contributionId) {
1778 $componentDetails = $pledgePayment = array();
1779 if (!$contributionId) {
1780 return $componentDetails;
1784 SELECT c.id as contribution_id,
1785 c.contact_id as contact_id,
1786 c.contribution_recur_id,
1787 mp.membership_id as membership_id,
1788 m.membership_type_id as membership_type_id,
1789 pp.participant_id as participant_id,
1790 p.event_id as event_id,
1791 pgp.id as pledge_payment_id
1792 FROM civicrm_contribution c
1793 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1794 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1795 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1796 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1797 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1798 WHERE c.id = $contributionId";
1800 $dao = CRM_Core_DAO
::executeQuery($query);
1801 $componentDetails = array();
1803 while ($dao->fetch()) {
1804 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1805 $componentDetails['contact_id'] = $dao->contact_id
;
1806 if ($dao->event_id
) {
1807 $componentDetails['event'] = $dao->event_id
;
1809 if ($dao->participant_id
) {
1810 $componentDetails['participant'] = $dao->participant_id
;
1812 if ($dao->membership_id
) {
1813 if (!isset($componentDetails['membership'])) {
1814 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1816 $componentDetails['membership'][] = $dao->membership_id
;
1817 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1819 if ($dao->pledge_payment_id
) {
1820 $pledgePayment[] = $dao->pledge_payment_id
;
1822 if ($dao->contribution_recur_id
) {
1823 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1827 if ($pledgePayment) {
1828 $componentDetails['pledge_payment'] = $pledgePayment;
1831 return $componentDetails;
1835 * @param int $contactId
1836 * @param bool $includeSoftCredit
1838 * @return null|string
1840 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1845 $contactContributionsSQL = "
1846 SELECT contribution.id AS id
1847 FROM civicrm_contribution contribution
1848 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1850 $contactSoftCreditContributionsSQL = "
1851 SELECT contribution.id
1852 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1853 ON ( contribution.id = softContribution.contribution_id )
1854 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1855 $query = "SELECT count( x.id ) count FROM ( ";
1856 $query .= $contactContributionsSQL;
1858 if ($includeSoftCredit) {
1859 $query .= " UNION ";
1860 $query .= $contactSoftCreditContributionsSQL;
1865 return CRM_Core_DAO
::singleValueQuery($query);
1869 * Get individual id for onbehalf contribution.
1871 * @param int $contributionId
1873 * @param int $contributorId
1877 * containing organization id and individual id
1879 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1883 if (!$contributionId) {
1887 // fetch contributor id if null
1888 if (!$contributorId) {
1889 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1890 $contributionId, 'contact_id'
1894 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1895 $activityTypeId = array_search('Contribution', $activityTypeIds);
1897 if ($activityTypeId && $contributorId) {
1899 SELECT civicrm_activity_contact.contact_id
1900 FROM civicrm_activity_contact
1901 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1902 WHERE civicrm_activity.activity_type_id = %1
1903 AND civicrm_activity.source_record_id = %2
1904 AND civicrm_activity_contact.record_type_id = %3
1907 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1908 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1911 1 => array($activityTypeId, 'Integer'),
1912 2 => array($contributionId, 'Integer'),
1913 3 => array($sourceID, 'Integer'),
1916 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1918 // for on behalf contribution source is individual and contributor is organization
1919 if ($sourceContactId && $sourceContactId != $contributorId) {
1920 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1921 // get rel type id for employee of relation
1922 foreach ($relationshipTypeIds as $id => $typeVals) {
1923 if ($typeVals['name_a_b'] == 'Employee of') {
1924 $relationshipTypeId = $id;
1929 $rel = new CRM_Contact_DAO_Relationship();
1930 $rel->relationship_type_id
= $relationshipTypeId;
1931 $rel->contact_id_a
= $sourceContactId;
1932 $rel->contact_id_b
= $contributorId;
1933 if ($rel->find(TRUE)) {
1934 $ids['individual_id'] = $rel->contact_id_a
;
1935 $ids['organization_id'] = $rel->contact_id_b
;
1946 public static function getContributionDates() {
1947 $config = CRM_Core_Config
::singleton();
1948 $currentMonth = date('m');
1949 $currentDay = date('d');
1950 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1951 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1952 (int ) $config->fiscalYearStart
['d'] > $currentDay
1955 $year = date('Y') - 1;
1960 $year = array('Y' => $year);
1961 $yearDate = $config->fiscalYearStart
;
1962 $yearDate = array_merge($year, $yearDate);
1963 $yearDate = CRM_Utils_Date
::format($yearDate);
1965 $monthDate = date('Ym') . '01';
1971 'yearDate' => $yearDate,
1972 'monthDate' => $monthDate,
1977 * Load objects relations to contribution object.
1978 * Objects are stored in the $_relatedObjects property
1979 * In the first instance we are just moving functionality from BASEIpn -
1980 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1982 * Note that the unit test for the BaseIPN class tests this function
1984 * @param array $input
1985 * Input as delivered from Payment Processor.
1987 * Ids as Loaded by Payment Processor.
1988 * @param bool $required
1989 * Is Payment processor / contribution page required.
1990 * @param bool $loadAll
1991 * Load all related objects - even where id not passed in? (allows API to call this).
1996 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1998 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1999 if (empty($ids['contact']) && isset($this->contact_id
)) {
2000 $ids['contact'] = $this->contact_id
;
2003 if (empty($this->_component
)) {
2004 if (!empty($ids['event'])) {
2005 $this->_component
= 'event';
2008 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2011 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2012 $contributionType = new CRM_Financial_BAO_FinancialType();
2013 $contributionType->id
= $this->financial_type_id
;
2014 if (!$contributionType->find(TRUE)) {
2015 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2017 if (!empty($ids['contact'])) {
2018 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2019 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2020 $this->_relatedObjects
['contact']->find(TRUE);
2022 $this->_relatedObjects
['contributionType'] = $contributionType;
2024 if ($this->_component
== 'contribute') {
2025 // retrieve the other optional objects first so
2026 // stuff down the line can use this info and do things
2028 //in any case get the memberships associated with the contribution
2029 //because we now support multiple memberships w/ price set
2030 // see if there are any other memberships to be considered for same contribution.
2032 SELECT membership_id
2033 FROM civicrm_membership_payment
2034 WHERE contribution_id = %1 ";
2035 $params = array(1 => array($this->id
, 'Integer'));
2037 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2038 while ($dao->fetch()) {
2039 if ($dao->membership_id
) {
2040 if (!is_array($ids['membership'])) {
2041 $ids['membership'] = array();
2043 $ids['membership'][] = $dao->membership_id
;
2047 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2048 foreach ($ids['membership'] as $id) {
2050 $membership = new CRM_Member_BAO_Membership();
2051 $membership->id
= $id;
2052 if (!$membership->find(TRUE)) {
2053 throw new Exception("Could not find membership record: $id");
2055 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2056 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2057 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2058 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2059 $membership->free();
2064 if (!empty($ids['pledge_payment'])) {
2066 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2067 if (empty($paymentID)) {
2070 $payment = new CRM_Pledge_BAO_PledgePayment();
2071 $payment->id
= $paymentID;
2072 if (!$payment->find(TRUE)) {
2073 throw new Exception("Could not find pledge payment record: " . $paymentID);
2075 $this->_relatedObjects
['pledge_payment'][] = $payment;
2079 if (!empty($ids['contributionRecur'])) {
2080 $recur = new CRM_Contribute_BAO_ContributionRecur();
2081 $recur->id
= $ids['contributionRecur'];
2082 if (!$recur->find(TRUE)) {
2083 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2085 $this->_relatedObjects
['contributionRecur'] = &$recur;
2086 //get payment processor id from recur object.
2087 $paymentProcessorID = $recur->payment_processor_id
;
2089 //for normal contribution get the payment processor id.
2090 if (!$paymentProcessorID) {
2091 if ($this->contribution_page_id
) {
2092 // get the payment processor id from contribution page
2093 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2094 $this->contribution_page_id
,
2098 //fail to load payment processor id.
2099 elseif (empty($ids['pledge_payment'])) {
2100 $loadObjectSuccess = TRUE;
2102 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2104 return $loadObjectSuccess;
2109 // we are in event mode
2110 // make sure event exists and is valid
2111 $event = new CRM_Event_BAO_Event();
2112 $event->id
= $ids['event'];
2113 if ($ids['event'] &&
2116 throw new Exception("Could not find event: " . $ids['event']);
2119 $this->_relatedObjects
['event'] = &$event;
2121 $participant = new CRM_Event_BAO_Participant();
2122 $participant->id
= $ids['participant'];
2123 if ($ids['participant'] &&
2124 !$participant->find(TRUE)
2126 throw new Exception("Could not find participant: " . $ids['participant']);
2128 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2130 $this->_relatedObjects
['participant'] = &$participant;
2132 if (!$paymentProcessorID) {
2133 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2137 if ($paymentProcessorID) {
2138 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2139 $this->is_test ?
'test' : 'live'
2141 $ids['paymentProcessor'] = $paymentProcessorID;
2142 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2144 elseif ($required) {
2145 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2152 * Create array of message information - ie. return html version, txt version, to field
2154 * @param array $input
2155 * Incoming information.
2156 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2157 * just check presence of recur object but maintaining legacy approach
2160 * IDs of related objects.
2161 * @param array $values
2162 * Any values that may have already been compiled by calling process.
2163 * This is augmented by values 'gathered' by gatherMessageValues
2164 * @param bool $recur
2165 * @param bool $returnMessageText
2166 * Distinguishes between whether to send message or return.
2167 * message text. We are working towards this function ALWAYS returning message text & calling
2168 * function doing emails / pdfs with it
2174 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2175 if (empty($this->_relatedObjects
)) {
2176 $this->loadRelatedObjects($input, $ids);
2178 if (empty($this->_component
)) {
2179 $this->_component
= CRM_Utils_Array
::value('component', $input);
2182 //not really sure what params might be passed in but lets merge em into values
2183 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2184 $template = CRM_Core_Smarty
::singleton();
2185 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2186 //what does recur 'mean here - to do with payment processor return functionality but
2187 // what is the importance
2188 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2189 $paymentObject = &CRM_Core_Payment
::singleton(
2190 $this->is_test ?
'test' : 'live',
2191 $this->_relatedObjects
['paymentProcessor']
2194 $entityID = $entity = NULL;
2195 if (isset($ids['contribution'])) {
2196 $entity = 'contribution';
2197 $entityID = $ids['contribution'];
2199 if (!empty($ids['membership'])) {
2200 //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
2201 // 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
2202 // line having loaded an array
2203 $ids['membership'] = (array) $ids['membership'];
2204 $entity = 'membership';
2205 $entityID = $ids['membership'][0];
2208 $url = $paymentObject->subscriptionURL($entityID, $entity);
2209 $template->assign('cancelSubscriptionUrl', $url);
2211 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2212 $template->assign('updateSubscriptionBillingUrl', $url);
2214 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2215 $template->assign('updateSubscriptionUrl', $url);
2217 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2218 //direct mode showing billing block, so use directIPN for temporary
2219 $template->assign('contributeMode', 'directIPN');
2222 // todo remove strtolower - check consistency
2223 if (strtolower($this->_component
) == 'event') {
2224 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2225 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2229 $values['contribution_id'] = $this->id
;
2230 if (!empty($ids['related_contact'])) {
2231 $values['related_contact'] = $ids['related_contact'];
2232 if (isset($ids['onbehalf_dupe_alert'])) {
2233 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2235 $entityBlock = array(
2236 'contact_id' => $ids['contact'],
2237 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2238 'Home', 'id', 'name'
2241 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2242 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2245 if ($this->is_test
) {
2248 if (!empty($this->_relatedObjects
['membership'])) {
2249 foreach ($this->_relatedObjects
['membership'] as $membership) {
2250 if ($membership->id
) {
2251 $values['isMembership'] = TRUE;
2253 // need to set the membership values here
2254 $template->assign('membership_assign', 1);
2255 $template->assign('membership_name',
2256 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2258 $template->assign('mem_start_date', $membership->start_date
);
2259 $template->assign('mem_join_date', $membership->join_date
);
2260 $template->assign('mem_end_date', $membership->end_date
);
2261 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2262 $template->assign('mem_status', $membership_status);
2263 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2264 $template->assign('is_pay_later', 1);
2267 // if separate payment there are two contributions recorded and the
2268 // admin will need to send a receipt for each of them separately.
2269 // we dont link the two in the db (but can potentially infer it if needed)
2270 $template->assign('is_separate_payment', 0);
2272 if ($recur && $paymentObject) {
2273 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2274 $template->assign('cancelSubscriptionUrl', $url);
2275 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2276 $template->assign('updateSubscriptionBillingUrl', $url);
2277 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2278 $template->assign('updateSubscriptionUrl', $url);
2281 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2284 // otherwise if its about sending emails, continue sending without return, as we
2285 // don't want to exit the loop.
2290 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2296 * Gather values for contribution mail - this function has been created
2297 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2298 * Values related to the contribution in question are gathered
2300 * @param array $input
2301 * Input into function (probably from payment processor).
2302 * @param array $values
2304 * The set of ids related to the input.
2308 public function _gatherMessageValues($input, &$values, $ids = array()) {
2309 // set display address of contributor
2310 if ($this->address_id
) {
2311 $addressParams = array('id' => $this->address_id
);
2312 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2313 $addressDetails = array_values($addressDetails);
2314 $values['address'] = $addressDetails[0]['display'];
2316 if ($this->_component
== 'contribute') {
2317 if (isset($this->contribution_page_id
)) {
2318 CRM_Contribute_BAO_ContributionPage
::setValues(
2319 $this->contribution_page_id
,
2322 if ($this->contribution_page_id
) {
2323 // CRM-8254 - override default currency if applicable
2324 $config = CRM_Core_Config
::singleton();
2325 $config->defaultCurrency
= CRM_Utils_Array
::value(
2328 $config->defaultCurrency
2332 // no contribution page -probably back office
2334 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2335 $values['is_email_receipt'] = 1;
2336 $values['title'] = 'Contribution';
2338 // set lineItem for contribution
2340 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2341 if (!empty($lineItem)) {
2342 $itemId = key($lineItem);
2343 foreach ($lineItem as &$eachItem) {
2344 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2345 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2346 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2347 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2350 $values['lineItem'][0] = $lineItem;
2351 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2355 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2359 // if this is onbehalf of contribution then set related contact
2360 if (!empty($relatedContact['individual_id'])) {
2361 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2366 $eventParams = array(
2367 'id' => $this->_relatedObjects
['event']->id
,
2369 $values['event'] = array();
2371 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2373 //get location details
2374 $locationParams = array(
2375 'entity_id' => $this->_relatedObjects
['event']->id
,
2376 'entity_table' => 'civicrm_event',
2378 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2380 $ufJoinParams = array(
2381 'entity_table' => 'civicrm_event',
2382 'entity_id' => $ids['event'],
2383 'module' => 'CiviEvent',
2386 list($custom_pre_id,
2388 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2390 $values['custom_pre_id'] = $custom_pre_id;
2391 $values['custom_post_id'] = $custom_post_ids;
2393 // set lineItem for event contribution
2395 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2396 if (!empty($participantIds)) {
2397 foreach ($participantIds as $pIDs) {
2398 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2399 if (!CRM_Utils_System
::isNull($lineItem)) {
2400 $values['lineItem'][] = $lineItem;
2411 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2412 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2413 * Note we send directly from this function in some cases because it is only partly refactored
2414 * Don't call this function directly as the signature will change
2418 * @param CRM_Core_SMARTY $template
2419 * @param bool $recur
2420 * @param bool $returnMessageText
2424 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2425 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2426 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2427 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2428 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2429 $template->assign('useForMember', TRUE);
2431 //assign honor information to receipt message
2432 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2434 if (isset($softRecord['soft_credit'])) {
2435 //if id of contribution page is present
2436 if (!empty($values['id'])) {
2437 $values['honor'] = array(
2438 'honor_profile_values' => array(),
2439 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2440 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2442 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2444 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2445 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2448 //offline contribution
2449 $softCreditTypes = $softCredits = array();
2450 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2451 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2452 $softCredits[$key] = array(
2453 'Name' => $softCredit['contact_name'],
2454 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2457 $template->assign('softCreditTypes', $softCreditTypes);
2458 $template->assign('softCredits', $softCredits);
2462 $dao = new CRM_Contribute_DAO_ContributionProduct();
2463 $dao->contribution_id
= $this->id
;
2464 if ($dao->find(TRUE)) {
2465 $premiumId = $dao->product_id
;
2466 $template->assign('option', $dao->product_option
);
2468 $productDAO = new CRM_Contribute_DAO_Product();
2469 $productDAO->id
= $premiumId;
2470 $productDAO->find(TRUE);
2471 $template->assign('selectPremium', TRUE);
2472 $template->assign('product_name', $productDAO->name
);
2473 $template->assign('price', $productDAO->price
);
2474 $template->assign('sku', $productDAO->sku
);
2476 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2477 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2478 if (empty($amount) && isset($this->total_amount
)) {
2479 $amount = $this->total_amount
;
2481 $template->assign('amount', $amount);
2482 // add the new contribution values
2483 if (strtolower($this->_component
) == 'contribute') {
2485 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2486 $softDAO->contribution_id
= $this->id
;
2487 if ($softDAO->find(TRUE)) {
2488 $template->assign('pcpBlock', TRUE);
2489 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2490 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2491 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2493 //assign the pcp page title for email subject
2494 $pcpDAO = new CRM_PCP_DAO_PCP();
2495 $pcpDAO->id
= $softDAO->pcp_id
;
2496 if ($pcpDAO->find(TRUE)) {
2497 $template->assign('title', $pcpDAO->title
);
2502 if ($this->financial_type_id
) {
2503 $values['financial_type_id'] = $this->financial_type_id
;
2506 $template->assign('trxn_id', $this->trxn_id
);
2507 $template->assign('receive_date',
2508 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2510 $template->assign('contributeMode', 'notify');
2511 $template->assign('action', $this->is_test ?
1024 : 1);
2512 $template->assign('receipt_text',
2513 CRM_Utils_Array
::value('receipt_text',
2517 $template->assign('is_monetary', 1);
2518 $template->assign('is_recur', (bool) $recur);
2519 $template->assign('currency', $this->currency
);
2520 $template->assign('address', CRM_Utils_Address
::format($input));
2521 if ($this->_component
== 'event') {
2522 $template->assign('title', $values['event']['title']);
2523 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2524 $viewRoles = array();
2525 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2526 $viewRoles[] = $participantRoles[$v];
2528 $values['event']['participant_role'] = implode(', ', $viewRoles);
2529 $template->assign('event', $values['event']);
2530 $template->assign('location', $values['location']);
2531 $template->assign('customPre', $values['custom_pre_id']);
2532 $template->assign('customPost', $values['custom_post_id']);
2535 if ($this->_relatedObjects
['participant']->is_test
) {
2539 $values['params'] = array();
2540 //to get email of primary participant.
2541 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2542 $primaryAmount[] = array(
2543 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2544 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2546 //build an array of cId/pId of participants
2547 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2548 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2549 //send receipt to additional participant if exists
2550 if (count($additionalIDs)) {
2551 $template->assign('isPrimary', 0);
2552 $template->assign('customProfile', NULL);
2553 //set additionalParticipant true
2554 $values['params']['additionalParticipant'] = TRUE;
2555 foreach ($additionalIDs as $pId => $cId) {
2557 //to change the status pending to completed
2558 $additional = new CRM_Event_DAO_Participant();
2559 $additional->id
= $pId;
2560 $additional->contact_id
= $cId;
2561 $additional->find(TRUE);
2562 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2563 $additional->status_id
= 1;
2564 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2565 //if additional participant dont have email
2567 if (!$additionalParticipantInfo) {
2568 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2570 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2571 $primaryAmount[] = array(
2572 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2573 'amount' => $additional->fee_amount
,
2575 $additional->save();
2576 $additional->free();
2577 $template->assign('amount', $amount);
2578 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2582 //build an array of custom profile and assigning it to template
2583 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2585 if (count($customProfile)) {
2586 $template->assign('customProfile', $customProfile);
2589 // for primary contact
2590 $values['params']['additionalParticipant'] = FALSE;
2591 $template->assign('isPrimary', 1);
2592 $template->assign('amount', $primaryAmount);
2593 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2594 if ($this->payment_instrument_id
) {
2595 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2596 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2598 // carry paylater, since we did not created billing,
2599 // so need to pull email from primary location, CRM-4395
2600 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2606 * Check whether payment processor supports
2607 * cancellation of contribution subscription
2609 * @param int $contributionId
2612 * @param bool $isNotCancelled
2616 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2617 $cacheKeyString = "$contributionId";
2618 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2620 static $supportsCancel = array();
2622 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2623 $supportsCancel[$cacheKeyString] = FALSE;
2624 $isCancelled = FALSE;
2626 if ($isNotCancelled) {
2627 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2630 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2631 if (!empty($paymentObject)) {
2632 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2635 return $supportsCancel[$cacheKeyString];
2639 * Check whether subscription is already cancelled.
2641 * @param int $contributionId
2645 * contribution status
2647 public static function isSubscriptionCancelled($contributionId) {
2649 SELECT cr.contribution_status_id
2650 FROM civicrm_contribution_recur cr
2651 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2652 WHERE con.id = %1 LIMIT 1";
2653 $params = array(1 => array($contributionId, 'Integer'));
2654 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2655 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2656 if ($status == 'Cancelled') {
2663 * Create all financial accounts entry.
2665 * @param array $params
2666 * Contribution object, line item array and params for trxn.
2669 * @param array $financialTrxnValues
2671 * @return null|object
2673 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2674 $skipRecords = $update = $return = $isRelatedId = FALSE;
2676 $additionalParticipantId = array();
2677 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2679 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2680 $entityId = $params['participant_id'];
2681 $entityTable = 'civicrm_participant';
2682 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2684 elseif (!empty($params['membership_id'])) {
2685 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2686 // are created off one contribution should be handled elsewhere
2687 $entityId = $params['membership_id'];
2688 $entityTable = 'civicrm_membership';
2691 $entityId = $params['contribution']->id
;
2692 $entityTable = 'civicrm_contribution';
2695 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2696 $isRelatedId = TRUE;
2699 $entityID[] = $entityId;
2700 if (!empty($additionalParticipantId)) {
2701 $entityID +
= $additionalParticipantId;
2703 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2704 if (empty($params['prevContribution'])) {
2711 $statusId = $params['contribution']->contribution_status_id
;
2712 // CRM-13964 partial payment
2713 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2714 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2716 $partialAmtPay = $params['partial_amount_pay'];
2717 $partialAmtTotal = $params['partial_payment_total'];
2719 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2720 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2721 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2722 $params['total_amount'] = $partialAmtPay;
2724 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2725 if (empty($balanceTrxnInfo['trxn_id'])) {
2726 // create new balance transaction record
2727 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2728 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2730 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2731 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2732 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2733 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2734 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2735 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2736 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2737 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2738 $balanceTrxnParams['status_id'] = $statusId;
2739 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2740 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2741 if (!empty($params['payment_processor'])) {
2742 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2744 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2748 // build line item array if its not set in $params
2749 if (empty($params['line_item']) ||
$additionalParticipantId) {
2750 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2753 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2754 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2756 $skipRecords = TRUE;
2757 $pendingStatus = array(
2758 array_search('Pending', $contributionStatuses),
2759 array_search('In Progress', $contributionStatuses),
2761 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2762 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2763 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2765 elseif (!empty($params['payment_processor'])) {
2766 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2768 elseif (!empty($params['payment_instrument_id'])) {
2769 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2772 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2773 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2774 $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);
2777 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2778 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2779 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2782 //build financial transaction params
2783 $trxnParams = array(
2784 'contribution_id' => $params['contribution']->id
,
2785 'to_financial_account_id' => $params['to_financial_account_id'],
2786 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2787 'total_amount' => $totalAmount,
2788 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2789 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2790 'currency' => $params['contribution']->currency
,
2791 'trxn_id' => $params['contribution']->trxn_id
,
2792 'status_id' => $statusId,
2793 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2794 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2797 if (!empty($params['payment_processor'])) {
2798 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2801 if (isset($fromFinancialAccountId)) {
2802 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2805 // consider external values passed for recording transaction entry
2806 if (!empty($financialTrxnValues)) {
2807 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2810 $params['trxnParams'] = $trxnParams;
2812 if (!empty($params['prevContribution'])) {
2813 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2814 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2815 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2816 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2817 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2819 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2820 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2821 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2823 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2824 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2827 //if financial type is changed
2828 if (!empty($params['financial_type_id']) &&
2829 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2831 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2832 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2833 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2834 if ($oldFinancialAccount != $newFinancialAccount) {
2835 $params['total_amount'] = 0;
2836 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2837 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2838 $params['prevContribution']->financial_type_id
, $relationTypeId);
2841 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2842 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2843 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2846 self
::updateFinancialAccounts($params, 'changeFinancialType');
2847 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2848 $params['financial_account_id'] = $newFinancialAccount;
2849 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2850 self
::updateFinancialAccounts($params);
2851 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2855 //Update contribution status
2856 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2857 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2858 if (!empty($params['contribution_status_id']) &&
2859 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2861 //Update Financial Records
2862 self
::updateFinancialAccounts($params, 'changedStatus');
2865 // change Payment Instrument for a Completed contribution
2866 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2867 // instrument is null and now new payment instrument is added along with the payment
2868 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2869 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2870 if (array_key_exists('payment_instrument_id', $params)) {
2871 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2872 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2873 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2875 //check if status is changed from Pending to Completed
2876 // do not update payment instrument changes for Pending to Completed
2877 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2878 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2880 // for all other statuses create new financial records
2881 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2882 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2883 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2886 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2887 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2888 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2890 // for any other payment instrument changes create new financial records
2891 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2892 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2893 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2895 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2896 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2898 // another special case when check number is changed, create new financial records
2899 // create financial trxn with negative amount
2900 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2901 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2902 // create financial trxn with positive amount
2903 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2904 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2905 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2909 //if Change contribution amount
2910 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2911 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2912 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2913 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2914 if (isset($totalAmount) &&
2915 $totalAmount != $params['prevContribution']->total_amount
2917 //Update Financial Records
2918 $params['trxnParams']['from_financial_account_id'] = NULL;
2919 self
::updateFinancialAccounts($params, 'changedAmount');
2924 // records finanical trxn and entity financial trxn
2925 // also make it available as return value
2926 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2927 $params['entity_id'] = $financialTxn->id
;
2930 // record line items and finacial items
2931 if (empty($params['skipLineItem'])) {
2932 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2935 // create batch entry if batch_id is passed and
2936 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
2937 if (!empty($params['batch_id']) && !empty($financialTxn)) {
2938 $entityParams = array(
2939 'batch_id' => $params['batch_id'],
2940 'entity_table' => 'civicrm_financial_trxn',
2941 'entity_id' => $financialTxn->id
,
2943 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2946 // when a fee is charged
2947 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2948 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2951 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2952 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2954 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2955 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2956 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2958 unset($params['line_item']);
2964 * Update all financial accounts entry.
2966 * @param array $params
2967 * Contribution object, line item array and params for trxn.
2969 * @param string $context
2972 * @param null $skipTrxn
2975 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2976 $itemAmount = $trxnID = NULL;
2977 //get all the statuses
2978 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2979 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2980 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2981 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2982 && $context == 'changePaymentInstrument'
2986 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2987 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2989 if ($context == 'changedStatus') {
2990 //get all the statuses
2991 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2993 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2994 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2995 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2997 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2999 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3000 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3002 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3003 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3004 $params['trxnParams']['to_financial_account_id'] = NULL;
3005 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3007 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3008 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3009 $financialTypeID, $relationTypeId);
3011 $itemAmount = $params['trxnParams']['total_amount'];
3013 elseif ($context == 'changePaymentInstrument') {
3014 if ($params['trxnParams']['total_amount'] < 0) {
3015 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3016 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3017 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3018 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3022 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3023 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3026 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3027 $params['entity_id'] = $trxn->id
;
3029 if ($context == 'changedStatus') {
3030 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3031 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3032 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3034 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3035 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3037 $entityParams = array(
3038 'entity_table' => 'civicrm_financial_item',
3039 'financial_trxn_id' => $trxn->id
,
3041 if (empty($params['line_item'])) {
3043 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3044 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3045 // & this can be removed
3048 foreach ($params['line_item'] as $fieldId => $fields) {
3049 foreach ($fields as $fieldValueId => $fieldValues) {
3051 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3052 2 => array($fieldValues['id'], 'Integer'),
3054 CRM_Core_DAO
::executeQuery($query, $fparams);
3056 1 => array($fieldValues['id'], 'Integer'),
3058 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3059 while ($financialItem->fetch()) {
3060 $entityParams['entity_id'] = $financialItem->id
;
3061 $entityParams['amount'] = $financialItem->amount
;
3062 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3069 if ($context != 'changePaymentInstrument') {
3070 $itemParams['entity_table'] = 'civicrm_line_item';
3071 $trxnIds['id'] = $params['entity_id'];
3072 foreach ($params['line_item'] as $fieldId => $fields) {
3073 foreach ($fields as $fieldValueId => $fieldValues) {
3074 $prevParams['entity_id'] = $fieldValues['id'];
3075 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3077 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3078 if ($params['contribution']->receive_date
) {
3079 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3082 $financialAccount = $prevfinancialItem->financial_account_id
;
3083 if (!empty($params['financial_account_id'])) {
3084 $financialAccount = $params['financial_account_id'];
3087 $currency = $params['prevContribution']->currency
;
3088 if ($params['contribution']->currency
) {
3089 $currency = $params['contribution']->currency
;
3092 if (!empty($params['is_quick_config'])) {
3093 $amount = $itemAmount;
3095 $amount = $params['total_amount'];
3099 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3100 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3104 $amount = $diff * $fieldValues['line_total'];
3107 $itemParams = array(
3108 'transaction_date' => $receiveDate,
3109 'contact_id' => $params['prevContribution']->contact_id
,
3110 'currency' => $currency,
3111 'amount' => $amount,
3112 'description' => $prevfinancialItem->description
,
3113 'status_id' => $prevfinancialItem->status_id
,
3114 'financial_account_id' => $financialAccount,
3115 'entity_table' => 'civicrm_line_item',
3116 'entity_id' => $fieldValues['id'],
3118 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3120 if ($fieldValues['tax_amount']) {
3121 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3122 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3123 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3124 $itemParams['description'] = $taxTerm;
3125 if ($fieldValues['financial_type_id']) {
3126 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3128 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3133 if ($context == 'changeFinancialType') {
3134 $params['skipLineItem'] = FALSE;
3135 foreach ($params['line_item'] as &$lineItems) {
3136 foreach ($lineItems as &$line) {
3137 $line['financial_type_id'] = $params['financial_type_id'];
3144 * Check status validation on update of a contribution.
3146 * @param array $values
3147 * Previous form values before submit.
3149 * @param array $fields
3150 * The input form values.
3152 * @param array $errors
3157 public static function checkStatusValidation($values, &$fields, &$errors) {
3158 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3159 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3160 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3164 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3165 $checkStatus = array(
3166 'Cancelled' => array('Completed', 'Refunded'),
3167 'Completed' => array('Cancelled', 'Refunded'),
3168 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3169 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3170 'Refunded' => array('Cancelled', 'Completed'),
3173 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3174 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3175 1 => $contributionStatuses[$values['contribution_status_id']],
3176 2 => $contributionStatuses[$fields['contribution_status_id']],
3182 * Delete contribution of contact.
3186 * @param int $contactId
3190 public static function deleteContactContribution($contactId) {
3191 $contribution = new CRM_Contribute_DAO_Contribution();
3192 $contribution->contact_id
= $contactId;
3193 $contribution->find();
3194 while ($contribution->fetch()) {
3195 self
::deleteContribution($contribution->id
);
3200 * Get options for a given contribution field.
3201 * @see CRM_Core_DAO::buildOptions
3203 * @param string $fieldName
3204 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3205 * @param array $props whatever is known about this dao object.
3207 * @return array|bool
3209 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3210 $className = __CLASS__
;
3212 switch ($fieldName) {
3213 // This field is not part of this object but the api supports it
3214 case 'payment_processor':
3215 $className = 'CRM_Contribute_BAO_ContributionPage';
3216 // Filter results by contribution page
3217 if (!empty($props['contribution_page_id'])) {
3218 $page = civicrm_api('contribution_page', 'getsingle', array(
3220 'id' => ($props['contribution_page_id']),
3222 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3223 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3227 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3228 case 'honor_type_id':
3229 $className = 'CRM_Contribute_BAO_ContributionSoft';
3230 $fieldName = 'soft_credit_type_id';
3231 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3234 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3238 * Validate financial type.
3242 * @param int $financialTypeId
3243 * Financial Type id.
3245 * @param string $relationName
3247 * @return array|bool
3249 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3250 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3251 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3253 if (!$financialAccount) {
3254 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3261 * Function to record additional payment for partial and refund contributions.
3263 * @param int $contributionId
3264 * is the invoice contribution id (got created after processing participant payment).
3265 * @param array $trxnsData
3266 * to take user provided input of transaction details.
3267 * @param string $paymentType
3268 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3269 * @param int $participantId
3271 * @return null|object
3273 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3274 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3275 $getInfoOf['id'] = $contributionId;
3276 $defaults = array();
3277 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3279 if ($paymentType == 'owed') {
3280 // build params for recording financial trxn entry
3281 $params['contribution'] = $contributionDAO;
3282 $params = array_merge($defaults, $params);
3283 $params['skipLineItem'] = TRUE;
3284 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3285 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3286 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3287 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3290 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3291 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3292 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3294 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3295 if (!empty($trxnId)) {
3296 $trxnId = $trxnId['trxn_id'];
3298 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3299 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3302 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3303 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3304 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3308 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3309 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3310 FROM civicrm_financial_trxn ft
3311 LEFT JOIN civicrm_entity_financial_trxn eft
3312 ON (ft.id = eft.financial_trxn_id)
3313 WHERE eft.entity_table = 'civicrm_contribution'
3314 AND eft.entity_id = {$contributionId}
3315 AND ft.to_financial_account_id != {$toFinancialAccount}
3316 AND ft.status_id = {$statusId}
3318 $query = CRM_Core_DAO
::executeQuery($sql);
3320 $sumOfPayments = $query->sum_of_payments
;
3323 if ($contributionDAO->total_amount
== $sumOfPayments) {
3324 // update contribution status and
3325 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3326 $contributionDAO->contribution_status_id
= $statusId;
3327 $contributionDAO->cancel_date
= 'null';
3328 $contributionDAO->cancel_reason
= NULL;
3329 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3330 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3331 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3332 $contributionDAO->save();
3334 //Change status of financial record too
3335 $financialTrxn->status_id
= $statusId;
3336 $financialTrxn->save();
3338 // note : not using the self::add method,
3339 // the reason because it performs 'status change' related code execution for financial records
3340 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3341 // are coded below i.e. just updating financial_item status to 'Paid'
3343 if ($participantId) {
3344 // update participant status
3345 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3346 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3347 foreach ($ids as $val) {
3348 $participantUpdate['id'] = $val;
3349 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3350 CRM_Event_BAO_Participant
::add($participantUpdate);
3354 // update financial item statuses
3355 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3356 $paidStatus = array_search('Paid', $financialItemStatus);
3358 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3359 $sqlFinancialItemUpdate = "
3360 UPDATE civicrm_financial_item fi
3361 LEFT JOIN civicrm_entity_financial_trxn eft
3362 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3363 SET status_id = {$paidStatus}
3364 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3366 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3369 elseif ($paymentType == 'refund') {
3370 // build params for recording financial trxn entry
3371 $params['contribution'] = $contributionDAO;
3372 $params = array_merge($defaults, $params);
3373 $params['skipLineItem'] = TRUE;
3374 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3375 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3377 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3378 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3379 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3381 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3383 // note : not using the self::add method,
3384 // the reason because it performs 'status change' related code execution for financial records
3385 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3386 // are coded below i.e. just updating financial_item status to 'Paid'
3387 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3389 // add financial item entry
3390 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3391 $getLine['entity_id'] = $contributionDAO->id
;
3392 $getLine['entity_table'] = 'civicrm_contribution';
3393 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3394 if (!empty($lineItemId->id
)) {
3395 $addFinancialEntry = array(
3396 'transaction_date' => $financialTrxn->trxn_date
,
3397 'contact_id' => $contributionDAO->contact_id
,
3398 'amount' => $financialTrxn->total_amount
,
3399 'status_id' => array_search('Paid', $financialItemStatus),
3400 'entity_id' => $lineItemId->id
,
3401 'entity_table' => 'civicrm_line_item',
3403 $trxnIds['id'] = $financialTrxn->id
;
3404 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3406 if ($participantId) {
3407 // update participant status
3408 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3409 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3410 foreach ($ids as $val) {
3411 $participantUpdate['id'] = $val;
3412 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3413 CRM_Event_BAO_Participant
::add($participantUpdate);
3418 // activity creation
3419 if (!empty($financialTrxn)) {
3420 if ($participantId) {
3421 $inputParams['id'] = $participantId;
3424 $component = 'event';
3425 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3426 $entityObj = $entityObj[$participantId];
3428 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3430 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3432 return $financialTrxn;
3438 * @param $activityType
3440 * @param int $contributionId
3442 * @throws CRM_Core_Exception
3444 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3445 if ($component == 'event') {
3446 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3447 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3448 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3449 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3450 $targetCid = $entityObj->contact_id
;
3451 // source record id would be the contribution id
3452 $srcRecId = $contributionId;
3456 $activityParams = array(
3457 'source_contact_id' => $targetCid,
3458 'source_record_id' => $srcRecId,
3459 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3463 'subject' => $subject,
3464 'activity_date_time' => $date,
3465 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3469 'skipRecentView' => TRUE,
3472 // create activity with target contacts
3473 $session = CRM_Core_Session
::singleton();
3474 $id = $session->get('userID');
3476 $activityParams['source_contact_id'] = $id;
3477 $activityParams['target_contact_id'][] = $targetCid;
3479 CRM_Activity_BAO_Activity
::create($activityParams);
3483 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3487 * @param bool $getTrxnInfo
3488 * @param bool $usingLineTotal
3492 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3493 if ($component == 'event') {
3494 $entity = 'participant';
3495 $entityTable = 'civicrm_participant';
3496 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3498 if (!$contributionId) {
3499 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3500 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3501 $id = $primaryParticipantId;
3503 if (!$contributionId) {
3508 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3509 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3515 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3516 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3519 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3520 // for additional participants
3521 if ($entityTable == 'civicrm_participant') {
3522 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3524 foreach ($ids as $val) {
3525 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3529 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3533 $baseTrxnId = $total['trxn_id'];
3534 $total = $total['total_amount'];
3537 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3538 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3540 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3541 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3542 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3544 if ($paymentBalance == 0 && $contributionIsPayLater) {
3545 $paymentBalance = $total;
3548 $info['total'] = $total;
3549 $info['paid'] = $total - $paymentBalance;
3550 $info['balance'] = $paymentBalance;
3552 $info['component'] = $component;
3553 $info['payLater'] = $contributionIsPayLater;
3555 if ($getTrxnInfo && $baseTrxnId) {
3556 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3558 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3559 FROM civicrm_contribution con
3560 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3561 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3562 WHERE con.id = {$contributionId}
3565 // conditioned WHERE clause
3567 // if balance trxn exists don't include details of it in transaction info
3568 $sql .= " AND ft.id != {$baseTrxnId} ";
3570 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3572 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3573 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3574 while ($resultDAO->fetch()) {
3575 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3576 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3578 'total_amount' => $resultDAO->total_amount
,
3579 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3580 'payment_instrument' => $paidByLabel,
3581 'receive_date' => $resultDAO->trxn_date
,
3582 'trxn_id' => $resultDAO->trxn_id
,
3583 'status' => $statuses[$resultDAO->status_id
],
3585 if ($paidByName == 'Check') {
3586 $val['check_number'] = $resultDAO->check_number
;
3590 $info['transaction'] = $rows;
3596 * Get financial account id has 'Sales Tax Account is'
3597 * account relationship with financial type
3599 * @param int $financialTypeId
3601 * @return FinancialAccountId
3603 public static function getFinancialAccountId($financialTypeId) {
3604 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3605 $searchParams = array(
3606 'entity_table' => 'civicrm_financial_type',
3607 'entity_id' => $financialTypeId,
3608 'account_relationship' => $accountRel,
3611 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3613 return CRM_Utils_Array
::value('financial_account_id', $result);
3619 * @param array $params
3620 * @param bool $isLineItem
3624 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3625 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3627 // Update contribution.
3628 if (!empty($params['id'])) {
3629 $id = $params['id'];
3630 $values = $ids = array();
3631 $contrbutionParams = array('id' => $id);
3632 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3634 // To assign pervious finantial type on update of contribution
3635 if (!isset($params['financial_type_id'])) {
3636 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3638 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3639 // Assisn tax Amount on update of contrbution
3640 if (!empty($prevContributionValue->tax_amount
)) {
3641 $params['tax_amount'] = 'null';
3642 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3643 foreach ($params['line_item'] as $setID => $priceField) {
3644 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3645 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3652 // New Contrbution and update of contribution with tax rate financial type
3653 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3654 empty($params['skipLineItem']) && !$isLineItem
3656 $taxRateParams = $taxRates[$params['financial_type_id']];
3657 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3658 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3660 // Get Line Item on update of contribution
3661 if (isset($params['id'])) {
3662 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3665 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3667 foreach ($params['line_item'] as $setID => $priceField) {
3668 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3669 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3672 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3674 elseif (isset($params['api.line_item.create'])) {
3675 // Update total amount of contribution using lineItem
3676 $taxAmountArray = array();
3677 foreach ($params['api.line_item.create'] as $key => $value) {
3678 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3679 $taxRate = $taxRates[$value['financial_type_id']];
3680 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3681 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3684 $params['tax_amount'] = array_sum($taxAmountArray);
3685 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3688 // update line item of contrbution
3689 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3690 $taxRate = $taxRates[$params['financial_type_id']];
3691 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3692 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3699 * Check financial type validation on update of a contribution.
3701 * @param Integer $financialTypeId
3702 * Value of latest Financial Type.
3704 * @param Integer $contributionId
3707 * @param array $errors
3712 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3713 if (!empty($financialTypeId)) {
3714 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3715 if ($oldFinancialTypeId == $financialTypeId) {
3719 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3721 '1' => array($contributionId, 'Integer'),
3723 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3724 if ($result->N
> 1) {
3725 $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.');