3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * Static field for all the contribution information that we can potentially import
42 static $_importableFields = NULL;
45 * Static field for all the contribution information that we can potentially export
49 static $_exportableFields = NULL;
52 * Field for all the objects related to this contribution
53 * @var array of objects (e.g membership object, participant object)
55 public $_relatedObjects = array();
58 * Field for the component - either 'event' (participant) or 'contribute'
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
63 * @var string component or event
65 public $_component = NULL;
68 * Possibly obsolete variable.
70 * If you use it please explain why it is set in the create function here.
74 public $trxn_result_code;
79 * @return \CRM_Contribute_DAO_Contribution
83 public function __construct() {
84 parent
::__construct();
88 * Takes an associative array and creates a contribution object.
90 * the function extract all the params it needs to initialize the create a
91 * contribution object. the params array could contain additional unused name/value
94 * @param array $params
95 * (reference ) an assoc array of name/value pairs.
97 * The array that holds all the db ids.
99 * @return CRM_Contribute_BAO_Contribution|void
101 public static function add(&$params, $ids = array()) {
102 if (empty($params)) {
105 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
106 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
107 $duplicates = array();
108 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
109 $error = CRM_Core_Error
::singleton();
110 $d = implode(', ', $duplicates);
111 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
114 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
119 // first clean up all the money fields
120 $moneyFields = array(
124 'non_deductible_amount',
127 //if priceset is used, no need to cleanup money
128 if (!empty($params['skipCleanMoney'])) {
129 unset($moneyFields[0]);
132 foreach ($moneyFields as $field) {
133 if (isset($params[$field])) {
134 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
138 //set defaults in create mode
139 if (!$contributionID) {
140 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
141 self
::calculateMissingAmountParams($params);
144 if (!empty($params['payment_instrument_id'])) {
145 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
146 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
147 $params['check_number'] = 'null';
151 $setPrevContribution = TRUE;
152 // CRM-13964 partial payment
153 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
154 $partialAmtTotal = $params['partial_payment_total'];
155 $partialAmtPay = $params['partial_amount_pay'];
156 $params['total_amount'] = $partialAmtTotal;
157 if ($partialAmtPay < $partialAmtTotal) {
158 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
159 $params['is_pay_later'] = 0;
160 $setPrevContribution = FALSE;
164 if ($contributionID) {
165 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
168 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
170 $contribution = new CRM_Contribute_BAO_Contribution();
171 $contribution->copyValues($params);
173 $contribution->id
= $contributionID;
175 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
176 $config = CRM_Core_Config
::singleton();
177 $contribution->currency
= $config->defaultCurrency
;
180 if ($contributionID && $setPrevContribution) {
181 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
184 $result = $contribution->save();
186 // Add financial_trxn details as part of fix for CRM-4724
187 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
188 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
190 //add Account details
191 $params['contribution'] = $contribution;
192 self
::recordFinancialAccounts($params);
194 // reset the group contact cache for this group
195 CRM_Contact_BAO_GroupContactCache
::remove();
197 if ($contributionID) {
198 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
201 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
208 * Get defaults for new entity.
211 public static function getDefaults() {
213 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
214 FALSE, FALSE, FALSE, 'AND is_default = 1')
216 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
221 * Given the list of params in the params array, fetch the object
222 * and store the values in the values array
224 * @param array $params
225 * Input parameters to find object.
226 * @param array $values
227 * Output values of the object.
229 * The array that holds all the db ids.
231 * @return CRM_Contribute_BAO_Contribution|null the found object or null
233 public static function &getValues($params, &$values, &$ids) {
234 if (empty($params)) {
237 $contribution = new CRM_Contribute_BAO_Contribution();
239 $contribution->copyValues($params);
241 if ($contribution->find(TRUE)) {
242 $ids['contribution'] = $contribution->id
;
244 CRM_Core_DAO
::storeValues($contribution, $values);
246 return $contribution;
248 $null = NULL; // return by reference
253 * Calculate net_amount & fee_amount if they are not set.
255 * Net amount should be total - fee.
256 * This should only be called for new contributions.
258 * @param array $params
259 * Params for a new contribution before they are saved.
261 public static function calculateMissingAmountParams(&$params) {
262 if (!isset($params['fee_amount'])) {
263 if (isset($params['total_amount']) && isset($params['net_amount'])) {
264 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
267 $params['fee_amount'] = 0;
270 if (!isset($params['net_amount'])) {
271 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
276 * Get the number of terms for this contribution for a given membership type
277 * based on querying the line item table and relevant price field values
278 * Note that any one contribution should only be able to have one line item relating to a particular membership
281 * @param int $membershipTypeID
283 * @param int $contributionID
287 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
288 $numTerms = CRM_Core_DAO
::singleValueQuery("
289 SELECT membership_num_terms FROM civicrm_line_item li
290 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
291 WHERE contribution_id = %1 AND membership_type_id = %2",
292 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
294 // default of 1 is precautionary
295 return empty($numTerms) ?
1 : $numTerms;
299 * Takes an associative array and creates a contribution object.
301 * @param array $params
302 * (reference ) an assoc array of name/value pairs.
304 * The array that holds all the db ids.
306 * @return CRM_Contribute_BAO_Contribution
308 public static function create(&$params, $ids = array()) {
309 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
310 foreach ($dateFields as $df) {
311 if (isset($params[$df])) {
312 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
316 $transaction = new CRM_Core_Transaction();
318 $contribution = self
::add($params, $ids);
320 if (is_a($contribution, 'CRM_Core_Error')) {
321 $transaction->rollback();
322 return $contribution;
325 $params['contribution_id'] = $contribution->id
;
327 if (!empty($params['custom']) &&
328 is_array($params['custom'])
330 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
333 $session = CRM_Core_Session
::singleton();
335 if (!empty($params['note'])) {
337 'entity_table' => 'civicrm_contribution',
338 'note' => $params['note'],
339 'entity_id' => $contribution->id
,
340 'contact_id' => $session->get('userID'),
341 'modified_date' => date('Ymd'),
343 if (!$noteParams['contact_id']) {
344 $noteParams['contact_id'] = $params['contact_id'];
346 CRM_Core_BAO_Note
::add($noteParams);
349 // make entry in batch entity batch table
350 if (!empty($params['batch_id'])) {
351 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
352 $titleFields = array(
358 $retrieveRequired = 0;
359 foreach ($titleFields as $titleField) {
360 if (!isset($contribution->$titleField)) {
361 $retrieveRequired = 1;
365 if ($retrieveRequired == 1) {
366 $contribution->find(TRUE);
370 // Handle soft credit and / or link to personal campaign page
371 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
373 //Delete PCP against this contribution and create new on submitted PCP information
374 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
376 $deleteParams = array('id' => $pcpId);
377 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
379 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
380 $softParams = array();
381 $softParams['contribution_id'] = $contribution->id
;
382 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
383 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
384 $pcp['pcp_made_through_id'], 'contact_id'
386 $softParams['currency'] = $contribution->currency
;
387 $softParams['amount'] = $contribution->total_amount
;
388 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
389 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
390 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
391 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
392 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
393 //Send notification to owner for PCP
394 if ($contributionSoft->pcp_id
&& empty($pcpId)) {
395 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
398 if (isset($params['soft_credit'])) {
399 $softParams = $params['soft_credit'];
401 if (!empty($softIDs)) {
402 foreach ($softIDs as $softID) {
403 if (!in_array($softID, $params['soft_credit_ids'])) {
404 $deleteParams = array('id' => $softID);
405 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
410 foreach ($softParams as $softParam) {
411 $softParam['contribution_id'] = $contribution->id
;
412 $softParam['currency'] = $contribution->currency
;
413 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
414 if (empty($softParam['amount'])) {
415 $softParam['amount'] = $contribution->total_amount
;
417 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
421 $transaction->commit();
423 // check if activity record exist for this contribution, if
425 $activity = new CRM_Activity_DAO_Activity();
426 $activity->source_record_id
= $contribution->id
;
427 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
431 if (!$activity->find(TRUE)) {
432 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
435 // CRM-13237 : if activity record found, update it with campaign id of contribution
436 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
439 // do not add to recent items for import, CRM-4399
440 if (empty($params['skipRecentView'])) {
441 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
442 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
444 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
445 $titleFields = array(
451 $retrieveRequired = 0;
452 foreach ($titleFields as $titleField) {
453 if (!isset($contribution->$titleField)) {
454 $retrieveRequired = 1;
458 if ($retrieveRequired == 1) {
459 $contribution->find(TRUE);
461 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
462 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
464 $recentOther = array();
465 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
466 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
467 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
471 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
472 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
473 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
477 // add the recently created Contribution
478 CRM_Utils_Recent
::add($title,
482 $contribution->contact_id
,
488 return $contribution;
492 * Get the values for pseudoconstants for name->value and reverse.
494 * @param array $defaults
495 * (reference) the default values, some of which need to be resolved.
496 * @param bool $reverse
497 * True if we want to resolve the values in the reverse direction (value -> name).
501 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
502 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
503 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
504 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
505 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
509 * Convert associative array names to values and vice-versa.
511 * This function is used by both the web form layer and the api. Note that
512 * the api needs the name => value conversion, also the view layer typically
513 * requires value => name conversion
515 * @param array $defaults
516 * @param string $property
517 * @param array $lookup
518 * @param bool $reverse
522 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
523 $id = $property . '_id';
525 $src = $reverse ?
$property : $id;
526 $dst = $reverse ?
$id : $property;
528 if (!array_key_exists($src, $defaults)) {
532 $look = $reverse ?
array_flip($lookup) : $lookup;
534 if (is_array($look)) {
535 if (!array_key_exists($defaults[$src], $look)) {
539 $defaults[$dst] = $look[$defaults[$src]];
544 * Retrieve DB object based on input parameters.
546 * It also stores all the retrieved values in the default array.
548 * @param array $params
549 * (reference ) an assoc array of name/value pairs.
550 * @param array $defaults
551 * (reference ) an assoc array to hold the name / value pairs.
552 * in a hierarchical manner
554 * (reference) the array that holds all the db ids.
556 * @return CRM_Contribute_BAO_Contribution
558 public static function retrieve(&$params, &$defaults, &$ids) {
559 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
560 return $contribution;
564 * Combine all the importable fields from the lower levels object.
566 * The ordering is important, since currently we do not have a weight
567 * scheme. Adding weight is super important and should be done in the
568 * next week or so, before this can be called complete.
570 * @param string $contactType
571 * @param bool $status
574 * array of importable Fields
576 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
577 if (!self
::$_importableFields) {
578 if (!self
::$_importableFields) {
579 self
::$_importableFields = array();
583 $fields = array('' => array('title' => ts('- do not import -')));
586 $fields = array('' => array('title' => ts('- Contribution Fields -')));
589 $note = CRM_Core_DAO_Note
::import();
590 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
591 unset($tmpFields['option_value']);
592 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
593 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
595 // Using new Dedupe rule.
597 'contact_type' => $contactType,
598 'used' => 'Unsupervised',
600 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
601 $tmpContactField = array();
602 if (is_array($fieldsArray)) {
603 foreach ($fieldsArray as $value) {
604 //skip if there is no dupe rule
605 if ($value == 'none') {
608 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
613 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
614 $tmpContactField[trim($value)] = $contactFields[trim($value)];
616 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
619 $title = $tmpContactField[trim($value)]['title'];
621 $tmpContactField[trim($value)]['title'] = $title;
625 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
626 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
627 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
628 $fields = array_merge($fields, $tmpContactField);
629 $fields = array_merge($fields, $tmpFields);
630 $fields = array_merge($fields, $note);
631 $fields = array_merge($fields, $optionFields);
632 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
633 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
634 self
::$_importableFields = $fields;
636 return self
::$_importableFields;
642 public static function &exportableFields() {
643 if (!self
::$_exportableFields) {
644 if (!self
::$_exportableFields) {
645 self
::$_exportableFields = array();
648 $impFields = CRM_Contribute_DAO_Contribution
::export();
649 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
650 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
651 $typeField = CRM_Financial_DAO_FinancialType
::export();
652 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
653 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
654 $contributionStatus = array(
655 'contribution_status' => array(
656 'title' => ts('Contribution Status'),
657 'name' => 'contribution_status',
658 'data_type' => CRM_Utils_Type
::T_STRING
,
662 $contributionPage = array(
663 'contribution_page' => array(
664 'title' => ts('Contribution Page'),
665 'name' => 'contribution_page',
666 'where' => 'civicrm_contribution_page.title',
667 'data_type' => CRM_Utils_Type
::T_STRING
,
671 $contributionNote = array(
672 'contribution_note' => array(
673 'title' => ts('Contribution Note'),
674 'name' => 'contribution_note',
675 'data_type' => CRM_Utils_Type
::T_TEXT
,
679 $contributionRecurId = array(
680 'contribution_recur_id' => array(
681 'title' => ts('Recurring Contributions ID'),
682 'name' => 'contribution_recur_id',
683 'where' => 'civicrm_contribution.contribution_recur_id',
684 'data_type' => CRM_Utils_Type
::T_INT
,
688 $extraFields = array(
689 'contribution_batch' => array(
690 'title' => ts('Batch Name'),
694 $softCreditFields = array(
695 'contribution_soft_credit_name' => array(
696 'name' => 'contribution_soft_credit_name',
697 'title' => 'Soft Credit For',
698 'where' => 'civicrm_contact_d.display_name',
699 'data_type' => CRM_Utils_Type
::T_STRING
,
701 'contribution_soft_credit_amount' => array(
702 'name' => 'contribution_soft_credit_amount',
703 'title' => 'Soft Credit Amount',
704 'where' => 'civicrm_contribution_soft.amount',
705 'data_type' => CRM_Utils_Type
::T_MONEY
,
707 'contribution_soft_credit_type' => array(
708 'name' => 'contribution_soft_credit_type',
709 'title' => 'Soft Credit Type',
710 'where' => 'contribution_softcredit_type.label',
711 'data_type' => CRM_Utils_Type
::T_STRING
,
713 'contribution_soft_credit_contribution_id' => array(
714 'name' => 'contribution_soft_credit_contribution_id',
715 'title' => 'Soft Credit For Contribution ID',
716 'where' => 'civicrm_contribution_soft.contribution_id',
717 'data_type' => CRM_Utils_Type
::T_INT
,
721 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
722 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
723 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
726 self
::$_exportableFields = $fields;
729 return self
::$_exportableFields;
733 * @param null $status
734 * @param null $startDate
735 * @param null $endDate
739 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
743 $where[] = 'contribution_status_id = 1';
747 $where[] = 'contribution_status_id = 3';
752 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
755 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
758 $whereCond = implode(' AND ', $where);
761 SELECT sum( total_amount ) as total_amount,
762 count( civicrm_contribution.id ) as total_count,
764 FROM civicrm_contribution
765 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
767 AND ( is_test = 0 OR is_test IS NULL )
768 AND contact.is_deleted = 0
772 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
775 while ($dao->fetch()) {
776 $count +
= $dao->total_count
;
777 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
781 'amount' => implode(', ', $amount),
789 * Delete the indirect records associated with this contribution first.
794 * $results no of deleted Contribution on success, false otherwise
796 public static function deleteContribution($id) {
797 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
799 $transaction = new CRM_Core_Transaction();
802 //delete activity record
804 'source_record_id' => $id,
805 // activity type id for contribution
806 'activity_type_id' => 6,
809 CRM_Activity_BAO_Activity
::deleteActivity($params);
811 //delete billing address if exists for this contribution.
812 self
::deleteAddress($id);
814 //update pledge and pledge payment, CRM-3961
815 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
817 // remove entry from civicrm_price_set_entity, CRM-5095
818 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
819 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
821 // cleanup line items.
822 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
824 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
825 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
827 if ($participantId) {
828 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
831 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
835 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
836 $noteId = key($note);
838 CRM_Core_BAO_Note
::del($noteId, FALSE);
841 $dao = new CRM_Contribute_DAO_Contribution();
844 $results = $dao->delete();
846 $transaction->commit();
848 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
850 // delete the recently created Contribution
851 $contributionRecent = array(
853 'type' => 'Contribution',
855 CRM_Utils_Recent
::del($contributionRecent);
861 * Check if there is a contribution with the same trxn_id or invoice_id.
863 * @param array $input
864 * An assoc array of name/value pairs.
865 * @param array $duplicates
866 * (reference) store ids of duplicate contribs.
870 * true if duplicate, false otherwise
872 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
874 $id = CRM_Utils_Array
::value('id', $input);
876 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
877 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
883 $clause[] = "trxn_id = %1";
884 $input[1] = array($trxn_id, 'String');
888 $clause[] = "invoice_id = %2";
889 $input[2] = array($invoice_id, 'String');
892 if (empty($clause)) {
896 $clause = implode(' OR ', $clause);
898 $clause = "( $clause ) AND id != %3";
899 $input[3] = array($id, 'Integer');
902 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
903 $dao = CRM_Core_DAO
::executeQuery($query, $input);
905 while ($dao->fetch()) {
906 $duplicates[] = $dao->id
;
913 * Takes an associative array and creates a contribution_product object.
915 * the function extract all the params it needs to initialize the create a
916 * contribution_product object. the params array could contain additional unused name/value
919 * @param array $params
920 * (reference) an assoc array of name/value pairs.
922 * @return CRM_Contribute_DAO_ContributionProduct
924 public static function addPremium(&$params) {
925 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
926 $contributionProduct->copyValues($params);
927 return $contributionProduct->save();
931 * Get list of contribution fields for profile.
932 * For now we only allow custom contribution fields to be in
935 * @param bool $addExtraFields
936 * True if special fields needs to be added.
939 * the list of contribution fields
941 public static function getContributionFields($addExtraFields = TRUE) {
942 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
943 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
945 if ($addExtraFields) {
946 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
949 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
951 foreach ($contributionFields as $key => $var) {
952 if ($key == 'contribution_contact_id') {
955 elseif ($key == 'contribution_campaign_id') {
956 $var['title'] = ts('Campaign');
958 $fields[$key] = $var;
961 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
966 * Add extra fields specific to contribution.
968 public static function getSpecialContributionFields() {
969 $extraFields = array(
970 'contribution_soft_credit_name' => array(
971 'name' => 'contribution_soft_credit_name',
972 'title' => 'Soft Credit Name',
973 'headerPattern' => '/^soft_credit_name$/i',
974 'where' => 'civicrm_contact_d.display_name',
976 'contribution_soft_credit_email' => array(
977 'name' => 'contribution_soft_credit_email',
978 'title' => 'Soft Credit Email',
979 'headerPattern' => '/^soft_credit_email$/i',
980 'where' => 'soft_email.email',
982 'contribution_soft_credit_phone' => array(
983 'name' => 'contribution_soft_credit_phone',
984 'title' => 'Soft Credit Phone',
985 'headerPattern' => '/^soft_credit_phone$/i',
986 'where' => 'soft_phone.phone',
988 'contribution_soft_credit_contact_id' => array(
989 'name' => 'contribution_soft_credit_contact_id',
990 'title' => 'Soft Credit Contact ID',
991 'headerPattern' => '/^soft_credit_contact_id$/i',
992 'where' => 'civicrm_contribution_soft.contact_id',
1000 * @param int $pageID
1004 public static function getCurrentandGoalAmount($pageID) {
1006 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1007 FROM civicrm_contribution_page p,
1008 civicrm_contribution c
1009 WHERE p.id = c.contribution_page_id
1011 AND c.cancel_date is null
1015 $config = CRM_Core_Config
::singleton();
1016 $params = array(1 => array($pageID, 'Integer'));
1017 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1019 if ($dao->fetch()) {
1020 return array($dao->goal
, $dao->total
);
1023 return array(NULL, NULL);
1028 * Get list of contribution In Honor of contact Ids.
1030 * @param int $honorId
1031 * In Honor of Contact ID.
1034 * list of contribution fields
1037 public static function getHonorContacts($honorId) {
1039 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1040 $honorDAO->contact_id
= $honorId;
1043 $type = CRM_Contribute_PseudoConstant
::financialType();
1045 while ($honorDAO->fetch()) {
1046 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1047 $contributionDAO->id
= $honorDAO->contribution_id
;
1049 if ($contributionDAO->find(TRUE)) {
1050 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1051 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1052 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1053 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1054 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1055 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1056 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1057 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1058 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1066 * Get the sort name of a contact for a particular contribution.
1069 * Id of the contribution.
1071 * @return null|string
1072 * sort name of the contact if found
1074 public static function sortName($id) {
1075 $id = CRM_Utils_Type
::escape($id, 'Integer');
1078 SELECT civicrm_contact.sort_name
1079 FROM civicrm_contribution, civicrm_contact
1080 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1081 AND civicrm_contribution.id = {$id}
1083 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1087 * @param int $contactID
1091 public static function annual($contactID) {
1092 if (is_array($contactID)) {
1093 $contactIDs = implode(',', $contactID);
1096 $contactIDs = $contactID;
1099 $config = CRM_Core_Config
::singleton();
1100 $startDate = $endDate = NULL;
1102 $currentMonth = date('m');
1103 $currentDay = date('d');
1104 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1105 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1106 (int ) $config->fiscalYearStart
['d'] > $currentDay
1109 $year = date('Y') - 1;
1114 $nextYear = $year +
1;
1116 if ($config->fiscalYearStart
) {
1117 if ($config->fiscalYearStart
['M'] < 10) {
1118 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1120 if ($config->fiscalYearStart
['d'] < 10) {
1121 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1123 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1128 $startDate = "$year$monthDay";
1129 $endDate = "$nextYear$monthDay";
1132 SELECT count(*) as count,
1133 sum(total_amount) as amount,
1134 avg(total_amount) as average,
1136 FROM civicrm_contribution b
1137 WHERE b.contact_id IN ( $contactIDs )
1138 AND b.contribution_status_id = 1
1140 AND b.receive_date >= $startDate
1141 AND b.receive_date < $endDate
1144 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1146 $amount = $average = array();
1147 while ($dao->fetch()) {
1148 if ($dao->count
> 0 && $dao->amount
> 0) {
1149 $count +
= $dao->count
;
1150 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1151 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1157 implode(', ', $amount),
1158 implode(', ', $average),
1161 return array(0, 0, 0);
1165 * Check if there is a contribution with the params passed in.
1166 * Used for trxn_id,invoice_id and contribution_id
1168 * @param array $params
1169 * An assoc array of name/value pairs.
1172 * contribution id if success else NULL
1174 public static function checkDuplicateIds($params) {
1175 $dao = new CRM_Contribute_DAO_Contribution();
1179 foreach ($params as $k => $v) {
1181 $clause[] = "$k = '$v'";
1184 $clause = implode(' AND ', $clause);
1185 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1186 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1188 while ($dao->fetch()) {
1196 * Get the contribution details for component export.
1198 * @param int $exportMode
1200 * @param string $componentIds
1207 public static function getContributionDetails($exportMode, $componentIds) {
1208 $paymentDetails = array();
1209 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1211 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1212 $componentSelect = " civicrm_participant_payment.participant_id id";
1213 $additionalClause = "
1214 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1215 AND civicrm_participant_payment.participant_id {$componentClause} )
1218 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1219 $componentSelect = " civicrm_membership_payment.membership_id id";
1220 $additionalClause = "
1221 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1222 AND civicrm_membership_payment.membership_id {$componentClause} )
1225 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1226 $componentSelect = " civicrm_pledge_payment.id id";
1227 $additionalClause = "
1228 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1229 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1233 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1234 trxn_id, {$componentSelect}
1235 FROM civicrm_contribution
1236 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1237 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1238 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1239 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1240 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1241 AND option_group_contribution_status.id = contribution_status.option_group_id )
1245 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1247 while ($dao->fetch()) {
1248 $paymentDetails[$dao->id
] = array(
1249 'total_amount' => $dao->total_amount
,
1250 'contribution_status' => $dao->status
,
1251 'receive_date' => $dao->receive_date
,
1252 'pay_instru' => $dao->payment_instrument
,
1253 'trxn_id' => $dao->trxn_id
,
1257 return $paymentDetails;
1261 * Create address associated with contribution record.
1263 * @param array $params
1264 * @param int $billingLocationTypeID
1269 public static function createAddress(&$params, $billingLocationTypeID) {
1270 $billingFields = array(
1273 'state_province_id',
1278 //build address array
1279 $addressParams = array();
1280 $addressParams['location_type_id'] = $billingLocationTypeID;
1281 $addressParams['is_billing'] = 1;
1283 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1284 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1285 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1286 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1288 foreach ($billingFields as $value) {
1289 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1292 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1294 return $address->id
;
1298 * Delete billing address record related contribution.
1300 * @param int $contributionId
1301 * @param int $contactId
1304 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1306 $contactJoin = NULL;
1308 if ($contributionId) {
1309 $clauses[] = "cc.id = {$contributionId}";
1313 $clauses[] = "cco.id = {$contactId}";
1314 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1317 if (empty($clauses)) {
1318 CRM_Core_Error
::fatal();
1321 $condition = implode(' OR ', $clauses);
1325 FROM civicrm_address ca
1326 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1330 $dao = CRM_Core_DAO
::executeQuery($query);
1332 while ($dao->fetch()) {
1333 $params = array('id' => $dao->id
);
1334 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1339 * This function check online pending contribution associated w/
1340 * Online Event Registration or Online Membership signup.
1342 * @param int $componentId
1343 * Participant/membership id.
1344 * @param string $componentName
1348 * pending contribution id.
1350 public static function checkOnlinePendingContribution($componentId, $componentName) {
1351 $contributionId = NULL;
1352 if (!$componentId ||
1353 !in_array($componentName, array('Event', 'Membership'))
1355 return $contributionId;
1358 if ($componentName == 'Event') {
1359 $idName = 'participant_id';
1360 $componentTable = 'civicrm_participant';
1361 $paymentTable = 'civicrm_participant_payment';
1362 $source = ts('Online Event Registration');
1365 if ($componentName == 'Membership') {
1366 $idName = 'membership_id';
1367 $componentTable = 'civicrm_membership';
1368 $paymentTable = 'civicrm_membership_payment';
1369 $source = ts('Online Contribution');
1372 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1375 SELECT component.id as {$idName},
1376 componentPayment.contribution_id as contribution_id,
1377 contribution.source source,
1378 contribution.contribution_status_id as contribution_status_id,
1379 contribution.is_pay_later as is_pay_later
1380 FROM $componentTable component
1381 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1382 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1383 WHERE component.id = {$componentId}";
1385 $dao = CRM_Core_DAO
::executeQuery($query);
1387 while ($dao->fetch()) {
1388 if ($dao->contribution_id
&&
1389 $dao->is_pay_later
&&
1390 $dao->contribution_status_id
== $pendingStatusId &&
1391 strpos($dao->source
, $source) !== FALSE
1393 $contributionId = $dao->contribution_id
;
1398 return $contributionId;
1402 * Update contribution as well as related objects.
1404 * @param array $params
1405 * @param bool $processContributionObject
1408 * @throws \Exception
1410 public static function transitionComponents($params, $processContributionObject = FALSE) {
1411 // get minimum required values.
1412 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1413 $componentId = CRM_Utils_Array
::value('component_id', $params);
1414 $componentName = CRM_Utils_Array
::value('componentName', $params);
1415 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1416 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1418 // if we already processed contribution object pass previous status id.
1419 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1421 $updateResult = array();
1423 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1425 // we process only ( Completed, Cancelled, or Failed ) contributions.
1426 if (!$contributionId ||
1427 !in_array($contributionStatusId, array(
1428 array_search('Completed', $contributionStatuses),
1429 array_search('Cancelled', $contributionStatuses),
1430 array_search('Failed', $contributionStatuses),
1433 return $updateResult;
1436 if (!$componentName ||
!$componentId) {
1437 // get the related component details.
1438 $componentDetails = self
::getComponentDetails($contributionId);
1441 $componentDetails['contact_id'] = $contactId;
1442 $componentDetails['component'] = $componentName;
1444 if ($componentName == 'event') {
1445 $componentDetails['participant'] = $componentId;
1448 $componentDetails['membership'] = $componentId;
1452 if (!empty($componentDetails['contact_id'])) {
1453 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1459 // do check for required ids.
1460 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1461 return $updateResult;
1464 //now we are ready w/ required ids, start processing.
1466 $baseIPN = new CRM_Core_Payment_BaseIPN();
1468 $input = $ids = $objects = array();
1470 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1471 $ids['contribution'] = $contributionId;
1472 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1473 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1474 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1475 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1476 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1477 $ids['contributionRecur'] = NULL;
1478 $ids['contributionPage'] = NULL;
1480 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1481 CRM_Core_Error
::fatal();
1484 $memberships = &$objects['membership'];
1485 $participant = &$objects['participant'];
1486 $pledgePayment = &$objects['pledge_payment'];
1487 $contribution = &$objects['contribution'];
1489 if ($pledgePayment) {
1490 $pledgePaymentIDs = array();
1491 foreach ($pledgePayment as $key => $object) {
1492 $pledgePaymentIDs[] = $object->id
;
1494 $pledgeID = $pledgePayment[0]->pledge_id
;
1497 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1500 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1501 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1506 // we might want to process contribution object.
1507 $processContribution = FALSE;
1508 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1509 if (is_array($memberships)) {
1510 foreach ($memberships as $membership) {
1512 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1513 $membership->save();
1515 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1516 if ($processContributionObject) {
1517 $processContribution = TRUE;
1524 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1525 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1527 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1528 if ($processContributionObject) {
1529 $processContribution = TRUE;
1533 if ($pledgePayment) {
1534 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1536 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1537 if ($processContributionObject) {
1538 $processContribution = TRUE;
1542 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1543 if (is_array($memberships)) {
1544 foreach ($memberships as $membership) {
1546 $membership->status_id
= array_search('Expired', $membershipStatuses);
1547 $membership->save();
1549 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1550 if ($processContributionObject) {
1551 $processContribution = TRUE;
1557 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1558 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1560 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1561 if ($processContributionObject) {
1562 $processContribution = TRUE;
1566 if ($pledgePayment) {
1567 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1569 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1570 if ($processContributionObject) {
1571 $processContribution = TRUE;
1575 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1577 // only pending contribution related object processed.
1578 if ($previousContriStatusId &&
1579 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1581 // this is case when we already processed contribution object.
1582 return $updateResult;
1584 elseif (!$previousContriStatusId &&
1585 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1587 // this is case when we are going to process contribution object later.
1588 return $updateResult;
1591 if (is_array($memberships)) {
1592 foreach ($memberships as $membership) {
1597 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1598 $membership->membership_type_id
,
1599 $membership->is_test
, $membership->id
1602 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1603 // this picks up membership type changes during renewals
1605 SELECT membership_type_id
1606 FROM civicrm_membership_log
1607 WHERE membership_id=$membership->id
1610 $dao = new CRM_Core_DAO();
1612 if ($dao->fetch()) {
1613 if (!empty($dao->membership_type_id
)) {
1614 $membership->membership_type_id
= $dao->membership_type_id
;
1615 $membership->save();
1618 // else fall back to using current membership type
1621 // Figure out number of terms
1623 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1624 foreach ($lineitems as $lineitem) {
1625 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1626 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1628 // in case membership_num_terms comes through as null or zero
1629 $numterms = $numterms >= 1 ?
$numterms : 1;
1634 // CRM-15735-to update the membership status as per the contribution receive date
1636 if (!empty($params['receive_date'])) {
1637 $joinDate = $params['receive_date'];
1638 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1639 $membership->end_date
,
1640 $membership->join_date
,
1641 $params['receive_date'],
1643 $membership->membership_type_id
,
1646 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1647 $membership->save();
1650 if ($currentMembership) {
1651 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1652 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1653 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1656 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1659 //get the status for membership.
1660 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1662 $dates['join_date'],
1665 $membership->membership_type_id
,
1669 $formattedParams = array(
1670 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1671 array_search('Current', $membershipStatuses)
1673 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1674 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1675 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1678 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1680 $membership->copyValues($formattedParams);
1681 $membership->save();
1683 //updating the membership log
1684 $membershipLog = array();
1685 $membershipLog = $formattedParams;
1686 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1687 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1689 $membershipLog['start_date'] = $logStartDate;
1690 $membershipLog['membership_id'] = $membership->id
;
1691 $membershipLog['modified_id'] = $membership->contact_id
;
1692 $membershipLog['modified_date'] = date('Ymd');
1693 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1695 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1697 //update related Memberships.
1698 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1700 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1703 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1704 if ($processContributionObject) {
1705 $processContribution = TRUE;
1708 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1714 $updatedStatusId = array_search('Registered', $participantStatuses);
1715 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1717 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1718 if ($processContributionObject) {
1719 $processContribution = TRUE;
1723 if ($pledgePayment) {
1724 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1726 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1727 if ($processContributionObject) {
1728 $processContribution = TRUE;
1733 // process contribution object.
1734 if ($processContribution) {
1735 $contributionParams = array();
1742 'payment_instrument_id',
1745 'financial_type_id',
1746 'contribution_status_id',
1747 'non_deductible_amount',
1751 foreach ($fields as $field) {
1752 if (empty($params[$field])) {
1755 $contributionParams[$field] = $params[$field];
1758 $ids = array('contribution' => $contributionId);
1759 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1762 return $updateResult;
1766 * Returns all contribution related object ids.
1768 * @param $contributionId
1772 public static function getComponentDetails($contributionId) {
1773 $componentDetails = $pledgePayment = array();
1774 if (!$contributionId) {
1775 return $componentDetails;
1779 SELECT c.id as contribution_id,
1780 c.contact_id as contact_id,
1781 c.contribution_recur_id,
1782 mp.membership_id as membership_id,
1783 m.membership_type_id as membership_type_id,
1784 pp.participant_id as participant_id,
1785 p.event_id as event_id,
1786 pgp.id as pledge_payment_id
1787 FROM civicrm_contribution c
1788 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1789 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1790 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1791 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1792 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1793 WHERE c.id = $contributionId";
1795 $dao = CRM_Core_DAO
::executeQuery($query);
1796 $componentDetails = array();
1798 while ($dao->fetch()) {
1799 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1800 $componentDetails['contact_id'] = $dao->contact_id
;
1801 if ($dao->event_id
) {
1802 $componentDetails['event'] = $dao->event_id
;
1804 if ($dao->participant_id
) {
1805 $componentDetails['participant'] = $dao->participant_id
;
1807 if ($dao->membership_id
) {
1808 if (!isset($componentDetails['membership'])) {
1809 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1811 $componentDetails['membership'][] = $dao->membership_id
;
1812 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1814 if ($dao->pledge_payment_id
) {
1815 $pledgePayment[] = $dao->pledge_payment_id
;
1817 if ($dao->contribution_recur_id
) {
1818 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1822 if ($pledgePayment) {
1823 $componentDetails['pledge_payment'] = $pledgePayment;
1826 return $componentDetails;
1830 * @param int $contactId
1831 * @param bool $includeSoftCredit
1833 * @return null|string
1835 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1840 $contactContributionsSQL = "
1841 SELECT contribution.id AS id
1842 FROM civicrm_contribution contribution
1843 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1845 $contactSoftCreditContributionsSQL = "
1846 SELECT contribution.id
1847 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1848 ON ( contribution.id = softContribution.contribution_id )
1849 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1850 $query = "SELECT count( x.id ) count FROM ( ";
1851 $query .= $contactContributionsSQL;
1853 if ($includeSoftCredit) {
1854 $query .= " UNION ";
1855 $query .= $contactSoftCreditContributionsSQL;
1860 return CRM_Core_DAO
::singleValueQuery($query);
1864 * Get individual id for onbehalf contribution.
1866 * @param int $contributionId
1868 * @param int $contributorId
1872 * containing organization id and individual id
1874 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1878 if (!$contributionId) {
1882 // fetch contributor id if null
1883 if (!$contributorId) {
1884 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1885 $contributionId, 'contact_id'
1889 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1890 $activityTypeId = array_search('Contribution', $activityTypeIds);
1892 if ($activityTypeId && $contributorId) {
1894 SELECT civicrm_activity_contact.contact_id
1895 FROM civicrm_activity_contact
1896 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1897 WHERE civicrm_activity.activity_type_id = %1
1898 AND civicrm_activity.source_record_id = %2
1899 AND civicrm_activity_contact.record_type_id = %3
1902 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1903 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1906 1 => array($activityTypeId, 'Integer'),
1907 2 => array($contributionId, 'Integer'),
1908 3 => array($sourceID, 'Integer'),
1911 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1913 // for on behalf contribution source is individual and contributor is organization
1914 if ($sourceContactId && $sourceContactId != $contributorId) {
1915 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1916 // get rel type id for employee of relation
1917 foreach ($relationshipTypeIds as $id => $typeVals) {
1918 if ($typeVals['name_a_b'] == 'Employee of') {
1919 $relationshipTypeId = $id;
1924 $rel = new CRM_Contact_DAO_Relationship();
1925 $rel->relationship_type_id
= $relationshipTypeId;
1926 $rel->contact_id_a
= $sourceContactId;
1927 $rel->contact_id_b
= $contributorId;
1928 if ($rel->find(TRUE)) {
1929 $ids['individual_id'] = $rel->contact_id_a
;
1930 $ids['organization_id'] = $rel->contact_id_b
;
1941 public static function getContributionDates() {
1942 $config = CRM_Core_Config
::singleton();
1943 $currentMonth = date('m');
1944 $currentDay = date('d');
1945 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1946 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1947 (int ) $config->fiscalYearStart
['d'] > $currentDay
1950 $year = date('Y') - 1;
1955 $year = array('Y' => $year);
1956 $yearDate = $config->fiscalYearStart
;
1957 $yearDate = array_merge($year, $yearDate);
1958 $yearDate = CRM_Utils_Date
::format($yearDate);
1960 $monthDate = date('Ym') . '01';
1966 'yearDate' => $yearDate,
1967 'monthDate' => $monthDate,
1972 * Load objects relations to contribution object.
1973 * Objects are stored in the $_relatedObjects property
1974 * In the first instance we are just moving functionality from BASEIpn -
1975 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1977 * Note that the unit test for the BaseIPN class tests this function
1979 * @param array $input
1980 * Input as delivered from Payment Processor.
1982 * Ids as Loaded by Payment Processor.
1983 * @param bool $required
1984 * Is Payment processor / contribution page required.
1985 * @param bool $loadAll
1986 * Load all related objects - even where id not passed in? (allows API to call this).
1991 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1993 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1994 if (empty($ids['contact']) && isset($this->contact_id
)) {
1995 $ids['contact'] = $this->contact_id
;
1998 if (empty($this->_component
)) {
1999 if (!empty($ids['event'])) {
2000 $this->_component
= 'event';
2003 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2006 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
2007 $contributionType = new CRM_Financial_BAO_FinancialType();
2008 $contributionType->id
= $this->financial_type_id
;
2009 if (!$contributionType->find(TRUE)) {
2010 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
2012 if (!empty($ids['contact'])) {
2013 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
2014 $this->_relatedObjects
['contact']->id
= $ids['contact'];
2015 $this->_relatedObjects
['contact']->find(TRUE);
2017 $this->_relatedObjects
['contributionType'] = $contributionType;
2019 if ($this->_component
== 'contribute') {
2020 // retrieve the other optional objects first so
2021 // stuff down the line can use this info and do things
2023 //in any case get the memberships associated with the contribution
2024 //because we now support multiple memberships w/ price set
2025 // see if there are any other memberships to be considered for same contribution.
2027 SELECT membership_id
2028 FROM civicrm_membership_payment
2029 WHERE contribution_id = %1 ";
2030 $params = array(1 => array($this->id
, 'Integer'));
2032 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2033 while ($dao->fetch()) {
2034 if ($dao->membership_id
) {
2035 if (!is_array($ids['membership'])) {
2036 $ids['membership'] = array();
2038 $ids['membership'][] = $dao->membership_id
;
2042 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2043 foreach ($ids['membership'] as $id) {
2045 $membership = new CRM_Member_BAO_Membership();
2046 $membership->id
= $id;
2047 if (!$membership->find(TRUE)) {
2048 throw new Exception("Could not find membership record: $id");
2050 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2051 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2052 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2053 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2054 $membership->free();
2059 if (!empty($ids['pledge_payment'])) {
2061 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2062 if (empty($paymentID)) {
2065 $payment = new CRM_Pledge_BAO_PledgePayment();
2066 $payment->id
= $paymentID;
2067 if (!$payment->find(TRUE)) {
2068 throw new Exception("Could not find pledge payment record: " . $paymentID);
2070 $this->_relatedObjects
['pledge_payment'][] = $payment;
2074 if (!empty($ids['contributionRecur'])) {
2075 $recur = new CRM_Contribute_BAO_ContributionRecur();
2076 $recur->id
= $ids['contributionRecur'];
2077 if (!$recur->find(TRUE)) {
2078 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2080 $this->_relatedObjects
['contributionRecur'] = &$recur;
2081 //get payment processor id from recur object.
2082 $paymentProcessorID = $recur->payment_processor_id
;
2084 //for normal contribution get the payment processor id.
2085 if (!$paymentProcessorID) {
2086 if ($this->contribution_page_id
) {
2087 // get the payment processor id from contribution page
2088 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2089 $this->contribution_page_id
,
2093 //fail to load payment processor id.
2094 elseif (empty($ids['pledge_payment'])) {
2095 $loadObjectSuccess = TRUE;
2097 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2099 return $loadObjectSuccess;
2104 // we are in event mode
2105 // make sure event exists and is valid
2106 $event = new CRM_Event_BAO_Event();
2107 $event->id
= $ids['event'];
2108 if ($ids['event'] &&
2111 throw new Exception("Could not find event: " . $ids['event']);
2114 $this->_relatedObjects
['event'] = &$event;
2116 $participant = new CRM_Event_BAO_Participant();
2117 $participant->id
= $ids['participant'];
2118 if ($ids['participant'] &&
2119 !$participant->find(TRUE)
2121 throw new Exception("Could not find participant: " . $ids['participant']);
2123 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2125 $this->_relatedObjects
['participant'] = &$participant;
2127 if (!$paymentProcessorID) {
2128 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2132 if ($paymentProcessorID) {
2133 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2134 $this->is_test ?
'test' : 'live'
2136 $ids['paymentProcessor'] = $paymentProcessorID;
2137 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2139 elseif ($required) {
2140 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2147 * Create array of message information - ie. return html version, txt version, to field
2149 * @param array $input
2150 * Incoming information.
2151 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2152 * just check presence of recur object but maintaining legacy approach
2155 * IDs of related objects.
2156 * @param array $values
2157 * Any values that may have already been compiled by calling process.
2158 * This is augmented by values 'gathered' by gatherMessageValues
2159 * @param bool $recur
2160 * @param bool $returnMessageText
2161 * Distinguishes between whether to send message or return.
2162 * message text. We are working towards this function ALWAYS returning message text & calling
2163 * function doing emails / pdfs with it
2169 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2170 if (empty($this->_relatedObjects
)) {
2171 $this->loadRelatedObjects($input, $ids);
2173 if (empty($this->_component
)) {
2174 $this->_component
= CRM_Utils_Array
::value('component', $input);
2177 //not really sure what params might be passed in but lets merge em into values
2178 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2179 $template = CRM_Core_Smarty
::singleton();
2180 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2181 //what does recur 'mean here - to do with payment processor return functionality but
2182 // what is the importance
2183 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2184 $paymentObject = &CRM_Core_Payment
::singleton(
2185 $this->is_test ?
'test' : 'live',
2186 $this->_relatedObjects
['paymentProcessor']
2189 $entityID = $entity = NULL;
2190 if (isset($ids['contribution'])) {
2191 $entity = 'contribution';
2192 $entityID = $ids['contribution'];
2194 if (!empty($ids['membership'])) {
2195 //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
2196 // 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
2197 // line having loaded an array
2198 $ids['membership'] = (array) $ids['membership'];
2199 $entity = 'membership';
2200 $entityID = $ids['membership'][0];
2203 $url = $paymentObject->subscriptionURL($entityID, $entity);
2204 $template->assign('cancelSubscriptionUrl', $url);
2206 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2207 $template->assign('updateSubscriptionBillingUrl', $url);
2209 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2210 $template->assign('updateSubscriptionUrl', $url);
2212 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2213 //direct mode showing billing block, so use directIPN for temporary
2214 $template->assign('contributeMode', 'directIPN');
2217 // todo remove strtolower - check consistency
2218 if (strtolower($this->_component
) == 'event') {
2219 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2220 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2224 $values['contribution_id'] = $this->id
;
2225 if (!empty($ids['related_contact'])) {
2226 $values['related_contact'] = $ids['related_contact'];
2227 if (isset($ids['onbehalf_dupe_alert'])) {
2228 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2230 $entityBlock = array(
2231 'contact_id' => $ids['contact'],
2232 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2233 'Home', 'id', 'name'
2236 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2237 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2240 if ($this->is_test
) {
2243 if (!empty($this->_relatedObjects
['membership'])) {
2244 foreach ($this->_relatedObjects
['membership'] as $membership) {
2245 if ($membership->id
) {
2246 $values['isMembership'] = TRUE;
2248 // need to set the membership values here
2249 $template->assign('membership_assign', 1);
2250 $template->assign('membership_name',
2251 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2253 $template->assign('mem_start_date', $membership->start_date
);
2254 $template->assign('mem_join_date', $membership->join_date
);
2255 $template->assign('mem_end_date', $membership->end_date
);
2256 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2257 $template->assign('mem_status', $membership_status);
2258 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2259 $template->assign('is_pay_later', 1);
2262 // if separate payment there are two contributions recorded and the
2263 // admin will need to send a receipt for each of them separately.
2264 // we dont link the two in the db (but can potentially infer it if needed)
2265 $template->assign('is_separate_payment', 0);
2267 if ($recur && $paymentObject) {
2268 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2269 $template->assign('cancelSubscriptionUrl', $url);
2270 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2271 $template->assign('updateSubscriptionBillingUrl', $url);
2272 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2273 $template->assign('updateSubscriptionUrl', $url);
2276 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2279 // otherwise if its about sending emails, continue sending without return, as we
2280 // don't want to exit the loop.
2285 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2291 * Gather values for contribution mail - this function has been created
2292 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2293 * Values related to the contribution in question are gathered
2295 * @param array $input
2296 * Input into function (probably from payment processor).
2297 * @param array $values
2299 * The set of ids related to the input.
2303 public function _gatherMessageValues($input, &$values, $ids = array()) {
2304 // set display address of contributor
2305 if ($this->address_id
) {
2306 $addressParams = array('id' => $this->address_id
);
2307 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2308 $addressDetails = array_values($addressDetails);
2309 $values['address'] = $addressDetails[0]['display'];
2311 if ($this->_component
== 'contribute') {
2312 if (isset($this->contribution_page_id
)) {
2313 CRM_Contribute_BAO_ContributionPage
::setValues(
2314 $this->contribution_page_id
,
2317 if ($this->contribution_page_id
) {
2318 // CRM-8254 - override default currency if applicable
2319 $config = CRM_Core_Config
::singleton();
2320 $config->defaultCurrency
= CRM_Utils_Array
::value(
2323 $config->defaultCurrency
2327 // no contribution page -probably back office
2329 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2330 $values['is_email_receipt'] = 1;
2331 $values['title'] = 'Contribution';
2333 // set lineItem for contribution
2335 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2336 if (!empty($lineItem)) {
2337 $itemId = key($lineItem);
2338 foreach ($lineItem as &$eachItem) {
2339 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2340 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2341 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2342 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2345 $values['lineItem'][0] = $lineItem;
2346 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2350 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2354 // if this is onbehalf of contribution then set related contact
2355 if (!empty($relatedContact['individual_id'])) {
2356 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2361 $eventParams = array(
2362 'id' => $this->_relatedObjects
['event']->id
,
2364 $values['event'] = array();
2366 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2368 //get location details
2369 $locationParams = array(
2370 'entity_id' => $this->_relatedObjects
['event']->id
,
2371 'entity_table' => 'civicrm_event',
2373 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2375 $ufJoinParams = array(
2376 'entity_table' => 'civicrm_event',
2377 'entity_id' => $ids['event'],
2378 'module' => 'CiviEvent',
2381 list($custom_pre_id,
2383 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2385 $values['custom_pre_id'] = $custom_pre_id;
2386 $values['custom_post_id'] = $custom_post_ids;
2388 // set lineItem for event contribution
2390 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2391 if (!empty($participantIds)) {
2392 foreach ($participantIds as $pIDs) {
2393 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2394 if (!CRM_Utils_System
::isNull($lineItem)) {
2395 $values['lineItem'][] = $lineItem;
2406 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2407 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2408 * Note we send directly from this function in some cases because it is only partly refactored
2409 * Don't call this function directly as the signature will change
2413 * @param CRM_Core_SMARTY $template
2414 * @param bool $recur
2415 * @param bool $returnMessageText
2419 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2420 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2421 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2422 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2423 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2424 $template->assign('useForMember', TRUE);
2426 //assign honor information to receipt message
2427 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2429 if (isset($softRecord['soft_credit'])) {
2430 //if id of contribution page is present
2431 if (!empty($values['id'])) {
2432 $values['honor'] = array(
2433 'honor_profile_values' => array(),
2434 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2435 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2437 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2439 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2440 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2443 //offline contribution
2444 $softCreditTypes = $softCredits = array();
2445 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2446 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2447 $softCredits[$key] = array(
2448 'Name' => $softCredit['contact_name'],
2449 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2452 $template->assign('softCreditTypes', $softCreditTypes);
2453 $template->assign('softCredits', $softCredits);
2457 $dao = new CRM_Contribute_DAO_ContributionProduct();
2458 $dao->contribution_id
= $this->id
;
2459 if ($dao->find(TRUE)) {
2460 $premiumId = $dao->product_id
;
2461 $template->assign('option', $dao->product_option
);
2463 $productDAO = new CRM_Contribute_DAO_Product();
2464 $productDAO->id
= $premiumId;
2465 $productDAO->find(TRUE);
2466 $template->assign('selectPremium', TRUE);
2467 $template->assign('product_name', $productDAO->name
);
2468 $template->assign('price', $productDAO->price
);
2469 $template->assign('sku', $productDAO->sku
);
2471 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2472 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2473 if (empty($amount) && isset($this->total_amount
)) {
2474 $amount = $this->total_amount
;
2476 $template->assign('amount', $amount);
2477 // add the new contribution values
2478 if (strtolower($this->_component
) == 'contribute') {
2480 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2481 $softDAO->contribution_id
= $this->id
;
2482 if ($softDAO->find(TRUE)) {
2483 $template->assign('pcpBlock', TRUE);
2484 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2485 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2486 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2488 //assign the pcp page title for email subject
2489 $pcpDAO = new CRM_PCP_DAO_PCP();
2490 $pcpDAO->id
= $softDAO->pcp_id
;
2491 if ($pcpDAO->find(TRUE)) {
2492 $template->assign('title', $pcpDAO->title
);
2497 if ($this->financial_type_id
) {
2498 $values['financial_type_id'] = $this->financial_type_id
;
2501 $template->assign('trxn_id', $this->trxn_id
);
2502 $template->assign('receive_date',
2503 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2505 $template->assign('contributeMode', 'notify');
2506 $template->assign('action', $this->is_test ?
1024 : 1);
2507 $template->assign('receipt_text',
2508 CRM_Utils_Array
::value('receipt_text',
2512 $template->assign('is_monetary', 1);
2513 $template->assign('is_recur', (bool) $recur);
2514 $template->assign('currency', $this->currency
);
2515 $template->assign('address', CRM_Utils_Address
::format($input));
2516 if ($this->_component
== 'event') {
2517 $template->assign('title', $values['event']['title']);
2518 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2519 $viewRoles = array();
2520 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2521 $viewRoles[] = $participantRoles[$v];
2523 $values['event']['participant_role'] = implode(', ', $viewRoles);
2524 $template->assign('event', $values['event']);
2525 $template->assign('location', $values['location']);
2526 $template->assign('customPre', $values['custom_pre_id']);
2527 $template->assign('customPost', $values['custom_post_id']);
2530 if ($this->_relatedObjects
['participant']->is_test
) {
2534 $values['params'] = array();
2535 //to get email of primary participant.
2536 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2537 $primaryAmount[] = array(
2538 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2539 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2541 //build an array of cId/pId of participants
2542 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2543 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2544 //send receipt to additional participant if exists
2545 if (count($additionalIDs)) {
2546 $template->assign('isPrimary', 0);
2547 $template->assign('customProfile', NULL);
2548 //set additionalParticipant true
2549 $values['params']['additionalParticipant'] = TRUE;
2550 foreach ($additionalIDs as $pId => $cId) {
2552 //to change the status pending to completed
2553 $additional = new CRM_Event_DAO_Participant();
2554 $additional->id
= $pId;
2555 $additional->contact_id
= $cId;
2556 $additional->find(TRUE);
2557 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2558 $additional->status_id
= 1;
2559 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2560 //if additional participant dont have email
2562 if (!$additionalParticipantInfo) {
2563 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2565 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2566 $primaryAmount[] = array(
2567 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2568 'amount' => $additional->fee_amount
,
2570 $additional->save();
2571 $additional->free();
2572 $template->assign('amount', $amount);
2573 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2577 //build an array of custom profile and assigning it to template
2578 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2580 if (count($customProfile)) {
2581 $template->assign('customProfile', $customProfile);
2584 // for primary contact
2585 $values['params']['additionalParticipant'] = FALSE;
2586 $template->assign('isPrimary', 1);
2587 $template->assign('amount', $primaryAmount);
2588 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2589 if ($this->payment_instrument_id
) {
2590 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2591 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2593 // carry paylater, since we did not created billing,
2594 // so need to pull email from primary location, CRM-4395
2595 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2601 * Check whether payment processor supports
2602 * cancellation of contribution subscription
2604 * @param int $contributionId
2607 * @param bool $isNotCancelled
2611 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2612 $cacheKeyString = "$contributionId";
2613 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2615 static $supportsCancel = array();
2617 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2618 $supportsCancel[$cacheKeyString] = FALSE;
2619 $isCancelled = FALSE;
2621 if ($isNotCancelled) {
2622 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2625 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2626 if (!empty($paymentObject)) {
2627 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2630 return $supportsCancel[$cacheKeyString];
2634 * Check whether subscription is already cancelled.
2636 * @param int $contributionId
2640 * contribution status
2642 public static function isSubscriptionCancelled($contributionId) {
2644 SELECT cr.contribution_status_id
2645 FROM civicrm_contribution_recur cr
2646 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2647 WHERE con.id = %1 LIMIT 1";
2648 $params = array(1 => array($contributionId, 'Integer'));
2649 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2650 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2651 if ($status == 'Cancelled') {
2658 * Create all financial accounts entry.
2660 * @param array $params
2661 * Contribution object, line item array and params for trxn.
2664 * @param array $financialTrxnValues
2666 * @return null|object
2668 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2669 $skipRecords = $update = $return = $isRelatedId = FALSE;
2671 $additionalParticipantId = array();
2672 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2674 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2675 $entityId = $params['participant_id'];
2676 $entityTable = 'civicrm_participant';
2677 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2679 elseif (!empty($params['membership_id'])) {
2680 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2681 // are created off one contribution should be handled elsewhere
2682 $entityId = $params['membership_id'];
2683 $entityTable = 'civicrm_membership';
2686 $entityId = $params['contribution']->id
;
2687 $entityTable = 'civicrm_contribution';
2690 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2691 $isRelatedId = TRUE;
2694 $entityID[] = $entityId;
2695 if (!empty($additionalParticipantId)) {
2696 $entityID +
= $additionalParticipantId;
2698 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2699 if (empty($params['prevContribution'])) {
2706 $statusId = $params['contribution']->contribution_status_id
;
2707 // CRM-13964 partial payment
2708 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2709 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2711 $partialAmtPay = $params['partial_amount_pay'];
2712 $partialAmtTotal = $params['partial_payment_total'];
2714 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2715 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2716 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2717 $params['total_amount'] = $partialAmtPay;
2719 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2720 if (empty($balanceTrxnInfo['trxn_id'])) {
2721 // create new balance transaction record
2722 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2723 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2725 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2726 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2727 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2728 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
2729 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2730 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2731 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2732 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2733 $balanceTrxnParams['status_id'] = $statusId;
2734 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2735 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2736 if (!empty($params['payment_processor'])) {
2737 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2739 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2743 // build line item array if its not set in $params
2744 if (empty($params['line_item']) ||
$additionalParticipantId) {
2745 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2748 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2749 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2751 $skipRecords = TRUE;
2752 $pendingStatus = array(
2753 array_search('Pending', $contributionStatuses),
2754 array_search('In Progress', $contributionStatuses),
2756 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2757 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2758 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2760 elseif (!empty($params['payment_processor'])) {
2761 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2763 elseif (!empty($params['payment_instrument_id'])) {
2764 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2767 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2768 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2769 $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);
2772 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2773 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2774 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2777 //build financial transaction params
2778 $trxnParams = array(
2779 'contribution_id' => $params['contribution']->id
,
2780 'to_financial_account_id' => $params['to_financial_account_id'],
2781 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
2782 'total_amount' => $totalAmount,
2783 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2784 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
2785 'currency' => $params['contribution']->currency
,
2786 'trxn_id' => $params['contribution']->trxn_id
,
2787 'status_id' => $statusId,
2788 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2789 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2792 if (!empty($params['payment_processor'])) {
2793 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2796 if (isset($fromFinancialAccountId)) {
2797 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2800 // consider external values passed for recording transaction entry
2801 if (!empty($financialTrxnValues)) {
2802 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2805 $params['trxnParams'] = $trxnParams;
2807 if (!empty($params['prevContribution'])) {
2808 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2809 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2810 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2811 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2812 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2814 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2815 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2816 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2818 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2819 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2822 //if financial type is changed
2823 if (!empty($params['financial_type_id']) &&
2824 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2826 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2827 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2828 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2829 if ($oldFinancialAccount != $newFinancialAccount) {
2830 $params['total_amount'] = 0;
2831 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2832 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2833 $params['prevContribution']->financial_type_id
, $relationTypeId);
2836 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2837 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2838 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2841 self
::updateFinancialAccounts($params, 'changeFinancialType');
2842 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2843 $params['financial_account_id'] = $newFinancialAccount;
2844 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2845 self
::updateFinancialAccounts($params);
2846 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2850 //Update contribution status
2851 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2852 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2853 if (!empty($params['contribution_status_id']) &&
2854 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2856 //Update Financial Records
2857 self
::updateFinancialAccounts($params, 'changedStatus');
2860 // change Payment Instrument for a Completed contribution
2861 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2862 // instrument is null and now new payment instrument is added along with the payment
2863 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2864 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2865 if (array_key_exists('payment_instrument_id', $params)) {
2866 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2867 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2868 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2870 //check if status is changed from Pending to Completed
2871 // do not update payment instrument changes for Pending to Completed
2872 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2873 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2875 // for all other statuses create new financial records
2876 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2877 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2878 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2881 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2882 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2883 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2885 // for any other payment instrument changes create new financial records
2886 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2887 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2888 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2890 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2891 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2893 // another special case when check number is changed, create new financial records
2894 // create financial trxn with negative amount
2895 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2896 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2897 // create financial trxn with positive amount
2898 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2899 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2900 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2904 //if Change contribution amount
2905 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2906 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2907 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2908 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2909 if (isset($totalAmount) &&
2910 $totalAmount != $params['prevContribution']->total_amount
2912 //Update Financial Records
2913 $params['trxnParams']['from_financial_account_id'] = NULL;
2914 self
::updateFinancialAccounts($params, 'changedAmount');
2919 // records finanical trxn and entity financial trxn
2920 // also make it available as return value
2921 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2922 $params['entity_id'] = $financialTxn->id
;
2925 // record line items and finacial items
2926 if (empty($params['skipLineItem'])) {
2927 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2930 // create batch entry if batch_id is passed and
2931 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
2932 if (!empty($params['batch_id']) && !empty($financialTxn)) {
2933 $entityParams = array(
2934 'batch_id' => $params['batch_id'],
2935 'entity_table' => 'civicrm_financial_trxn',
2936 'entity_id' => $financialTxn->id
,
2938 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2941 // when a fee is charged
2942 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2943 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2946 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2947 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2949 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2950 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2951 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2953 unset($params['line_item']);
2959 * Update all financial accounts entry.
2961 * @param array $params
2962 * Contribution object, line item array and params for trxn.
2964 * @param string $context
2967 * @param null $skipTrxn
2970 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2971 $itemAmount = $trxnID = NULL;
2972 //get all the statuses
2973 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2974 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2975 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2976 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2977 && $context == 'changePaymentInstrument'
2981 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2982 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2984 if ($context == 'changedStatus') {
2985 //get all the statuses
2986 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2988 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2989 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2990 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2992 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2994 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2995 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2997 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2998 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2999 $params['trxnParams']['to_financial_account_id'] = NULL;
3000 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3002 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3003 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3004 $financialTypeID, $relationTypeId);
3006 $itemAmount = $params['trxnParams']['total_amount'];
3008 elseif ($context == 'changePaymentInstrument') {
3009 if ($params['trxnParams']['total_amount'] < 0) {
3010 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3011 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3012 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3013 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3017 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3018 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3021 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3022 $params['entity_id'] = $trxn->id
;
3024 if ($context == 'changedStatus') {
3025 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3026 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3027 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3029 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3030 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3032 $entityParams = array(
3033 'entity_table' => 'civicrm_financial_item',
3034 'financial_trxn_id' => $trxn->id
,
3036 if (empty($params['line_item'])) {
3038 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3039 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3040 // & this can be removed
3043 foreach ($params['line_item'] as $fieldId => $fields) {
3044 foreach ($fields as $fieldValueId => $fieldValues) {
3046 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3047 2 => array($fieldValues['id'], 'Integer'),
3049 CRM_Core_DAO
::executeQuery($query, $fparams);
3051 1 => array($fieldValues['id'], 'Integer'),
3053 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3054 while ($financialItem->fetch()) {
3055 $entityParams['entity_id'] = $financialItem->id
;
3056 $entityParams['amount'] = $financialItem->amount
;
3057 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3064 if ($context != 'changePaymentInstrument') {
3065 $itemParams['entity_table'] = 'civicrm_line_item';
3066 $trxnIds['id'] = $params['entity_id'];
3067 foreach ($params['line_item'] as $fieldId => $fields) {
3068 foreach ($fields as $fieldValueId => $fieldValues) {
3069 $prevParams['entity_id'] = $fieldValues['id'];
3070 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3072 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3073 if ($params['contribution']->receive_date
) {
3074 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3077 $financialAccount = $prevfinancialItem->financial_account_id
;
3078 if (!empty($params['financial_account_id'])) {
3079 $financialAccount = $params['financial_account_id'];
3082 $currency = $params['prevContribution']->currency
;
3083 if ($params['contribution']->currency
) {
3084 $currency = $params['contribution']->currency
;
3087 if (!empty($params['is_quick_config'])) {
3088 $amount = $itemAmount;
3090 $amount = $params['total_amount'];
3094 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3095 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3099 $amount = $diff * $fieldValues['line_total'];
3102 $itemParams = array(
3103 'transaction_date' => $receiveDate,
3104 'contact_id' => $params['prevContribution']->contact_id
,
3105 'currency' => $currency,
3106 'amount' => $amount,
3107 'description' => $prevfinancialItem->description
,
3108 'status_id' => $prevfinancialItem->status_id
,
3109 'financial_account_id' => $financialAccount,
3110 'entity_table' => 'civicrm_line_item',
3111 'entity_id' => $fieldValues['id'],
3113 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3115 if ($fieldValues['tax_amount']) {
3116 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3117 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3118 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3119 $itemParams['description'] = $taxTerm;
3120 if ($fieldValues['financial_type_id']) {
3121 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3123 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3128 if ($context == 'changeFinancialType') {
3129 $params['skipLineItem'] = FALSE;
3130 foreach ($params['line_item'] as &$lineItems) {
3131 foreach ($lineItems as &$line) {
3132 $line['financial_type_id'] = $params['financial_type_id'];
3139 * Check status validation on update of a contribution.
3141 * @param array $values
3142 * Previous form values before submit.
3144 * @param array $fields
3145 * The input form values.
3147 * @param array $errors
3152 public static function checkStatusValidation($values, &$fields, &$errors) {
3153 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3154 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3155 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3159 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3160 $checkStatus = array(
3161 'Cancelled' => array('Completed', 'Refunded'),
3162 'Completed' => array('Cancelled', 'Refunded'),
3163 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3164 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3165 'Refunded' => array('Cancelled', 'Completed'),
3168 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3169 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3170 1 => $contributionStatuses[$values['contribution_status_id']],
3171 2 => $contributionStatuses[$fields['contribution_status_id']],
3177 * Delete contribution of contact.
3181 * @param int $contactId
3185 public static function deleteContactContribution($contactId) {
3186 $contribution = new CRM_Contribute_DAO_Contribution();
3187 $contribution->contact_id
= $contactId;
3188 $contribution->find();
3189 while ($contribution->fetch()) {
3190 self
::deleteContribution($contribution->id
);
3195 * Get options for a given contribution field.
3196 * @see CRM_Core_DAO::buildOptions
3198 * @param string $fieldName
3199 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3200 * @param array $props whatever is known about this dao object.
3202 * @return array|bool
3204 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3205 $className = __CLASS__
;
3207 switch ($fieldName) {
3208 // This field is not part of this object but the api supports it
3209 case 'payment_processor':
3210 $className = 'CRM_Contribute_BAO_ContributionPage';
3211 // Filter results by contribution page
3212 if (!empty($props['contribution_page_id'])) {
3213 $page = civicrm_api('contribution_page', 'getsingle', array(
3215 'id' => ($props['contribution_page_id']),
3217 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3218 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3222 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3223 case 'honor_type_id':
3224 $className = 'CRM_Contribute_BAO_ContributionSoft';
3225 $fieldName = 'soft_credit_type_id';
3226 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3229 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3233 * Validate financial type.
3237 * @param int $financialTypeId
3238 * Financial Type id.
3240 * @param string $relationName
3242 * @return array|bool
3244 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3245 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3246 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3248 if (!$financialAccount) {
3249 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3256 * Function to record additional payment for partial and refund contributions.
3258 * @param int $contributionId
3259 * is the invoice contribution id (got created after processing participant payment).
3260 * @param array $trxnsData
3261 * to take user provided input of transaction details.
3262 * @param string $paymentType
3263 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3264 * @param int $participantId
3266 * @return null|object
3268 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3269 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3270 $getInfoOf['id'] = $contributionId;
3271 $defaults = array();
3272 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3274 if ($paymentType == 'owed') {
3275 // build params for recording financial trxn entry
3276 $params['contribution'] = $contributionDAO;
3277 $params = array_merge($defaults, $params);
3278 $params['skipLineItem'] = TRUE;
3279 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3280 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3281 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3282 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3285 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3286 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3287 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3289 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3290 if (!empty($trxnId)) {
3291 $trxnId = $trxnId['trxn_id'];
3293 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3294 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3297 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3298 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3299 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3303 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3304 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3305 FROM civicrm_financial_trxn ft
3306 LEFT JOIN civicrm_entity_financial_trxn eft
3307 ON (ft.id = eft.financial_trxn_id)
3308 WHERE eft.entity_table = 'civicrm_contribution'
3309 AND eft.entity_id = {$contributionId}
3310 AND ft.to_financial_account_id != {$toFinancialAccount}
3311 AND ft.status_id = {$statusId}
3313 $query = CRM_Core_DAO
::executeQuery($sql);
3315 $sumOfPayments = $query->sum_of_payments
;
3318 if ($contributionDAO->total_amount
== $sumOfPayments) {
3319 // update contribution status and
3320 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3321 $contributionDAO->contribution_status_id
= $statusId;
3322 $contributionDAO->cancel_date
= 'null';
3323 $contributionDAO->cancel_reason
= NULL;
3324 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3325 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3326 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3327 $contributionDAO->save();
3329 //Change status of financial record too
3330 $financialTrxn->status_id
= $statusId;
3331 $financialTrxn->save();
3333 // note : not using the self::add method,
3334 // the reason because it performs 'status change' related code execution for financial records
3335 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3336 // are coded below i.e. just updating financial_item status to 'Paid'
3338 if ($participantId) {
3339 // update participant status
3340 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3341 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3342 foreach ($ids as $val) {
3343 $participantUpdate['id'] = $val;
3344 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3345 CRM_Event_BAO_Participant
::add($participantUpdate);
3349 // update financial item statuses
3350 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3351 $paidStatus = array_search('Paid', $financialItemStatus);
3353 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3354 $sqlFinancialItemUpdate = "
3355 UPDATE civicrm_financial_item fi
3356 LEFT JOIN civicrm_entity_financial_trxn eft
3357 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3358 SET status_id = {$paidStatus}
3359 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3361 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3364 elseif ($paymentType == 'refund') {
3365 // build params for recording financial trxn entry
3366 $params['contribution'] = $contributionDAO;
3367 $params = array_merge($defaults, $params);
3368 $params['skipLineItem'] = TRUE;
3369 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3370 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3372 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3373 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3374 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3376 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3378 // note : not using the self::add method,
3379 // the reason because it performs 'status change' related code execution for financial records
3380 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3381 // are coded below i.e. just updating financial_item status to 'Paid'
3382 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3384 // add financial item entry
3385 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3386 $getLine['entity_id'] = $contributionDAO->id
;
3387 $getLine['entity_table'] = 'civicrm_contribution';
3388 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3389 if (!empty($lineItemId->id
)) {
3390 $addFinancialEntry = array(
3391 'transaction_date' => $financialTrxn->trxn_date
,
3392 'contact_id' => $contributionDAO->contact_id
,
3393 'amount' => $financialTrxn->total_amount
,
3394 'status_id' => array_search('Paid', $financialItemStatus),
3395 'entity_id' => $lineItemId->id
,
3396 'entity_table' => 'civicrm_line_item',
3398 $trxnIds['id'] = $financialTrxn->id
;
3399 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3401 if ($participantId) {
3402 // update participant status
3403 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3404 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3405 foreach ($ids as $val) {
3406 $participantUpdate['id'] = $val;
3407 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3408 CRM_Event_BAO_Participant
::add($participantUpdate);
3413 // activity creation
3414 if (!empty($financialTrxn)) {
3415 if ($participantId) {
3416 $inputParams['id'] = $participantId;
3419 $component = 'event';
3420 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3421 $entityObj = $entityObj[$participantId];
3423 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3425 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3427 return $financialTrxn;
3433 * @param $activityType
3435 * @param int $contributionId
3437 * @throws CRM_Core_Exception
3439 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3440 if ($component == 'event') {
3441 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3442 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3443 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3444 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3445 $targetCid = $entityObj->contact_id
;
3446 // source record id would be the contribution id
3447 $srcRecId = $contributionId;
3451 $activityParams = array(
3452 'source_contact_id' => $targetCid,
3453 'source_record_id' => $srcRecId,
3454 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3458 'subject' => $subject,
3459 'activity_date_time' => $date,
3460 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3464 'skipRecentView' => TRUE,
3467 // create activity with target contacts
3468 $session = CRM_Core_Session
::singleton();
3469 $id = $session->get('userID');
3471 $activityParams['source_contact_id'] = $id;
3472 $activityParams['target_contact_id'][] = $targetCid;
3474 CRM_Activity_BAO_Activity
::create($activityParams);
3478 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3482 * @param bool $getTrxnInfo
3483 * @param bool $usingLineTotal
3487 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3488 if ($component == 'event') {
3489 $entity = 'participant';
3490 $entityTable = 'civicrm_participant';
3491 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3493 if (!$contributionId) {
3494 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3495 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3496 $id = $primaryParticipantId;
3498 if (!$contributionId) {
3503 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3504 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3510 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3511 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3514 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3515 // for additional participants
3516 if ($entityTable == 'civicrm_participant') {
3517 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3519 foreach ($ids as $val) {
3520 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3524 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3528 $baseTrxnId = $total['trxn_id'];
3529 $total = $total['total_amount'];
3532 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3533 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3535 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3536 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3537 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3539 if ($paymentBalance == 0 && $contributionIsPayLater) {
3540 $paymentBalance = $total;
3543 $info['total'] = $total;
3544 $info['paid'] = $total - $paymentBalance;
3545 $info['balance'] = $paymentBalance;
3547 $info['component'] = $component;
3548 $info['payLater'] = $contributionIsPayLater;
3550 if ($getTrxnInfo && $baseTrxnId) {
3551 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3553 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3554 FROM civicrm_contribution con
3555 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3556 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3557 WHERE con.id = {$contributionId}
3560 // conditioned WHERE clause
3562 // if balance trxn exists don't include details of it in transaction info
3563 $sql .= " AND ft.id != {$baseTrxnId} ";
3565 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3567 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3568 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3569 while ($resultDAO->fetch()) {
3570 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3571 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3573 'total_amount' => $resultDAO->total_amount
,
3574 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3575 'payment_instrument' => $paidByLabel,
3576 'receive_date' => $resultDAO->trxn_date
,
3577 'trxn_id' => $resultDAO->trxn_id
,
3578 'status' => $statuses[$resultDAO->status_id
],
3580 if ($paidByName == 'Check') {
3581 $val['check_number'] = $resultDAO->check_number
;
3585 $info['transaction'] = $rows;
3591 * Get financial account id has 'Sales Tax Account is'
3592 * account relationship with financial type
3594 * @param int $financialTypeId
3596 * @return FinancialAccountId
3598 public static function getFinancialAccountId($financialTypeId) {
3599 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3600 $searchParams = array(
3601 'entity_table' => 'civicrm_financial_type',
3602 'entity_id' => $financialTypeId,
3603 'account_relationship' => $accountRel,
3606 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3608 return CRM_Utils_Array
::value('financial_account_id', $result);
3614 * @param array $params
3615 * @param bool $isLineItem
3619 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3620 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3622 // Update contribution.
3623 if (!empty($params['id'])) {
3624 $id = $params['id'];
3625 $values = $ids = array();
3626 $contrbutionParams = array('id' => $id);
3627 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3629 // To assign pervious finantial type on update of contribution
3630 if (!isset($params['financial_type_id'])) {
3631 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3633 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3634 // Assisn tax Amount on update of contrbution
3635 if (!empty($prevContributionValue->tax_amount
)) {
3636 $params['tax_amount'] = 'null';
3637 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3638 foreach ($params['line_item'] as $setID => $priceField) {
3639 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3640 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3647 // New Contrbution and update of contribution with tax rate financial type
3648 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3649 empty($params['skipLineItem']) && !$isLineItem
3651 $taxRateParams = $taxRates[$params['financial_type_id']];
3652 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3653 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3655 // Get Line Item on update of contribution
3656 if (isset($params['id'])) {
3657 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3660 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3662 foreach ($params['line_item'] as $setID => $priceField) {
3663 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3664 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3667 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3669 elseif (isset($params['api.line_item.create'])) {
3670 // Update total amount of contribution using lineItem
3671 $taxAmountArray = array();
3672 foreach ($params['api.line_item.create'] as $key => $value) {
3673 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3674 $taxRate = $taxRates[$value['financial_type_id']];
3675 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3676 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3679 $params['tax_amount'] = array_sum($taxAmountArray);
3680 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3683 // update line item of contrbution
3684 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3685 $taxRate = $taxRates[$params['financial_type_id']];
3686 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3687 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3694 * Check financial type validation on update of a contribution.
3696 * @param Integer $financialTypeId
3697 * Value of latest Financial Type.
3699 * @param Integer $contributionId
3702 * @param array $errors
3707 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3708 if (!empty($financialTypeId)) {
3709 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3710 if ($oldFinancialTypeId == $financialTypeId) {
3714 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3716 '1' => array($contributionId, 'Integer'),
3718 $result = CRM_Core_DAO
::executeQuery($sql, $params);
3719 if ($result->N
> 1) {
3720 $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.');