3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
38 * Static field for all the contribution information that we can potentially import
42 static $_importableFields = NULL;
45 * Static field for all the contribution information that we can potentially export
49 static $_exportableFields = NULL;
52 * Field for all the objects related to this contribution
53 * @var array of objects (e.g membership object, participant object)
55 public $_relatedObjects = array();
58 * Field for the component - either 'event' (participant) or 'contribute'
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
63 * @var string component or event
65 public $_component = NULL;
70 * @return \CRM_Contribute_DAO_Contribution
74 public function __construct() {
75 parent
::__construct();
79 * Takes an associative array and creates a contribution object
81 * the function extract all the params it needs to initialize the create a
82 * contribution object. the params array could contain additional unused name/value
85 * @param array $params
86 * (reference ) an assoc array of name/value pairs.
88 * The array that holds all the db ids.
90 * @return CRM_Contribute_BAO_Contribution|void
92 public static function add(&$params, $ids = array()) {
96 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
97 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
98 $duplicates = array();
99 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
100 $error = CRM_Core_Error
::singleton();
101 $d = implode(', ', $duplicates);
102 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
105 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
110 // first clean up all the money fields
111 $moneyFields = array(
115 'non_deductible_amount',
118 //if priceset is used, no need to cleanup money
119 if (!empty($params['skipCleanMoney'])) {
120 unset($moneyFields[0]);
123 foreach ($moneyFields as $field) {
124 if (isset($params[$field])) {
125 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
129 //set defaults in create mode
130 if (!$contributionID) {
131 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
132 self
::calculateMissingAmountParams($params);
135 if (!empty($params['payment_instrument_id'])) {
136 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
137 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
138 $params['check_number'] = 'null';
142 $setPrevContribution = TRUE;
143 // CRM-13964 partial payment
144 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
145 $partialAmtTotal = $params['partial_payment_total'];
146 $partialAmtPay = $params['partial_amount_pay'];
147 $params['total_amount'] = $partialAmtTotal;
148 if ($partialAmtPay < $partialAmtTotal) {
149 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
150 $params['is_pay_later'] = 0;
151 $setPrevContribution = FALSE;
155 if ($contributionID) {
156 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
159 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
161 $contribution = new CRM_Contribute_BAO_Contribution();
162 $contribution->copyValues($params);
164 $contribution->id
= $contributionID;
166 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
167 $config = CRM_Core_Config
::singleton();
168 $contribution->currency
= $config->defaultCurrency
;
171 if ($contributionID && $setPrevContribution) {
172 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
175 $result = $contribution->save();
177 // Add financial_trxn details as part of fix for CRM-4724
178 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
179 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
181 //add Account details
182 $params['contribution'] = $contribution;
183 self
::recordFinancialAccounts($params);
185 // reset the group contact cache for this group
186 CRM_Contact_BAO_GroupContactCache
::remove();
188 if ($contributionID) {
189 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
192 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
199 * Get defaults for new entity
202 public static function getDefaults() {
204 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
205 FALSE, FALSE, FALSE, 'AND is_default = 1')
207 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
212 * Given the list of params in the params array, fetch the object
213 * and store the values in the values array
215 * @param array $params
216 * Input parameters to find object.
217 * @param array $values
218 * Output values of the object.
220 * The array that holds all the db ids.
222 * @return CRM_Contribute_BAO_Contribution|null the found object or null
224 public static function &getValues($params, &$values, &$ids) {
225 if (empty($params)) {
228 $contribution = new CRM_Contribute_BAO_Contribution();
230 $contribution->copyValues($params);
232 if ($contribution->find(TRUE)) {
233 $ids['contribution'] = $contribution->id
;
235 CRM_Core_DAO
::storeValues($contribution, $values);
237 return $contribution;
239 $null = NULL; // return by reference
244 * @param array $params
248 public static function calculateMissingAmountParams(&$params) {
249 if (!isset($params['fee_amount'])) {
250 if (isset($params['total_amount']) && isset($params['net_amount'])) {
251 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
254 $params['fee_amount'] = 0;
257 if (!isset($params['net_amount'])) {
258 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
263 * Get the number of terms for this contribution for a given membership type
264 * based on querying the line item table and relevant price field values
265 * Note that any one contribution should only be able to have one line item relating to a particular membership
268 * @param int $membershipTypeID
270 * @param int $contributionID
274 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
275 $numTerms = CRM_Core_DAO
::singleValueQuery("
276 SELECT membership_num_terms FROM civicrm_line_item li
277 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
278 WHERE contribution_id = %1 AND membership_type_id = %2",
279 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
281 // default of 1 is precautionary
282 return empty($numTerms) ?
1 : $numTerms;
286 * Takes an associative array and creates a contribution object
288 * @param array $params
289 * (reference ) an assoc array of name/value pairs.
291 * The array that holds all the db ids.
293 * @return CRM_Contribute_BAO_Contribution
295 public static function create(&$params, $ids = array()) {
296 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
297 foreach ($dateFields as $df) {
298 if (isset($params[$df])) {
299 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
303 $transaction = new CRM_Core_Transaction();
305 $contribution = self
::add($params, $ids);
307 if (is_a($contribution, 'CRM_Core_Error')) {
308 $transaction->rollback();
309 return $contribution;
312 $params['contribution_id'] = $contribution->id
;
314 if (!empty($params['custom']) &&
315 is_array($params['custom'])
317 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
320 $session = CRM_Core_Session
::singleton();
322 if (!empty($params['note'])) {
324 'entity_table' => 'civicrm_contribution',
325 'note' => $params['note'],
326 'entity_id' => $contribution->id
,
327 'contact_id' => $session->get('userID'),
328 'modified_date' => date('Ymd'),
330 if (!$noteParams['contact_id']) {
331 $noteParams['contact_id'] = $params['contact_id'];
333 CRM_Core_BAO_Note
::add($noteParams);
336 // make entry in batch entity batch table
337 if (!empty($params['batch_id'])) {
338 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
339 $titleFields = array(
345 $retrieveRequired = 0;
346 foreach ($titleFields as $titleField) {
347 if (!isset($contribution->$titleField)) {
348 $retrieveRequired = 1;
352 if ($retrieveRequired == 1) {
353 $contribution->find(TRUE);
357 // check if activity record exist for this contribution, if
359 $activity = new CRM_Activity_DAO_Activity();
360 $activity->source_record_id
= $contribution->id
;
361 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
365 if (!$activity->find(TRUE)) {
366 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
369 // CRM-13237 : if activity record found, update it with campaign id of contribution
370 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
373 // Handle soft credit and / or link to personal campaign page
374 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
376 //Delete PCP against this contribution and create new on submitted PCP information
377 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
379 $deleteParams = array('id' => $pcpId);
380 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
382 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
383 $softParams = array();
384 $softParams['contribution_id'] = $contribution->id
;
385 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
386 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
387 $pcp['pcp_made_through_id'], 'contact_id'
389 $softParams['currency'] = $contribution->currency
;
390 $softParams['amount'] = $contribution->total_amount
;
391 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
392 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
393 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
394 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
395 $contributionSoft = CRM_Contribute_BAO_ContributionSoft
::add($softParams);
396 //Send notification to owner for PCP
397 if ($contributionSoft->pcp_id
) {
398 CRM_Contribute_Form_Contribution_Confirm
::pcpNotifyOwner($contribution, $contributionSoft);
401 if (isset($params['soft_credit'])) {
402 $softParams = $params['soft_credit'];
404 if (!empty($softIDs)) {
405 foreach ($softIDs as $softID) {
406 if (!in_array($softID, $params['soft_credit_ids'])) {
407 $deleteParams = array('id' => $softID);
408 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
413 foreach ($softParams as $softParam) {
414 $softParam['contribution_id'] = $contribution->id
;
415 $softParam['currency'] = $contribution->currency
;
416 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
417 if (empty($softParam['amount'])) {
418 $softParam['amount'] = $contribution->total_amount
;
420 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
424 $transaction->commit();
426 // do not add to recent items for import, CRM-4399
427 if (empty($params['skipRecentView'])) {
428 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
429 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
431 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
432 $titleFields = array(
438 $retrieveRequired = 0;
439 foreach ($titleFields as $titleField) {
440 if (!isset($contribution->$titleField)) {
441 $retrieveRequired = 1;
445 if ($retrieveRequired == 1) {
446 $contribution->find(TRUE);
448 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
449 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
451 $recentOther = array();
452 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
453 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
454 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
458 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
459 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
460 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
464 // add the recently created Contribution
465 CRM_Utils_Recent
::add($title,
469 $contribution->contact_id
,
475 return $contribution;
479 * Get the values for pseudoconstants for name->value and reverse.
481 * @param array $defaults
482 * (reference) the default values, some of which need to be resolved.
483 * @param bool $reverse
484 * True if we want to resolve the values in the reverse direction (value -> name).
488 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
489 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
490 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
491 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
492 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
496 * convert associative array names to values
499 * This function is used by both the web form layer and the api. Note that
500 * the api needs the name => value conversion, also the view layer typically
501 * requires value => name conversion
503 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
504 $id = $property . '_id';
506 $src = $reverse ?
$property : $id;
507 $dst = $reverse ?
$id : $property;
509 if (!array_key_exists($src, $defaults)) {
513 $look = $reverse ?
array_flip($lookup) : $lookup;
515 if (is_array($look)) {
516 if (!array_key_exists($defaults[$src], $look)) {
520 $defaults[$dst] = $look[$defaults[$src]];
525 * Takes a bunch of params that are needed to match certain criteria and
526 * retrieves the relevant objects. We'll tweak this function to be more
527 * full featured over a period of time. This is the inverse function of
528 * create. It also stores all the retrieved values in the default array
530 * @param array $params
531 * (reference ) an assoc array of name/value pairs.
532 * @param array $defaults
533 * (reference ) an assoc array to hold the name / value pairs.
534 * in a hierarchical manner
536 * (reference) the array that holds all the db ids.
538 * @return CRM_Contribute_BAO_Contribution
540 public static function retrieve(&$params, &$defaults, &$ids) {
541 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
542 return $contribution;
546 * Combine all the importable fields from the lower levels object
548 * The ordering is important, since currently we do not have a weight
549 * scheme. Adding weight is super important and should be done in the
550 * next week or so, before this can be called complete.
552 * @param string $contactType
553 * @param bool $status
556 * array of importable Fields
558 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
559 if (!self
::$_importableFields) {
560 if (!self
::$_importableFields) {
561 self
::$_importableFields = array();
565 $fields = array('' => array('title' => ts('- do not import -')));
568 $fields = array('' => array('title' => ts('- Contribution Fields -')));
571 $note = CRM_Core_DAO_Note
::import();
572 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
573 unset($tmpFields['option_value']);
574 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
575 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
577 // Using new Dedupe rule.
579 'contact_type' => $contactType,
580 'used' => 'Unsupervised',
582 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
583 $tmpContactField = array();
584 if (is_array($fieldsArray)) {
585 foreach ($fieldsArray as $value) {
586 //skip if there is no dupe rule
587 if ($value == 'none') {
590 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
595 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
596 $tmpContactField[trim($value)] = $contactFields[trim($value)];
598 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
601 $title = $tmpContactField[trim($value)]['title'];
603 $tmpContactField[trim($value)]['title'] = $title;
607 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
608 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
609 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
610 $fields = array_merge($fields, $tmpContactField);
611 $fields = array_merge($fields, $tmpFields);
612 $fields = array_merge($fields, $note);
613 $fields = array_merge($fields, $optionFields);
614 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
615 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
616 self
::$_importableFields = $fields;
618 return self
::$_importableFields;
624 public static function &exportableFields() {
625 if (!self
::$_exportableFields) {
626 if (!self
::$_exportableFields) {
627 self
::$_exportableFields = array();
630 $impFields = CRM_Contribute_DAO_Contribution
::export();
631 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
632 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
633 $typeField = CRM_Financial_DAO_FinancialType
::export();
634 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
635 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
636 $contributionStatus = array(
637 'contribution_status' => array(
638 'title' => ts('Contribution Status'),
639 'name' => 'contribution_status',
640 'data_type' => CRM_Utils_Type
::T_STRING
,
644 $contributionPage = array(
645 'contribution_page' => array(
646 'title' => ts('Contribution Page'),
647 'name' => 'contribution_page',
648 'where' => 'civicrm_contribution_page.title',
649 'data_type' => CRM_Utils_Type
::T_STRING
,
653 $contributionNote = array(
654 'contribution_note' => array(
655 'title' => ts('Contribution Note'),
656 'name' => 'contribution_note',
657 'data_type' => CRM_Utils_Type
::T_TEXT
,
661 $contributionRecurId = array(
662 'contribution_recur_id' => array(
663 'title' => ts('Recurring Contributions ID'),
664 'name' => 'contribution_recur_id',
665 'where' => 'civicrm_contribution.contribution_recur_id',
666 'data_type' => CRM_Utils_Type
::T_INT
,
670 $extraFields = array(
671 'contribution_batch' => array(
672 'title' => ts('Batch Name'),
676 $softCreditFields = array(
677 'contribution_soft_credit_name' => array(
678 'name' => 'contribution_soft_credit_name',
679 'title' => 'Soft Credit For',
680 'where' => 'civicrm_contact_d.display_name',
681 'data_type' => CRM_Utils_Type
::T_STRING
,
683 'contribution_soft_credit_amount' => array(
684 'name' => 'contribution_soft_credit_amount',
685 'title' => 'Soft Credit Amount',
686 'where' => 'civicrm_contribution_soft.amount',
687 'data_type' => CRM_Utils_Type
::T_MONEY
,
689 'contribution_soft_credit_type' => array(
690 'name' => 'contribution_soft_credit_type',
691 'title' => 'Soft Credit Type',
692 'where' => 'contribution_softcredit_type.label',
693 'data_type' => CRM_Utils_Type
::T_STRING
,
695 'contribution_soft_credit_contribution_id' => array(
696 'name' => 'contribution_soft_credit_contribution_id',
697 'title' => 'Soft Credit For Contribution ID',
698 'where' => 'civicrm_contribution_soft.contribution_id',
699 'data_type' => CRM_Utils_Type
::T_INT
,
703 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
704 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
705 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
708 self
::$_exportableFields = $fields;
711 return self
::$_exportableFields;
715 * @param null $status
716 * @param null $startDate
717 * @param null $endDate
721 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
725 $where[] = 'contribution_status_id = 1';
729 $where[] = 'contribution_status_id = 3';
734 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
737 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
740 $whereCond = implode(' AND ', $where);
743 SELECT sum( total_amount ) as total_amount,
744 count( civicrm_contribution.id ) as total_count,
746 FROM civicrm_contribution
747 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
749 AND ( is_test = 0 OR is_test IS NULL )
750 AND contact.is_deleted = 0
754 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
757 while ($dao->fetch()) {
758 $count +
= $dao->total_count
;
759 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
763 'amount' => implode(', ', $amount),
771 * Delete the indirect records associated with this contribution first
776 * $results no of deleted Contribution on success, false otherwise
778 public static function deleteContribution($id) {
779 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
781 $transaction = new CRM_Core_Transaction();
784 //delete activity record
786 'source_record_id' => $id,
787 // activity type id for contribution
788 'activity_type_id' => 6,
791 CRM_Activity_BAO_Activity
::deleteActivity($params);
793 //delete billing address if exists for this contribution.
794 self
::deleteAddress($id);
796 //update pledge and pledge payment, CRM-3961
797 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
799 // remove entry from civicrm_price_set_entity, CRM-5095
800 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
801 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
803 // cleanup line items.
804 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
806 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
807 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
809 if ($participantId) {
810 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
813 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
817 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
818 $noteId = key($note);
820 CRM_Core_BAO_Note
::del($noteId, FALSE);
823 $dao = new CRM_Contribute_DAO_Contribution();
826 $results = $dao->delete();
828 $transaction->commit();
830 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
832 // delete the recently created Contribution
833 $contributionRecent = array(
835 'type' => 'Contribution',
837 CRM_Utils_Recent
::del($contributionRecent);
843 * Check if there is a contribution with the same trxn_id or invoice_id
845 * @param array $input
846 * An assoc array of name/value pairs.
847 * @param array $duplicates
848 * (reference) store ids of duplicate contribs.
852 * true if duplicate, false otherwise
854 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
856 $id = CRM_Utils_Array
::value('id', $input);
858 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
859 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
865 $clause[] = "trxn_id = %1";
866 $input[1] = array($trxn_id, 'String');
870 $clause[] = "invoice_id = %2";
871 $input[2] = array($invoice_id, 'String');
874 if (empty($clause)) {
878 $clause = implode(' OR ', $clause);
880 $clause = "( $clause ) AND id != %3";
881 $input[3] = array($id, 'Integer');
884 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
885 $dao = CRM_Core_DAO
::executeQuery($query, $input);
887 while ($dao->fetch()) {
888 $duplicates[] = $dao->id
;
895 * Takes an associative array and creates a contribution_product object
897 * the function extract all the params it needs to initialize the create a
898 * contribution_product object. the params array could contain additional unused name/value
901 * @param array $params
902 * (reference) an assoc array of name/value pairs.
904 * @return CRM_Contribute_DAO_ContributionProduct
906 public static function addPremium(&$params) {
907 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
908 $contributionProduct->copyValues($params);
909 return $contributionProduct->save();
913 * Get list of contribution fields for profile
914 * For now we only allow custom contribution fields to be in
917 * @param bool $addExtraFields
918 * True if special fields needs to be added.
921 * the list of contribution fields
923 public static function getContributionFields($addExtraFields = TRUE) {
924 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
925 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
927 if ($addExtraFields) {
928 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
931 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
933 foreach ($contributionFields as $key => $var) {
934 if ($key == 'contribution_contact_id') {
937 elseif ($key == 'contribution_campaign_id') {
938 $var['title'] = ts('Campaign');
940 $fields[$key] = $var;
943 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
948 * Add extra fields specific to contribtion
951 public static function getSpecialContributionFields() {
952 $extraFields = array(
953 'contribution_soft_credit_name' => array(
954 'name' => 'contribution_soft_credit_name',
955 'title' => 'Soft Credit Name',
956 'headerPattern' => '/^soft_credit_name$/i',
957 'where' => 'civicrm_contact_d.display_name',
959 'contribution_soft_credit_email' => array(
960 'name' => 'contribution_soft_credit_email',
961 'title' => 'Soft Credit Email',
962 'headerPattern' => '/^soft_credit_email$/i',
963 'where' => 'soft_email.email',
965 'contribution_soft_credit_phone' => array(
966 'name' => 'contribution_soft_credit_phone',
967 'title' => 'Soft Credit Phone',
968 'headerPattern' => '/^soft_credit_phone$/i',
969 'where' => 'soft_phone.phone',
971 'contribution_soft_credit_contact_id' => array(
972 'name' => 'contribution_soft_credit_contact_id',
973 'title' => 'Soft Credit Contact ID',
974 'headerPattern' => '/^soft_credit_contact_id$/i',
975 'where' => 'civicrm_contribution_soft.contact_id',
987 public static function getCurrentandGoalAmount($pageID) {
989 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
990 FROM civicrm_contribution_page p,
991 civicrm_contribution c
992 WHERE p.id = c.contribution_page_id
994 AND c.cancel_date is null
998 $config = CRM_Core_Config
::singleton();
999 $params = array(1 => array($pageID, 'Integer'));
1000 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1002 if ($dao->fetch()) {
1003 return array($dao->goal
, $dao->total
);
1006 return array(NULL, NULL);
1011 * Get list of contribution In Honor of contact Ids
1013 * @param int $honorId
1014 * In Honor of Contact ID.
1017 * list of contribution fields
1020 public static function getHonorContacts($honorId) {
1022 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1023 $honorDAO->contact_id
= $honorId;
1026 $type = CRM_Contribute_PseudoConstant
::financialType();
1028 while ($honorDAO->fetch()) {
1029 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1030 $contributionDAO->id
= $honorDAO->contribution_id
;
1032 if ($contributionDAO->find(TRUE)) {
1033 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1034 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1035 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1036 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1037 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1038 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1039 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1040 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1041 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1049 * Get the sort name of a contact for a particular contribution
1052 * Id of the contribution.
1054 * @return null|string
1055 * sort name of the contact if found
1057 public static function sortName($id) {
1058 $id = CRM_Utils_Type
::escape($id, 'Integer');
1061 SELECT civicrm_contact.sort_name
1062 FROM civicrm_contribution, civicrm_contact
1063 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1064 AND civicrm_contribution.id = {$id}
1066 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1070 * @param int $contactID
1074 public static function annual($contactID) {
1075 if (is_array($contactID)) {
1076 $contactIDs = implode(',', $contactID);
1079 $contactIDs = $contactID;
1082 $config = CRM_Core_Config
::singleton();
1083 $startDate = $endDate = NULL;
1085 $currentMonth = date('m');
1086 $currentDay = date('d');
1087 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1088 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1089 (int ) $config->fiscalYearStart
['d'] > $currentDay
1092 $year = date('Y') - 1;
1097 $nextYear = $year +
1;
1099 if ($config->fiscalYearStart
) {
1100 if ($config->fiscalYearStart
['M'] < 10) {
1101 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1103 if ($config->fiscalYearStart
['d'] < 10) {
1104 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1106 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1111 $startDate = "$year$monthDay";
1112 $endDate = "$nextYear$monthDay";
1115 SELECT count(*) as count,
1116 sum(total_amount) as amount,
1117 avg(total_amount) as average,
1119 FROM civicrm_contribution b
1120 WHERE b.contact_id IN ( $contactIDs )
1121 AND b.contribution_status_id = 1
1123 AND b.receive_date >= $startDate
1124 AND b.receive_date < $endDate
1127 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1129 $amount = $average = array();
1130 while ($dao->fetch()) {
1131 if ($dao->count
> 0 && $dao->amount
> 0) {
1132 $count +
= $dao->count
;
1133 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1134 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1140 implode(', ', $amount),
1141 implode(', ', $average),
1144 return array(0, 0, 0);
1148 * Check if there is a contribution with the params passed in.
1149 * Used for trxn_id,invoice_id and contribution_id
1151 * @param array $params
1152 * An assoc array of name/value pairs.
1155 * contribution id if success else NULL
1157 public static function checkDuplicateIds($params) {
1158 $dao = new CRM_Contribute_DAO_Contribution();
1162 foreach ($params as $k => $v) {
1164 $clause[] = "$k = '$v'";
1167 $clause = implode(' AND ', $clause);
1168 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1169 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1171 while ($dao->fetch()) {
1179 * Get the contribution details for component export
1181 * @param int $exportMode
1183 * @param string $componentIds
1190 public static function getContributionDetails($exportMode, $componentIds) {
1191 $paymentDetails = array();
1192 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1194 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1195 $componentSelect = " civicrm_participant_payment.participant_id id";
1196 $additionalClause = "
1197 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1198 AND civicrm_participant_payment.participant_id {$componentClause} )
1201 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1202 $componentSelect = " civicrm_membership_payment.membership_id id";
1203 $additionalClause = "
1204 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1205 AND civicrm_membership_payment.membership_id {$componentClause} )
1208 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1209 $componentSelect = " civicrm_pledge_payment.id id";
1210 $additionalClause = "
1211 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1212 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1216 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1217 trxn_id, {$componentSelect}
1218 FROM civicrm_contribution
1219 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1220 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1221 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1222 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1223 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1224 AND option_group_contribution_status.id = contribution_status.option_group_id )
1228 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1230 while ($dao->fetch()) {
1231 $paymentDetails[$dao->id
] = array(
1232 'total_amount' => $dao->total_amount
,
1233 'contribution_status' => $dao->status
,
1234 'receive_date' => $dao->receive_date
,
1235 'pay_instru' => $dao->payment_instrument
,
1236 'trxn_id' => $dao->trxn_id
,
1240 return $paymentDetails;
1244 * Create address associated with contribution record.
1246 * @param array $params
1247 * @param int $billingLocationTypeID
1252 public static function createAddress(&$params, $billingLocationTypeID) {
1253 $billingFields = array(
1256 'state_province_id',
1261 //build address array
1262 $addressParams = array();
1263 $addressParams['location_type_id'] = $billingLocationTypeID;
1264 $addressParams['is_billing'] = 1;
1266 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1267 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1268 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1269 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1271 foreach ($billingFields as $value) {
1272 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1275 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1277 return $address->id
;
1281 * Delete billing address record related contribution
1283 * @param int $contributionId
1284 * @param int $contactId
1287 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1289 $contactJoin = NULL;
1291 if ($contributionId) {
1292 $clauses[] = "cc.id = {$contributionId}";
1296 $clauses[] = "cco.id = {$contactId}";
1297 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1300 if (empty($clauses)) {
1301 CRM_Core_Error
::fatal();
1304 $condition = implode(' OR ', $clauses);
1308 FROM civicrm_address ca
1309 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1313 $dao = CRM_Core_DAO
::executeQuery($query);
1315 while ($dao->fetch()) {
1316 $params = array('id' => $dao->id
);
1317 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1322 * This function check online pending contribution associated w/
1323 * Online Event Registration or Online Membership signup.
1325 * @param int $componentId
1326 * Participant/membership id.
1327 * @param string $componentName
1331 * pending contribution id.
1333 public static function checkOnlinePendingContribution($componentId, $componentName) {
1334 $contributionId = NULL;
1335 if (!$componentId ||
1336 !in_array($componentName, array('Event', 'Membership'))
1338 return $contributionId;
1341 if ($componentName == 'Event') {
1342 $idName = 'participant_id';
1343 $componentTable = 'civicrm_participant';
1344 $paymentTable = 'civicrm_participant_payment';
1345 $source = ts('Online Event Registration');
1348 if ($componentName == 'Membership') {
1349 $idName = 'membership_id';
1350 $componentTable = 'civicrm_membership';
1351 $paymentTable = 'civicrm_membership_payment';
1352 $source = ts('Online Contribution');
1355 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1358 SELECT component.id as {$idName},
1359 componentPayment.contribution_id as contribution_id,
1360 contribution.source source,
1361 contribution.contribution_status_id as contribution_status_id,
1362 contribution.is_pay_later as is_pay_later
1363 FROM $componentTable component
1364 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1365 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1366 WHERE component.id = {$componentId}";
1368 $dao = CRM_Core_DAO
::executeQuery($query);
1370 while ($dao->fetch()) {
1371 if ($dao->contribution_id
&&
1372 $dao->is_pay_later
&&
1373 $dao->contribution_status_id
== $pendingStatusId &&
1374 strpos($dao->source
, $source) !== FALSE
1376 $contributionId = $dao->contribution_id
;
1381 return $contributionId;
1385 * Update contribution as well as related objects.
1387 public static function transitionComponents($params, $processContributionObject = FALSE) {
1388 // get minimum required values.
1389 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1390 $componentId = CRM_Utils_Array
::value('component_id', $params);
1391 $componentName = CRM_Utils_Array
::value('componentName', $params);
1392 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1393 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1395 // if we already processed contribution object pass previous status id.
1396 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1398 $updateResult = array();
1400 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1402 // we process only ( Completed, Cancelled, or Failed ) contributions.
1403 if (!$contributionId ||
1404 !in_array($contributionStatusId, array(
1405 array_search('Completed', $contributionStatuses),
1406 array_search('Cancelled', $contributionStatuses),
1407 array_search('Failed', $contributionStatuses),
1410 return $updateResult;
1413 if (!$componentName ||
!$componentId) {
1414 // get the related component details.
1415 $componentDetails = self
::getComponentDetails($contributionId);
1418 $componentDetails['contact_id'] = $contactId;
1419 $componentDetails['component'] = $componentName;
1421 if ($componentName == 'event') {
1422 $componentDetails['participant'] = $componentId;
1425 $componentDetails['membership'] = $componentId;
1429 if (!empty($componentDetails['contact_id'])) {
1430 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1436 // do check for required ids.
1437 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1438 return $updateResult;
1441 //now we are ready w/ required ids, start processing.
1443 $baseIPN = new CRM_Core_Payment_BaseIPN();
1445 $input = $ids = $objects = array();
1447 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1448 $ids['contribution'] = $contributionId;
1449 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1450 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1451 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1452 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1453 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1454 $ids['contributionRecur'] = NULL;
1455 $ids['contributionPage'] = NULL;
1457 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1458 CRM_Core_Error
::fatal();
1461 $memberships = &$objects['membership'];
1462 $participant = &$objects['participant'];
1463 $pledgePayment = &$objects['pledge_payment'];
1464 $contribution = &$objects['contribution'];
1466 if ($pledgePayment) {
1467 $pledgePaymentIDs = array();
1468 foreach ($pledgePayment as $key => $object) {
1469 $pledgePaymentIDs[] = $object->id
;
1471 $pledgeID = $pledgePayment[0]->pledge_id
;
1474 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1477 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1478 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1483 // we might want to process contribution object.
1484 $processContribution = FALSE;
1485 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1486 if (is_array($memberships)) {
1487 foreach ($memberships as $membership) {
1489 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1490 $membership->save();
1492 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1493 if ($processContributionObject) {
1494 $processContribution = TRUE;
1501 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1502 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1504 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1505 if ($processContributionObject) {
1506 $processContribution = TRUE;
1510 if ($pledgePayment) {
1511 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1513 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1514 if ($processContributionObject) {
1515 $processContribution = TRUE;
1519 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1520 if (is_array($memberships)) {
1521 foreach ($memberships as $membership) {
1523 $membership->status_id
= array_search('Expired', $membershipStatuses);
1524 $membership->save();
1526 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1527 if ($processContributionObject) {
1528 $processContribution = TRUE;
1534 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1535 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1537 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1538 if ($processContributionObject) {
1539 $processContribution = TRUE;
1543 if ($pledgePayment) {
1544 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1546 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1547 if ($processContributionObject) {
1548 $processContribution = TRUE;
1552 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1554 // only pending contribution related object processed.
1555 if ($previousContriStatusId &&
1556 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1558 // this is case when we already processed contribution object.
1559 return $updateResult;
1561 elseif (!$previousContriStatusId &&
1562 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1564 // this is case when we are going to process contribution object later.
1565 return $updateResult;
1568 if (is_array($memberships)) {
1569 foreach ($memberships as $membership) {
1574 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1575 $membership->membership_type_id
,
1576 $membership->is_test
, $membership->id
1579 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1580 // this picks up membership type changes during renewals
1582 SELECT membership_type_id
1583 FROM civicrm_membership_log
1584 WHERE membership_id=$membership->id
1587 $dao = new CRM_Core_DAO();
1589 if ($dao->fetch()) {
1590 if (!empty($dao->membership_type_id
)) {
1591 $membership->membership_type_id
= $dao->membership_type_id
;
1592 $membership->save();
1595 // else fall back to using current membership type
1598 // Figure out number of terms
1600 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1601 foreach ($lineitems as $lineitem) {
1602 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1603 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1605 // in case membership_num_terms comes through as null or zero
1606 $numterms = $numterms >= 1 ?
$numterms : 1;
1611 // CRM-15735-to update the membership status as per the contribution receive date
1612 if (!empty($params['receive_date'])) {
1613 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1614 $membership->end_date
,
1615 $membership->join_date
,
1616 $params['receive_date'],
1618 $membership->membership_type_id
,
1621 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1622 $membership->save();
1625 if ($currentMembership) {
1626 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1627 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1628 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1631 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1634 //get the status for membership.
1635 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1637 $dates['join_date'],
1640 $membership->membership_type_id
,
1644 $formattedParams = array(
1645 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1646 array_search('Current', $membershipStatuses)
1648 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1649 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1650 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1653 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1655 $membership->copyValues($formattedParams);
1656 $membership->save();
1658 //updating the membership log
1659 $membershipLog = array();
1660 $membershipLog = $formattedParams;
1661 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1662 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1664 $membershipLog['start_date'] = $logStartDate;
1665 $membershipLog['membership_id'] = $membership->id
;
1666 $membershipLog['modified_id'] = $membership->contact_id
;
1667 $membershipLog['modified_date'] = date('Ymd');
1668 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1670 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1672 //update related Memberships.
1673 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1675 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1678 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1679 if ($processContributionObject) {
1680 $processContribution = TRUE;
1683 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1689 $updatedStatusId = array_search('Registered', $participantStatuses);
1690 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1692 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1693 if ($processContributionObject) {
1694 $processContribution = TRUE;
1698 if ($pledgePayment) {
1699 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1701 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1702 if ($processContributionObject) {
1703 $processContribution = TRUE;
1708 // process contribution object.
1709 if ($processContribution) {
1710 $contributionParams = array();
1717 'payment_instrument_id',
1720 'financial_type_id',
1721 'contribution_status_id',
1722 'non_deductible_amount',
1726 foreach ($fields as $field) {
1727 if (empty($params[$field])) {
1730 $contributionParams[$field] = $params[$field];
1733 $ids = array('contribution' => $contributionId);
1734 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1737 return $updateResult;
1741 * Returns all contribution related object ids.
1743 * @param $contributionId
1747 public static function getComponentDetails($contributionId) {
1748 $componentDetails = $pledgePayment = array();
1749 if (!$contributionId) {
1750 return $componentDetails;
1754 SELECT c.id as contribution_id,
1755 c.contact_id as contact_id,
1756 mp.membership_id as membership_id,
1757 m.membership_type_id as membership_type_id,
1758 pp.participant_id as participant_id,
1759 p.event_id as event_id,
1760 pgp.id as pledge_payment_id
1761 FROM civicrm_contribution c
1762 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1763 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1764 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1765 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1766 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1767 WHERE c.id = $contributionId";
1769 $dao = CRM_Core_DAO
::executeQuery($query);
1770 $componentDetails = array();
1772 while ($dao->fetch()) {
1773 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1774 $componentDetails['contact_id'] = $dao->contact_id
;
1775 if ($dao->event_id
) {
1776 $componentDetails['event'] = $dao->event_id
;
1778 if ($dao->participant_id
) {
1779 $componentDetails['participant'] = $dao->participant_id
;
1781 if ($dao->membership_id
) {
1782 if (!isset($componentDetails['membership'])) {
1783 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1785 $componentDetails['membership'][] = $dao->membership_id
;
1786 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1788 if ($dao->pledge_payment_id
) {
1789 $pledgePayment[] = $dao->pledge_payment_id
;
1793 if ($pledgePayment) {
1794 $componentDetails['pledge_payment'] = $pledgePayment;
1797 return $componentDetails;
1801 * @param int $contactId
1802 * @param bool $includeSoftCredit
1804 * @return null|string
1806 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1811 $contactContributionsSQL = "
1812 SELECT contribution.id AS id
1813 FROM civicrm_contribution contribution
1814 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1816 $contactSoftCreditContributionsSQL = "
1817 SELECT contribution.id
1818 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1819 ON ( contribution.id = softContribution.contribution_id )
1820 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1821 $query = "SELECT count( x.id ) count FROM ( ";
1822 $query .= $contactContributionsSQL;
1824 if ($includeSoftCredit) {
1825 $query .= " UNION ";
1826 $query .= $contactSoftCreditContributionsSQL;
1831 return CRM_Core_DAO
::singleValueQuery($query);
1835 * Get individual id for onbehalf contribution
1837 * @param int $contributionId
1839 * @param int $contributorId
1843 * containing organization id and individual id
1845 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1849 if (!$contributionId) {
1853 // fetch contributor id if null
1854 if (!$contributorId) {
1855 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1856 $contributionId, 'contact_id'
1860 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1861 $activityTypeId = array_search('Contribution', $activityTypeIds);
1863 if ($activityTypeId && $contributorId) {
1865 SELECT civicrm_activity_contact.contact_id
1866 FROM civicrm_activity_contact
1867 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1868 WHERE civicrm_activity.activity_type_id = %1
1869 AND civicrm_activity.source_record_id = %2
1870 AND civicrm_activity_contact.record_type_id = %3
1873 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1874 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1877 1 => array($activityTypeId, 'Integer'),
1878 2 => array($contributionId, 'Integer'),
1879 3 => array($sourceID, 'Integer'),
1882 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1884 // for on behalf contribution source is individual and contributor is organization
1885 if ($sourceContactId && $sourceContactId != $contributorId) {
1886 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1887 // get rel type id for employee of relation
1888 foreach ($relationshipTypeIds as $id => $typeVals) {
1889 if ($typeVals['name_a_b'] == 'Employee of') {
1890 $relationshipTypeId = $id;
1895 $rel = new CRM_Contact_DAO_Relationship();
1896 $rel->relationship_type_id
= $relationshipTypeId;
1897 $rel->contact_id_a
= $sourceContactId;
1898 $rel->contact_id_b
= $contributorId;
1899 if ($rel->find(TRUE)) {
1900 $ids['individual_id'] = $rel->contact_id_a
;
1901 $ids['organization_id'] = $rel->contact_id_b
;
1912 public static function getContributionDates() {
1913 $config = CRM_Core_Config
::singleton();
1914 $currentMonth = date('m');
1915 $currentDay = date('d');
1916 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1917 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1918 (int ) $config->fiscalYearStart
['d'] > $currentDay
1921 $year = date('Y') - 1;
1926 $year = array('Y' => $year);
1927 $yearDate = $config->fiscalYearStart
;
1928 $yearDate = array_merge($year, $yearDate);
1929 $yearDate = CRM_Utils_Date
::format($yearDate);
1931 $monthDate = date('Ym') . '01';
1937 'yearDate' => $yearDate,
1938 'monthDate' => $monthDate,
1943 * Load objects relations to contribution object
1944 * Objects are stored in the $_relatedObjects property
1945 * In the first instance we are just moving functionality from BASEIpn -
1946 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1948 * Note that the unit test for the BaseIPN class tests this function
1950 * @param array $input
1951 * Input as delivered from Payment Processor.
1953 * Ids as Loaded by Payment Processor.
1954 * @param bool $required
1955 * Is Payment processor / contribution page required.
1956 * @param bool $loadAll
1957 * Load all related objects - even where id not passed in? (allows API to call this).
1962 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1964 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1965 if (empty($ids['contact']) && isset($this->contact_id
)) {
1966 $ids['contact'] = $this->contact_id
;
1969 if (empty($this->_component
)) {
1970 if (!empty($ids['event'])) {
1971 $this->_component
= 'event';
1974 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1977 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1978 $contributionType = new CRM_Financial_BAO_FinancialType();
1979 $contributionType->id
= $this->financial_type_id
;
1980 if (!$contributionType->find(TRUE)) {
1981 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1983 if (!empty($ids['contact'])) {
1984 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1985 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1986 $this->_relatedObjects
['contact']->find(TRUE);
1988 $this->_relatedObjects
['contributionType'] = $contributionType;
1990 if ($this->_component
== 'contribute') {
1991 // retrieve the other optional objects first so
1992 // stuff down the line can use this info and do things
1994 //in any case get the memberships associated with the contribution
1995 //because we now support multiple memberships w/ price set
1996 // see if there are any other memberships to be considered for same contribution.
1998 SELECT membership_id
1999 FROM civicrm_membership_payment
2000 WHERE contribution_id = %1 ";
2001 $params = array(1 => array($this->id
, 'Integer'));
2003 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2004 while ($dao->fetch()) {
2005 if ($dao->membership_id
) {
2006 if (!is_array($ids['membership'])) {
2007 $ids['membership'] = array();
2009 $ids['membership'][] = $dao->membership_id
;
2013 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2014 foreach ($ids['membership'] as $id) {
2016 $membership = new CRM_Member_BAO_Membership();
2017 $membership->id
= $id;
2018 if (!$membership->find(TRUE)) {
2019 throw new Exception("Could not find membership record: $id");
2021 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2022 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2023 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2024 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2025 $membership->free();
2030 if (!empty($ids['pledge_payment'])) {
2032 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2033 if (empty($paymentID)) {
2036 $payment = new CRM_Pledge_BAO_PledgePayment();
2037 $payment->id
= $paymentID;
2038 if (!$payment->find(TRUE)) {
2039 throw new Exception("Could not find pledge payment record: " . $paymentID);
2041 $this->_relatedObjects
['pledge_payment'][] = $payment;
2045 if (!empty($ids['contributionRecur'])) {
2046 $recur = new CRM_Contribute_BAO_ContributionRecur();
2047 $recur->id
= $ids['contributionRecur'];
2048 if (!$recur->find(TRUE)) {
2049 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2051 $this->_relatedObjects
['contributionRecur'] = &$recur;
2052 //get payment processor id from recur object.
2053 $paymentProcessorID = $recur->payment_processor_id
;
2055 //for normal contribution get the payment processor id.
2056 if (!$paymentProcessorID) {
2057 if ($this->contribution_page_id
) {
2058 // get the payment processor id from contribution page
2059 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2060 $this->contribution_page_id
,
2064 //fail to load payment processor id.
2065 elseif (empty($ids['pledge_payment'])) {
2066 $loadObjectSuccess = TRUE;
2068 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2070 return $loadObjectSuccess;
2075 // we are in event mode
2076 // make sure event exists and is valid
2077 $event = new CRM_Event_BAO_Event();
2078 $event->id
= $ids['event'];
2079 if ($ids['event'] &&
2082 throw new Exception("Could not find event: " . $ids['event']);
2085 $this->_relatedObjects
['event'] = &$event;
2087 $participant = new CRM_Event_BAO_Participant();
2088 $participant->id
= $ids['participant'];
2089 if ($ids['participant'] &&
2090 !$participant->find(TRUE)
2092 throw new Exception("Could not find participant: " . $ids['participant']);
2094 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2096 $this->_relatedObjects
['participant'] = &$participant;
2098 if (!$paymentProcessorID) {
2099 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2103 if ($paymentProcessorID) {
2104 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2105 $this->is_test ?
'test' : 'live'
2107 $ids['paymentProcessor'] = $paymentProcessorID;
2108 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2110 elseif ($required) {
2111 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2118 * Create array of message information - ie. return html version, txt version, to field
2120 * @param array $input
2121 * Incoming information.
2122 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2123 * just check presence of recur object but maintaining legacy approach
2126 * IDs of related objects.
2127 * @param array $values
2128 * Any values that may have already been compiled by calling process.
2129 * This is augmented by values 'gathered' by gatherMessageValues
2130 * @param bool $recur
2131 * @param bool $returnMessageText
2132 * Distinguishes between whether to send message or return.
2133 * message text. We are working towards this function ALWAYS returning message text & calling
2134 * function doing emails / pdfs with it
2140 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2141 if (empty($this->_relatedObjects
)) {
2142 $this->loadRelatedObjects($input, $ids);
2144 if (empty($this->_component
)) {
2145 $this->_component
= CRM_Utils_Array
::value('component', $input);
2148 //not really sure what params might be passed in but lets merge em into values
2149 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2150 $template = CRM_Core_Smarty
::singleton();
2151 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2152 //what does recur 'mean here - to do with payment processor return functionality but
2153 // what is the importance
2154 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2155 $paymentObject = &CRM_Core_Payment
::singleton(
2156 $this->is_test ?
'test' : 'live',
2157 $this->_relatedObjects
['paymentProcessor']
2160 $entityID = $entity = NULL;
2161 if (isset($ids['contribution'])) {
2162 $entity = 'contribution';
2163 $entityID = $ids['contribution'];
2165 if (!empty($ids['membership'])) {
2166 //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
2167 // 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
2168 // line having loaded an array
2169 $ids['membership'] = (array) $ids['membership'];
2170 $entity = 'membership';
2171 $entityID = $ids['membership'][0];
2174 $url = $paymentObject->subscriptionURL($entityID, $entity);
2175 $template->assign('cancelSubscriptionUrl', $url);
2177 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2178 $template->assign('updateSubscriptionBillingUrl', $url);
2180 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2181 $template->assign('updateSubscriptionUrl', $url);
2183 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2184 //direct mode showing billing block, so use directIPN for temporary
2185 $template->assign('contributeMode', 'directIPN');
2188 // todo remove strtolower - check consistency
2189 if (strtolower($this->_component
) == 'event') {
2190 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2191 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2195 $values['contribution_id'] = $this->id
;
2196 if (!empty($ids['related_contact'])) {
2197 $values['related_contact'] = $ids['related_contact'];
2198 if (isset($ids['onbehalf_dupe_alert'])) {
2199 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2201 $entityBlock = array(
2202 'contact_id' => $ids['contact'],
2203 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2204 'Home', 'id', 'name'
2207 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2208 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2211 if ($this->is_test
) {
2214 if (!empty($this->_relatedObjects
['membership'])) {
2215 foreach ($this->_relatedObjects
['membership'] as $membership) {
2216 if ($membership->id
) {
2217 $values['isMembership'] = TRUE;
2219 // need to set the membership values here
2220 $template->assign('membership_assign', 1);
2221 $template->assign('membership_name',
2222 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2224 $template->assign('mem_start_date', $membership->start_date
);
2225 $template->assign('mem_join_date', $membership->join_date
);
2226 $template->assign('mem_end_date', $membership->end_date
);
2227 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2228 $template->assign('mem_status', $membership_status);
2229 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2230 $template->assign('is_pay_later', 1);
2233 // if separate payment there are two contributions recorded and the
2234 // admin will need to send a receipt for each of them separately.
2235 // we dont link the two in the db (but can potentially infer it if needed)
2236 $template->assign('is_separate_payment', 0);
2238 if ($recur && $paymentObject) {
2239 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2240 $template->assign('cancelSubscriptionUrl', $url);
2241 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2242 $template->assign('updateSubscriptionBillingUrl', $url);
2243 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2244 $template->assign('updateSubscriptionUrl', $url);
2247 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2250 // otherwise if its about sending emails, continue sending without return, as we
2251 // don't want to exit the loop.
2256 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2262 * Gather values for contribution mail - this function has been created
2263 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2264 * Values related to the contribution in question are gathered
2266 * @param array $input
2267 * Input into function (probably from payment processor).
2268 * @param array $values
2270 * The set of ids related to the input.
2274 public function _gatherMessageValues($input, &$values, $ids = array()) {
2275 // set display address of contributor
2276 if ($this->address_id
) {
2277 $addressParams = array('id' => $this->address_id
);
2278 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2279 $addressDetails = array_values($addressDetails);
2280 $values['address'] = $addressDetails[0]['display'];
2282 if ($this->_component
== 'contribute') {
2283 if (isset($this->contribution_page_id
)) {
2284 CRM_Contribute_BAO_ContributionPage
::setValues(
2285 $this->contribution_page_id
,
2288 if ($this->contribution_page_id
) {
2289 // CRM-8254 - override default currency if applicable
2290 $config = CRM_Core_Config
::singleton();
2291 $config->defaultCurrency
= CRM_Utils_Array
::value(
2294 $config->defaultCurrency
2298 // no contribution page -probably back office
2300 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2301 $values['is_email_receipt'] = 1;
2302 $values['title'] = 'Contribution';
2304 // set lineItem for contribution
2306 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2307 if (!empty($lineItem)) {
2308 $itemId = key($lineItem);
2309 foreach ($lineItem as &$eachItem) {
2310 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2311 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2312 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2313 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2316 $values['lineItem'][0] = $lineItem;
2317 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2321 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2325 // if this is onbehalf of contribution then set related contact
2326 if (!empty($relatedContact['individual_id'])) {
2327 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2332 $eventParams = array(
2333 'id' => $this->_relatedObjects
['event']->id
,
2335 $values['event'] = array();
2337 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2339 //get location details
2340 $locationParams = array(
2341 'entity_id' => $this->_relatedObjects
['event']->id
,
2342 'entity_table' => 'civicrm_event',
2344 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2346 $ufJoinParams = array(
2347 'entity_table' => 'civicrm_event',
2348 'entity_id' => $ids['event'],
2349 'module' => 'CiviEvent',
2352 list($custom_pre_id,
2354 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2356 $values['custom_pre_id'] = $custom_pre_id;
2357 $values['custom_post_id'] = $custom_post_ids;
2359 // set lineItem for event contribution
2361 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2362 if (!empty($participantIds)) {
2363 foreach ($participantIds as $pIDs) {
2364 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2365 if (!CRM_Utils_System
::isNull($lineItem)) {
2366 $values['lineItem'][] = $lineItem;
2377 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2378 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2379 * Note we send directly from this function in some cases because it is only partly refactored
2380 * Don't call this function directly as the signature will change
2384 * @param CRM_Core_SMARTY $template
2385 * @param bool $recur
2386 * @param bool $returnMessageText
2390 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2391 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2392 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2393 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2394 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2395 $template->assign('useForMember', TRUE);
2397 //assign honor information to receipt message
2398 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2400 if (isset($softRecord['soft_credit'])) {
2401 //if id of contribution page is present
2402 if (!empty($values['id'])) {
2403 $values['honor'] = array(
2404 'honor_profile_values' => array(),
2405 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2406 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2408 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2410 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2411 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2414 //offline contribution
2415 $softCreditTypes = $softCredits = array();
2416 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2417 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2418 $softCredits[$key] = array(
2419 'Name' => $softCredit['contact_name'],
2420 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2423 $template->assign('softCreditTypes', $softCreditTypes);
2424 $template->assign('softCredits', $softCredits);
2428 $dao = new CRM_Contribute_DAO_ContributionProduct();
2429 $dao->contribution_id
= $this->id
;
2430 if ($dao->find(TRUE)) {
2431 $premiumId = $dao->product_id
;
2432 $template->assign('option', $dao->product_option
);
2434 $productDAO = new CRM_Contribute_DAO_Product();
2435 $productDAO->id
= $premiumId;
2436 $productDAO->find(TRUE);
2437 $template->assign('selectPremium', TRUE);
2438 $template->assign('product_name', $productDAO->name
);
2439 $template->assign('price', $productDAO->price
);
2440 $template->assign('sku', $productDAO->sku
);
2442 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2443 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2444 if (empty($amount) && isset($this->total_amount
)) {
2445 $amount = $this->total_amount
;
2447 $template->assign('amount', $amount);
2448 // add the new contribution values
2449 if (strtolower($this->_component
) == 'contribute') {
2451 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2452 $softDAO->contribution_id
= $this->id
;
2453 if ($softDAO->find(TRUE)) {
2454 $template->assign('pcpBlock', TRUE);
2455 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2456 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2457 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2459 //assign the pcp page title for email subject
2460 $pcpDAO = new CRM_PCP_DAO_PCP();
2461 $pcpDAO->id
= $softDAO->pcp_id
;
2462 if ($pcpDAO->find(TRUE)) {
2463 $template->assign('title', $pcpDAO->title
);
2468 if ($this->financial_type_id
) {
2469 $values['financial_type_id'] = $this->financial_type_id
;
2472 $template->assign('trxn_id', $this->trxn_id
);
2473 $template->assign('receive_date',
2474 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2476 $template->assign('contributeMode', 'notify');
2477 $template->assign('action', $this->is_test ?
1024 : 1);
2478 $template->assign('receipt_text',
2479 CRM_Utils_Array
::value('receipt_text',
2483 $template->assign('is_monetary', 1);
2484 $template->assign('is_recur', (bool) $recur);
2485 $template->assign('currency', $this->currency
);
2486 $template->assign('address', CRM_Utils_Address
::format($input));
2487 if ($this->_component
== 'event') {
2488 $template->assign('title', $values['event']['title']);
2489 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2490 $viewRoles = array();
2491 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2492 $viewRoles[] = $participantRoles[$v];
2494 $values['event']['participant_role'] = implode(', ', $viewRoles);
2495 $template->assign('event', $values['event']);
2496 $template->assign('location', $values['location']);
2497 $template->assign('customPre', $values['custom_pre_id']);
2498 $template->assign('customPost', $values['custom_post_id']);
2501 if ($this->_relatedObjects
['participant']->is_test
) {
2505 $values['params'] = array();
2506 //to get email of primary participant.
2507 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2508 $primaryAmount[] = array(
2509 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2510 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2512 //build an array of cId/pId of participants
2513 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2514 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2515 //send receipt to additional participant if exists
2516 if (count($additionalIDs)) {
2517 $template->assign('isPrimary', 0);
2518 $template->assign('customProfile', NULL);
2519 //set additionalParticipant true
2520 $values['params']['additionalParticipant'] = TRUE;
2521 foreach ($additionalIDs as $pId => $cId) {
2523 //to change the status pending to completed
2524 $additional = new CRM_Event_DAO_Participant();
2525 $additional->id
= $pId;
2526 $additional->contact_id
= $cId;
2527 $additional->find(TRUE);
2528 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2529 $additional->status_id
= 1;
2530 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2531 //if additional participant dont have email
2533 if (!$additionalParticipantInfo) {
2534 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2536 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2537 $primaryAmount[] = array(
2538 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2539 'amount' => $additional->fee_amount
,
2541 $additional->save();
2542 $additional->free();
2543 $template->assign('amount', $amount);
2544 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2548 //build an array of custom profile and assigning it to template
2549 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2551 if (count($customProfile)) {
2552 $template->assign('customProfile', $customProfile);
2555 // for primary contact
2556 $values['params']['additionalParticipant'] = FALSE;
2557 $template->assign('isPrimary', 1);
2558 $template->assign('amount', $primaryAmount);
2559 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2560 if ($this->payment_instrument_id
) {
2561 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2562 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2564 // carry paylater, since we did not created billing,
2565 // so need to pull email from primary location, CRM-4395
2566 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2572 * Check whether payment processor supports
2573 * cancellation of contribution subscription
2575 * @param int $contributionId
2578 * @param bool $isNotCancelled
2582 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2583 $cacheKeyString = "$contributionId";
2584 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2586 static $supportsCancel = array();
2588 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2589 $supportsCancel[$cacheKeyString] = FALSE;
2590 $isCancelled = FALSE;
2592 if ($isNotCancelled) {
2593 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2596 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2597 if (!empty($paymentObject)) {
2598 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2601 return $supportsCancel[$cacheKeyString];
2605 * Check whether subscription is already cancelled
2607 * @param int $contributionId
2611 * contribution status
2613 public static function isSubscriptionCancelled($contributionId) {
2615 SELECT cr.contribution_status_id
2616 FROM civicrm_contribution_recur cr
2617 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2618 WHERE con.id = %1 LIMIT 1";
2619 $params = array(1 => array($contributionId, 'Integer'));
2620 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2621 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2622 if ($status == 'Cancelled') {
2629 * Create all financial accounts entry
2631 * @param array $params
2632 * Contribution object, line item array and params for trxn.
2635 * @param array $financialTrxnValues
2637 * @return null|object
2639 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2640 $skipRecords = $update = $return = $isRelatedId = FALSE;
2642 $additionalParticipantId = array();
2643 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2645 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2646 $entityId = $params['participant_id'];
2647 $entityTable = 'civicrm_participant';
2648 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2650 elseif (!empty($params['membership_id'])) {
2651 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2652 // are created off one contribution should be handled elsewhere
2653 $entityId = $params['membership_id'];
2654 $entityTable = 'civicrm_membership';
2657 $entityId = $params['contribution']->id
;
2658 $entityTable = 'civicrm_contribution';
2661 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2662 $isRelatedId = TRUE;
2665 $entityID[] = $entityId;
2666 if (!empty($additionalParticipantId)) {
2667 $entityID +
= $additionalParticipantId;
2669 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2670 if (empty($params['prevContribution'])) {
2677 $statusId = $params['contribution']->contribution_status_id
;
2678 // CRM-13964 partial payment
2679 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2680 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2682 $partialAmtPay = $params['partial_amount_pay'];
2683 $partialAmtTotal = $params['partial_payment_total'];
2685 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2686 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2687 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2688 $params['total_amount'] = $partialAmtPay;
2690 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2691 if (empty($balanceTrxnInfo['trxn_id'])) {
2692 // create new balance transaction record
2693 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2694 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2696 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2697 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2698 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2699 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2700 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2701 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2702 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2703 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2704 $balanceTrxnParams['status_id'] = $statusId;
2705 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2706 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2707 if (!empty($params['payment_processor'])) {
2708 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2710 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2714 // build line item array if its not set in $params
2715 if (empty($params['line_item']) ||
$additionalParticipantId) {
2716 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2719 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2720 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2722 $skipRecords = TRUE;
2723 $pendingStatus = array(
2724 array_search('Pending', $contributionStatuses),
2725 array_search('In Progress', $contributionStatuses),
2727 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2728 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2729 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2731 elseif (!empty($params['payment_processor'])) {
2732 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2734 elseif (!empty($params['payment_instrument_id'])) {
2735 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2738 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2739 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2740 $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);
2743 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2744 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2745 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2748 //build financial transaction params
2749 $trxnParams = array(
2750 'contribution_id' => $params['contribution']->id
,
2751 'to_financial_account_id' => $params['to_financial_account_id'],
2752 'trxn_date' => date('YmdHis'),
2753 'total_amount' => $totalAmount,
2754 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2755 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2756 'currency' => $params['contribution']->currency
,
2757 'trxn_id' => $params['contribution']->trxn_id
,
2758 'status_id' => $statusId,
2759 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2760 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2763 if (!empty($params['payment_processor'])) {
2764 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2767 if (isset($fromFinancialAccountId)) {
2768 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2771 // consider external values passed for recording transaction entry
2772 if (!empty($financialTrxnValues)) {
2773 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2776 $params['trxnParams'] = $trxnParams;
2778 if (!empty($params['prevContribution'])) {
2779 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2780 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2781 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2782 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2783 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2785 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2786 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2787 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2789 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2790 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2793 //if financial type is changed
2794 if (!empty($params['financial_type_id']) &&
2795 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2797 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2798 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2799 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2800 if ($oldFinancialAccount != $newFinancialAccount) {
2801 $params['total_amount'] = 0;
2802 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2803 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2804 $params['prevContribution']->financial_type_id
, $relationTypeId);
2807 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2808 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2809 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2812 self
::updateFinancialAccounts($params, 'changeFinancialType');
2813 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2814 $params['financial_account_id'] = $newFinancialAccount;
2815 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2816 self
::updateFinancialAccounts($params);
2817 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2821 //Update contribution status
2822 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2823 if (!empty($params['contribution_status_id']) &&
2824 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2826 //Update Financial Records
2827 self
::updateFinancialAccounts($params, 'changedStatus');
2830 // change Payment Instrument for a Completed contribution
2831 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2832 // instrument is null and now new payment instrument is added along with the payment
2833 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2834 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2835 if (array_key_exists('payment_instrument_id', $params)) {
2836 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2837 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2838 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2840 //check if status is changed from Pending to Completed
2841 // do not update payment instrument changes for Pending to Completed
2842 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2843 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2845 // for all other statuses create new financial records
2846 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2847 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2848 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2851 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2852 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2853 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2855 // for any other payment instrument changes create new financial records
2856 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2857 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2858 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2860 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2861 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2863 // another special case when check number is changed, create new financial records
2864 // create financial trxn with negative amount
2865 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2866 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2867 // create financial trxn with positive amount
2868 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2869 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2870 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2874 //if Change contribution amount
2875 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2876 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2877 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2878 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2879 if (isset($totalAmount) &&
2880 $totalAmount != $params['prevContribution']->total_amount
2882 //Update Financial Records
2883 $params['trxnParams']['from_financial_account_id'] = NULL;
2884 self
::updateFinancialAccounts($params, 'changedAmount');
2889 // records finanical trxn and entity financial trxn
2890 // also make it available as return value
2891 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2892 $params['entity_id'] = $financialTxn->id
;
2895 // record line items and finacial items
2896 if (empty($params['skipLineItem'])) {
2897 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2900 // create batch entry if batch_id is passed
2901 if (!empty($params['batch_id'])) {
2902 $entityParams = array(
2903 'batch_id' => $params['batch_id'],
2904 'entity_table' => 'civicrm_financial_trxn',
2905 'entity_id' => $financialTxn->id
,
2907 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2910 // when a fee is charged
2911 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2912 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2915 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2916 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2918 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2919 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2920 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2922 unset($params['line_item']);
2928 * Update all financial accounts entry
2930 * @param array $params
2931 * Contribution object, line item array and params for trxn.
2933 * @param string $context
2936 * @param null $skipTrxn
2939 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2940 $itemAmount = $trxnID = NULL;
2941 //get all the statuses
2942 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2943 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2944 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2945 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2946 && $context == 'changePaymentInstrument'
2950 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2951 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2953 if ($context == 'changedStatus') {
2954 //get all the statuses
2955 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2957 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2958 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2959 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2961 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2963 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2964 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2966 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2967 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2968 $params['trxnParams']['to_financial_account_id'] = NULL;
2969 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2971 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2972 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2973 $financialTypeID, $relationTypeId);
2975 $itemAmount = $params['trxnParams']['total_amount'];
2977 elseif ($context == 'changePaymentInstrument') {
2978 if ($params['trxnParams']['total_amount'] < 0) {
2979 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2980 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2981 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2982 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2986 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2987 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2990 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2991 $params['entity_id'] = $trxn->id
;
2993 if ($context == 'changedStatus') {
2994 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2995 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2996 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
2998 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2999 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3001 $entityParams = array(
3002 'entity_table' => 'civicrm_financial_item',
3003 'financial_trxn_id' => $trxn->id
,
3005 if (empty($params['line_item'])) {
3007 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3008 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3009 // & this can be removed
3012 foreach ($params['line_item'] as $fieldId => $fields) {
3013 foreach ($fields as $fieldValueId => $fieldValues) {
3015 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3016 2 => array($fieldValues['id'], 'Integer'),
3018 CRM_Core_DAO
::executeQuery($query, $fparams);
3020 1 => array($fieldValues['id'], 'Integer'),
3022 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3023 while ($financialItem->fetch()) {
3024 $entityParams['entity_id'] = $financialItem->id
;
3025 $entityParams['amount'] = $financialItem->amount
;
3026 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3033 if ($context != 'changePaymentInstrument') {
3034 $itemParams['entity_table'] = 'civicrm_line_item';
3035 $trxnIds['id'] = $params['entity_id'];
3036 foreach ($params['line_item'] as $fieldId => $fields) {
3037 foreach ($fields as $fieldValueId => $fieldValues) {
3038 $prevParams['entity_id'] = $fieldValues['id'];
3039 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3041 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3042 if ($params['contribution']->receive_date
) {
3043 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3046 $financialAccount = $prevfinancialItem->financial_account_id
;
3047 if (!empty($params['financial_account_id'])) {
3048 $financialAccount = $params['financial_account_id'];
3051 $currency = $params['prevContribution']->currency
;
3052 if ($params['contribution']->currency
) {
3053 $currency = $params['contribution']->currency
;
3056 if (!empty($params['is_quick_config'])) {
3057 $amount = $itemAmount;
3059 $amount = $params['total_amount'];
3063 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3064 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3068 $amount = $diff * $fieldValues['line_total'];
3071 $itemParams = array(
3072 'transaction_date' => $receiveDate,
3073 'contact_id' => $params['prevContribution']->contact_id
,
3074 'currency' => $currency,
3075 'amount' => $amount,
3076 'description' => $prevfinancialItem->description
,
3077 'status_id' => $prevfinancialItem->status_id
,
3078 'financial_account_id' => $financialAccount,
3079 'entity_table' => 'civicrm_line_item',
3080 'entity_id' => $fieldValues['id'],
3082 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3084 if ($fieldValues['tax_amount']) {
3085 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3086 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3087 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3088 $itemParams['description'] = $taxTerm;
3089 if ($fieldValues['financial_type_id']) {
3090 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3092 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3100 * Check status validation on update of a contribution
3102 * @param array $values
3103 * Previous form values before submit.
3105 * @param array $fields
3106 * The input form values.
3108 * @param array $errors
3113 public static function checkStatusValidation($values, &$fields, &$errors) {
3114 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3115 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3116 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3120 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3121 $checkStatus = array(
3122 'Cancelled' => array('Completed', 'Refunded'),
3123 'Completed' => array('Cancelled', 'Refunded'),
3124 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3125 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3126 'Refunded' => array('Cancelled', 'Completed'),
3129 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3130 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3131 1 => $contributionStatuses[$values['contribution_status_id']],
3132 2 => $contributionStatuses[$fields['contribution_status_id']],
3138 * Delete contribution of contact
3142 * @param int $contactId
3146 public static function deleteContactContribution($contactId) {
3147 $contribution = new CRM_Contribute_DAO_Contribution();
3148 $contribution->contact_id
= $contactId;
3149 $contribution->find();
3150 while ($contribution->fetch()) {
3151 self
::deleteContribution($contribution->id
);
3156 * Get options for a given contribution field.
3157 * @see CRM_Core_DAO::buildOptions
3159 * @param string $fieldName
3160 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3161 * @param array $props whatever is known about this dao object.
3163 * @return array|bool
3165 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3166 $className = __CLASS__
;
3168 switch ($fieldName) {
3169 // This field is not part of this object but the api supports it
3170 case 'payment_processor':
3171 $className = 'CRM_Contribute_BAO_ContributionPage';
3172 // Filter results by contribution page
3173 if (!empty($props['contribution_page_id'])) {
3174 $page = civicrm_api('contribution_page', 'getsingle', array(
3176 'id' => ($props['contribution_page_id']),
3178 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3179 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3183 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3184 case 'honor_type_id':
3185 $className = 'CRM_Contribute_BAO_ContributionSoft';
3186 $fieldName = 'soft_credit_type_id';
3187 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3190 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3194 * Validate financial type
3198 * @param int $financialTypeId
3199 * Financial Type id.
3201 * @param string $relationName
3203 * @return array|bool
3205 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3206 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3207 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3209 if (!$financialAccount) {
3210 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3217 * Function to record additional payment for partial and refund contributions
3219 * @param int $contributionId
3220 * is the invoice contribution id (got created after processing participant payment).
3221 * @param array $trxnsData
3222 * to take user provided input of transaction details.
3223 * @param string $paymentType
3224 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3225 * @param int $participantId
3227 * @return null|object
3229 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3230 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3231 $getInfoOf['id'] = $contributionId;
3232 $defaults = array();
3233 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3235 if ($paymentType == 'owed') {
3236 // build params for recording financial trxn entry
3237 $params['contribution'] = $contributionDAO;
3238 $params = array_merge($defaults, $params);
3239 $params['skipLineItem'] = TRUE;
3240 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3241 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3242 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3245 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3246 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3247 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3249 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3250 if (!empty($trxnId)) {
3251 $trxnId = $trxnId['trxn_id'];
3253 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3254 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3257 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3258 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3259 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3263 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3264 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3265 FROM civicrm_financial_trxn ft
3266 LEFT JOIN civicrm_entity_financial_trxn eft
3267 ON (ft.id = eft.financial_trxn_id)
3268 WHERE eft.entity_table = 'civicrm_contribution'
3269 AND eft.entity_id = {$contributionId}
3270 AND ft.to_financial_account_id != {$toFinancialAccount}
3271 AND ft.status_id = {$statusId}
3273 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3276 if ($contributionDAO->total_amount
== $sumOfPayments) {
3277 // update contribution status and
3278 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3279 $contributionDAO->contribution_status_id
= $statusId;
3280 $contributionDAO->cancel_date
= 'null';
3281 $contributionDAO->cancel_reason
= NULL;
3282 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3283 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3284 $contributionDAO->save();
3286 //Change status of financial record too
3287 $financialTrxn->status_id
= $statusId;
3288 $financialTrxn->save();
3290 // note : not using the self::add method,
3291 // the reason because it performs 'status change' related code execution for financial records
3292 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3293 // are coded below i.e. just updating financial_item status to 'Paid'
3295 if ($participantId) {
3296 // update participant status
3297 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3298 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3299 foreach ($ids as $val) {
3300 $participantUpdate['id'] = $val;
3301 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3302 CRM_Event_BAO_Participant
::add($participantUpdate);
3306 // update financial item statuses
3307 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3308 $paidStatus = array_search('Paid', $financialItemStatus);
3310 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3311 $sqlFinancialItemUpdate = "
3312 UPDATE civicrm_financial_item fi
3313 LEFT JOIN civicrm_entity_financial_trxn eft
3314 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3315 SET status_id = {$paidStatus}
3316 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3318 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3321 elseif ($paymentType == 'refund') {
3322 // build params for recording financial trxn entry
3323 $params['contribution'] = $contributionDAO;
3324 $params = array_merge($defaults, $params);
3325 $params['skipLineItem'] = TRUE;
3326 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3327 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3329 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3330 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3331 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3333 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3335 // note : not using the self::add method,
3336 // the reason because it performs 'status change' related code execution for financial records
3337 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3338 // are coded below i.e. just updating financial_item status to 'Paid'
3339 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3341 // add financial item entry
3342 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3343 $getLine['entity_id'] = $contributionDAO->id
;
3344 $getLine['entity_table'] = 'civicrm_contribution';
3345 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3346 if (!empty($lineItemId->id
)) {
3347 $addFinancialEntry = array(
3348 'transaction_date' => $financialTrxn->trxn_date
,
3349 'contact_id' => $contributionDAO->contact_id
,
3350 'amount' => $financialTrxn->total_amount
,
3351 'status_id' => array_search('Paid', $financialItemStatus),
3352 'entity_id' => $lineItemId->id
,
3353 'entity_table' => 'civicrm_line_item',
3355 $trxnIds['id'] = $financialTrxn->id
;
3356 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3358 if ($participantId) {
3359 // update participant status
3360 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3361 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3362 foreach ($ids as $val) {
3363 $participantUpdate['id'] = $val;
3364 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3365 CRM_Event_BAO_Participant
::add($participantUpdate);
3370 // activity creation
3371 if (!empty($financialTrxn)) {
3372 if ($participantId) {
3373 $inputParams['id'] = $participantId;
3376 $component = 'event';
3377 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3378 $entityObj = $entityObj[$participantId];
3380 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3382 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3384 return $financialTrxn;
3390 * @param $activityType
3392 * @param int $contributionId
3394 * @throws CRM_Core_Exception
3396 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3397 if ($component == 'event') {
3398 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3399 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3400 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3401 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3402 $targetCid = $entityObj->contact_id
;
3403 // source record id would be the contribution id
3404 $srcRecId = $contributionId;
3408 $activityParams = array(
3409 'source_contact_id' => $targetCid,
3410 'source_record_id' => $srcRecId,
3411 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3415 'subject' => $subject,
3416 'activity_date_time' => $date,
3417 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3421 'skipRecentView' => TRUE,
3424 // create activity with target contacts
3425 $session = CRM_Core_Session
::singleton();
3426 $id = $session->get('userID');
3428 $activityParams['source_contact_id'] = $id;
3429 $activityParams['target_contact_id'][] = $targetCid;
3431 CRM_Activity_BAO_Activity
::create($activityParams);
3435 * Get list of payments displayed by Contribute_Page_PaymentInfo
3439 * @param bool $getTrxnInfo
3440 * @param bool $usingLineTotal
3444 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3445 if ($component == 'event') {
3446 $entity = 'participant';
3447 $entityTable = 'civicrm_participant';
3448 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3450 if (!$contributionId) {
3451 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3452 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3453 $id = $primaryParticipantId;
3455 if (!$contributionId) {
3460 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3461 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3467 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3468 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3471 if (empty($total) ||
$usingLineTotal) {
3472 // for additional participants
3473 if ($entityTable == 'civicrm_participant') {
3474 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3476 foreach ($ids as $val) {
3477 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3481 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3485 $baseTrxnId = $total['trxn_id'];
3486 $total = $total['total_amount'];
3489 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3490 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3492 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3493 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3494 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3496 if ($paymentBalance == 0 && $contributionIsPayLater) {
3497 $paymentBalance = $total;
3500 $info['total'] = $total;
3501 $info['paid'] = $total - $paymentBalance;
3502 $info['balance'] = $paymentBalance;
3504 $info['component'] = $component;
3505 $info['payLater'] = $contributionIsPayLater;
3507 if ($getTrxnInfo && $baseTrxnId) {
3508 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3510 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3511 FROM civicrm_contribution con
3512 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3513 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3514 WHERE con.id = {$contributionId}
3517 // conditioned WHERE clause
3519 // if balance trxn exists don't include details of it in transaction info
3520 $sql .= " AND ft.id != {$baseTrxnId} ";
3522 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3524 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3525 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3526 while ($resultDAO->fetch()) {
3527 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3528 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3530 'total_amount' => $resultDAO->total_amount
,
3531 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3532 'payment_instrument' => $paidByLabel,
3533 'receive_date' => $resultDAO->trxn_date
,
3534 'trxn_id' => $resultDAO->trxn_id
,
3535 'status' => $statuses[$resultDAO->status_id
],
3537 if ($paidByName == 'Check') {
3538 $val['check_number'] = $resultDAO->check_number
;
3542 $info['transaction'] = $rows;
3548 * Get financial account id has 'Sales Tax Account is'
3549 * account relationship with financial type
3551 * @param int $financialTypeId
3553 * @return FinancialAccountId
3555 public static function getFinancialAccountId($financialTypeId) {
3556 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3557 $searchParams = array(
3558 'entity_table' => 'civicrm_financial_type',
3559 'entity_id' => $financialTypeId,
3560 'account_relationship' => $accountRel,
3563 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3565 return CRM_Utils_Array
::value('financial_account_id', $result);
3571 * @param array $params
3572 * @param bool $isLineItem
3576 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3577 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3579 // Update contribution.
3580 if (!empty($params['id'])) {
3581 $id = $params['id'];
3582 $values = $ids = array();
3583 $contrbutionParams = array('id' => $id);
3584 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3586 // To assign pervious finantial type on update of contribution
3587 if (!isset($params['financial_type_id'])) {
3588 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3590 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3591 // Assisn tax Amount on update of contrbution
3592 if (!empty($prevContributionValue->tax_amount
)) {
3593 $params['tax_amount'] = 'null';
3594 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3595 foreach ($params['line_item'] as $setID => $priceField) {
3596 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3597 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3604 // New Contrbution and update of contribution with tax rate financial type
3605 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3606 empty($params['skipLineItem']) && !$isLineItem
3608 $taxRateParams = $taxRates[$params['financial_type_id']];
3609 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3610 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3612 // Get Line Item on update of contribution
3613 if (isset($params['id'])) {
3614 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3617 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3619 foreach ($params['line_item'] as $setID => $priceField) {
3620 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3621 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3624 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3626 elseif (isset($params['api.line_item.create'])) {
3627 // Update total amount of contribution using lineItem
3628 $taxAmountArray = array();
3629 foreach ($params['api.line_item.create'] as $key => $value) {
3630 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3631 $taxRate = $taxRates[$value['financial_type_id']];
3632 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3633 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3636 $params['tax_amount'] = array_sum($taxAmountArray);
3637 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3640 // update line item of contrbution
3641 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3642 $taxRate = $taxRates[$params['financial_type_id']];
3643 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3644 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);