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 and vice-versa.
498 * This function is used by both the web form layer and the api. Note that
499 * the api needs the name => value conversion, also the view layer typically
500 * requires value => name conversion
502 * @param array $defaults
503 * @param string $property
504 * @param array $lookup
505 * @param bool $reverse
509 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
510 $id = $property . '_id';
512 $src = $reverse ?
$property : $id;
513 $dst = $reverse ?
$id : $property;
515 if (!array_key_exists($src, $defaults)) {
519 $look = $reverse ?
array_flip($lookup) : $lookup;
521 if (is_array($look)) {
522 if (!array_key_exists($defaults[$src], $look)) {
526 $defaults[$dst] = $look[$defaults[$src]];
531 * Takes a bunch of params that are needed to match certain criteria and
532 * retrieves the relevant objects. We'll tweak this function to be more
533 * full featured over a period of time. This is the inverse function of
534 * create. It also stores all the retrieved values in the default array
536 * @param array $params
537 * (reference ) an assoc array of name/value pairs.
538 * @param array $defaults
539 * (reference ) an assoc array to hold the name / value pairs.
540 * in a hierarchical manner
542 * (reference) the array that holds all the db ids.
544 * @return CRM_Contribute_BAO_Contribution
546 public static function retrieve(&$params, &$defaults, &$ids) {
547 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
548 return $contribution;
552 * Combine all the importable fields from the lower levels object
554 * The ordering is important, since currently we do not have a weight
555 * scheme. Adding weight is super important and should be done in the
556 * next week or so, before this can be called complete.
558 * @param string $contactType
559 * @param bool $status
562 * array of importable Fields
564 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
565 if (!self
::$_importableFields) {
566 if (!self
::$_importableFields) {
567 self
::$_importableFields = array();
571 $fields = array('' => array('title' => ts('- do not import -')));
574 $fields = array('' => array('title' => ts('- Contribution Fields -')));
577 $note = CRM_Core_DAO_Note
::import();
578 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
579 unset($tmpFields['option_value']);
580 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
581 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
583 // Using new Dedupe rule.
585 'contact_type' => $contactType,
586 'used' => 'Unsupervised',
588 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
589 $tmpContactField = array();
590 if (is_array($fieldsArray)) {
591 foreach ($fieldsArray as $value) {
592 //skip if there is no dupe rule
593 if ($value == 'none') {
596 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
601 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
602 $tmpContactField[trim($value)] = $contactFields[trim($value)];
604 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
607 $title = $tmpContactField[trim($value)]['title'];
609 $tmpContactField[trim($value)]['title'] = $title;
613 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
614 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
615 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
616 $fields = array_merge($fields, $tmpContactField);
617 $fields = array_merge($fields, $tmpFields);
618 $fields = array_merge($fields, $note);
619 $fields = array_merge($fields, $optionFields);
620 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
621 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
622 self
::$_importableFields = $fields;
624 return self
::$_importableFields;
630 public static function &exportableFields() {
631 if (!self
::$_exportableFields) {
632 if (!self
::$_exportableFields) {
633 self
::$_exportableFields = array();
636 $impFields = CRM_Contribute_DAO_Contribution
::export();
637 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
638 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
639 $typeField = CRM_Financial_DAO_FinancialType
::export();
640 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
641 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
642 $contributionStatus = array(
643 'contribution_status' => array(
644 'title' => ts('Contribution Status'),
645 'name' => 'contribution_status',
646 'data_type' => CRM_Utils_Type
::T_STRING
,
650 $contributionPage = array(
651 'contribution_page' => array(
652 'title' => ts('Contribution Page'),
653 'name' => 'contribution_page',
654 'where' => 'civicrm_contribution_page.title',
655 'data_type' => CRM_Utils_Type
::T_STRING
,
659 $contributionNote = array(
660 'contribution_note' => array(
661 'title' => ts('Contribution Note'),
662 'name' => 'contribution_note',
663 'data_type' => CRM_Utils_Type
::T_TEXT
,
667 $contributionRecurId = array(
668 'contribution_recur_id' => array(
669 'title' => ts('Recurring Contributions ID'),
670 'name' => 'contribution_recur_id',
671 'where' => 'civicrm_contribution.contribution_recur_id',
672 'data_type' => CRM_Utils_Type
::T_INT
,
676 $extraFields = array(
677 'contribution_batch' => array(
678 'title' => ts('Batch Name'),
682 $softCreditFields = array(
683 'contribution_soft_credit_name' => array(
684 'name' => 'contribution_soft_credit_name',
685 'title' => 'Soft Credit For',
686 'where' => 'civicrm_contact_d.display_name',
687 'data_type' => CRM_Utils_Type
::T_STRING
,
689 'contribution_soft_credit_amount' => array(
690 'name' => 'contribution_soft_credit_amount',
691 'title' => 'Soft Credit Amount',
692 'where' => 'civicrm_contribution_soft.amount',
693 'data_type' => CRM_Utils_Type
::T_MONEY
,
695 'contribution_soft_credit_type' => array(
696 'name' => 'contribution_soft_credit_type',
697 'title' => 'Soft Credit Type',
698 'where' => 'contribution_softcredit_type.label',
699 'data_type' => CRM_Utils_Type
::T_STRING
,
701 'contribution_soft_credit_contribution_id' => array(
702 'name' => 'contribution_soft_credit_contribution_id',
703 'title' => 'Soft Credit For Contribution ID',
704 'where' => 'civicrm_contribution_soft.contribution_id',
705 'data_type' => CRM_Utils_Type
::T_INT
,
709 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
710 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
711 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
714 self
::$_exportableFields = $fields;
717 return self
::$_exportableFields;
721 * @param null $status
722 * @param null $startDate
723 * @param null $endDate
727 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
731 $where[] = 'contribution_status_id = 1';
735 $where[] = 'contribution_status_id = 3';
740 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
743 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
746 $whereCond = implode(' AND ', $where);
749 SELECT sum( total_amount ) as total_amount,
750 count( civicrm_contribution.id ) as total_count,
752 FROM civicrm_contribution
753 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
755 AND ( is_test = 0 OR is_test IS NULL )
756 AND contact.is_deleted = 0
760 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
763 while ($dao->fetch()) {
764 $count +
= $dao->total_count
;
765 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
769 'amount' => implode(', ', $amount),
777 * Delete the indirect records associated with this contribution first
782 * $results no of deleted Contribution on success, false otherwise
784 public static function deleteContribution($id) {
785 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
787 $transaction = new CRM_Core_Transaction();
790 //delete activity record
792 'source_record_id' => $id,
793 // activity type id for contribution
794 'activity_type_id' => 6,
797 CRM_Activity_BAO_Activity
::deleteActivity($params);
799 //delete billing address if exists for this contribution.
800 self
::deleteAddress($id);
802 //update pledge and pledge payment, CRM-3961
803 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
805 // remove entry from civicrm_price_set_entity, CRM-5095
806 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
807 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
809 // cleanup line items.
810 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
812 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
813 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
815 if ($participantId) {
816 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
819 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
823 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
824 $noteId = key($note);
826 CRM_Core_BAO_Note
::del($noteId, FALSE);
829 $dao = new CRM_Contribute_DAO_Contribution();
832 $results = $dao->delete();
834 $transaction->commit();
836 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
838 // delete the recently created Contribution
839 $contributionRecent = array(
841 'type' => 'Contribution',
843 CRM_Utils_Recent
::del($contributionRecent);
849 * Check if there is a contribution with the same trxn_id or invoice_id
851 * @param array $input
852 * An assoc array of name/value pairs.
853 * @param array $duplicates
854 * (reference) store ids of duplicate contribs.
858 * true if duplicate, false otherwise
860 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
862 $id = CRM_Utils_Array
::value('id', $input);
864 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
865 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
871 $clause[] = "trxn_id = %1";
872 $input[1] = array($trxn_id, 'String');
876 $clause[] = "invoice_id = %2";
877 $input[2] = array($invoice_id, 'String');
880 if (empty($clause)) {
884 $clause = implode(' OR ', $clause);
886 $clause = "( $clause ) AND id != %3";
887 $input[3] = array($id, 'Integer');
890 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
891 $dao = CRM_Core_DAO
::executeQuery($query, $input);
893 while ($dao->fetch()) {
894 $duplicates[] = $dao->id
;
901 * Takes an associative array and creates a contribution_product object
903 * the function extract all the params it needs to initialize the create a
904 * contribution_product object. the params array could contain additional unused name/value
907 * @param array $params
908 * (reference) an assoc array of name/value pairs.
910 * @return CRM_Contribute_DAO_ContributionProduct
912 public static function addPremium(&$params) {
913 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
914 $contributionProduct->copyValues($params);
915 return $contributionProduct->save();
919 * Get list of contribution fields for profile
920 * For now we only allow custom contribution fields to be in
923 * @param bool $addExtraFields
924 * True if special fields needs to be added.
927 * the list of contribution fields
929 public static function getContributionFields($addExtraFields = TRUE) {
930 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
931 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
933 if ($addExtraFields) {
934 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
937 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
939 foreach ($contributionFields as $key => $var) {
940 if ($key == 'contribution_contact_id') {
943 elseif ($key == 'contribution_campaign_id') {
944 $var['title'] = ts('Campaign');
946 $fields[$key] = $var;
949 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
954 * Add extra fields specific to contribution.
956 public static function getSpecialContributionFields() {
957 $extraFields = array(
958 'contribution_soft_credit_name' => array(
959 'name' => 'contribution_soft_credit_name',
960 'title' => 'Soft Credit Name',
961 'headerPattern' => '/^soft_credit_name$/i',
962 'where' => 'civicrm_contact_d.display_name',
964 'contribution_soft_credit_email' => array(
965 'name' => 'contribution_soft_credit_email',
966 'title' => 'Soft Credit Email',
967 'headerPattern' => '/^soft_credit_email$/i',
968 'where' => 'soft_email.email',
970 'contribution_soft_credit_phone' => array(
971 'name' => 'contribution_soft_credit_phone',
972 'title' => 'Soft Credit Phone',
973 'headerPattern' => '/^soft_credit_phone$/i',
974 'where' => 'soft_phone.phone',
976 'contribution_soft_credit_contact_id' => array(
977 'name' => 'contribution_soft_credit_contact_id',
978 'title' => 'Soft Credit Contact ID',
979 'headerPattern' => '/^soft_credit_contact_id$/i',
980 'where' => 'civicrm_contribution_soft.contact_id',
992 public static function getCurrentandGoalAmount($pageID) {
994 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
995 FROM civicrm_contribution_page p,
996 civicrm_contribution c
997 WHERE p.id = c.contribution_page_id
999 AND c.cancel_date is null
1003 $config = CRM_Core_Config
::singleton();
1004 $params = array(1 => array($pageID, 'Integer'));
1005 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1007 if ($dao->fetch()) {
1008 return array($dao->goal
, $dao->total
);
1011 return array(NULL, NULL);
1016 * Get list of contribution In Honor of contact Ids
1018 * @param int $honorId
1019 * In Honor of Contact ID.
1022 * list of contribution fields
1025 public static function getHonorContacts($honorId) {
1027 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1028 $honorDAO->contact_id
= $honorId;
1031 $type = CRM_Contribute_PseudoConstant
::financialType();
1033 while ($honorDAO->fetch()) {
1034 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1035 $contributionDAO->id
= $honorDAO->contribution_id
;
1037 if ($contributionDAO->find(TRUE)) {
1038 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1039 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1040 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1041 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1042 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1043 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1044 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1045 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1046 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1054 * Get the sort name of a contact for a particular contribution
1057 * Id of the contribution.
1059 * @return null|string
1060 * sort name of the contact if found
1062 public static function sortName($id) {
1063 $id = CRM_Utils_Type
::escape($id, 'Integer');
1066 SELECT civicrm_contact.sort_name
1067 FROM civicrm_contribution, civicrm_contact
1068 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1069 AND civicrm_contribution.id = {$id}
1071 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1075 * @param int $contactID
1079 public static function annual($contactID) {
1080 if (is_array($contactID)) {
1081 $contactIDs = implode(',', $contactID);
1084 $contactIDs = $contactID;
1087 $config = CRM_Core_Config
::singleton();
1088 $startDate = $endDate = NULL;
1090 $currentMonth = date('m');
1091 $currentDay = date('d');
1092 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1093 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1094 (int ) $config->fiscalYearStart
['d'] > $currentDay
1097 $year = date('Y') - 1;
1102 $nextYear = $year +
1;
1104 if ($config->fiscalYearStart
) {
1105 if ($config->fiscalYearStart
['M'] < 10) {
1106 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1108 if ($config->fiscalYearStart
['d'] < 10) {
1109 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1111 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1116 $startDate = "$year$monthDay";
1117 $endDate = "$nextYear$monthDay";
1120 SELECT count(*) as count,
1121 sum(total_amount) as amount,
1122 avg(total_amount) as average,
1124 FROM civicrm_contribution b
1125 WHERE b.contact_id IN ( $contactIDs )
1126 AND b.contribution_status_id = 1
1128 AND b.receive_date >= $startDate
1129 AND b.receive_date < $endDate
1132 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1134 $amount = $average = array();
1135 while ($dao->fetch()) {
1136 if ($dao->count
> 0 && $dao->amount
> 0) {
1137 $count +
= $dao->count
;
1138 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1139 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1145 implode(', ', $amount),
1146 implode(', ', $average),
1149 return array(0, 0, 0);
1153 * Check if there is a contribution with the params passed in.
1154 * Used for trxn_id,invoice_id and contribution_id
1156 * @param array $params
1157 * An assoc array of name/value pairs.
1160 * contribution id if success else NULL
1162 public static function checkDuplicateIds($params) {
1163 $dao = new CRM_Contribute_DAO_Contribution();
1167 foreach ($params as $k => $v) {
1169 $clause[] = "$k = '$v'";
1172 $clause = implode(' AND ', $clause);
1173 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1174 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1176 while ($dao->fetch()) {
1184 * Get the contribution details for component export
1186 * @param int $exportMode
1188 * @param string $componentIds
1195 public static function getContributionDetails($exportMode, $componentIds) {
1196 $paymentDetails = array();
1197 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1199 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1200 $componentSelect = " civicrm_participant_payment.participant_id id";
1201 $additionalClause = "
1202 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1203 AND civicrm_participant_payment.participant_id {$componentClause} )
1206 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1207 $componentSelect = " civicrm_membership_payment.membership_id id";
1208 $additionalClause = "
1209 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1210 AND civicrm_membership_payment.membership_id {$componentClause} )
1213 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1214 $componentSelect = " civicrm_pledge_payment.id id";
1215 $additionalClause = "
1216 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1217 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1221 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1222 trxn_id, {$componentSelect}
1223 FROM civicrm_contribution
1224 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1225 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1226 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1227 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1228 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1229 AND option_group_contribution_status.id = contribution_status.option_group_id )
1233 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1235 while ($dao->fetch()) {
1236 $paymentDetails[$dao->id
] = array(
1237 'total_amount' => $dao->total_amount
,
1238 'contribution_status' => $dao->status
,
1239 'receive_date' => $dao->receive_date
,
1240 'pay_instru' => $dao->payment_instrument
,
1241 'trxn_id' => $dao->trxn_id
,
1245 return $paymentDetails;
1249 * Create address associated with contribution record.
1251 * @param array $params
1252 * @param int $billingLocationTypeID
1257 public static function createAddress(&$params, $billingLocationTypeID) {
1258 $billingFields = array(
1261 'state_province_id',
1266 //build address array
1267 $addressParams = array();
1268 $addressParams['location_type_id'] = $billingLocationTypeID;
1269 $addressParams['is_billing'] = 1;
1271 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1272 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1273 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1274 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1276 foreach ($billingFields as $value) {
1277 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1280 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1282 return $address->id
;
1286 * Delete billing address record related contribution
1288 * @param int $contributionId
1289 * @param int $contactId
1292 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1294 $contactJoin = NULL;
1296 if ($contributionId) {
1297 $clauses[] = "cc.id = {$contributionId}";
1301 $clauses[] = "cco.id = {$contactId}";
1302 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1305 if (empty($clauses)) {
1306 CRM_Core_Error
::fatal();
1309 $condition = implode(' OR ', $clauses);
1313 FROM civicrm_address ca
1314 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1318 $dao = CRM_Core_DAO
::executeQuery($query);
1320 while ($dao->fetch()) {
1321 $params = array('id' => $dao->id
);
1322 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1327 * This function check online pending contribution associated w/
1328 * Online Event Registration or Online Membership signup.
1330 * @param int $componentId
1331 * Participant/membership id.
1332 * @param string $componentName
1336 * pending contribution id.
1338 public static function checkOnlinePendingContribution($componentId, $componentName) {
1339 $contributionId = NULL;
1340 if (!$componentId ||
1341 !in_array($componentName, array('Event', 'Membership'))
1343 return $contributionId;
1346 if ($componentName == 'Event') {
1347 $idName = 'participant_id';
1348 $componentTable = 'civicrm_participant';
1349 $paymentTable = 'civicrm_participant_payment';
1350 $source = ts('Online Event Registration');
1353 if ($componentName == 'Membership') {
1354 $idName = 'membership_id';
1355 $componentTable = 'civicrm_membership';
1356 $paymentTable = 'civicrm_membership_payment';
1357 $source = ts('Online Contribution');
1360 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1363 SELECT component.id as {$idName},
1364 componentPayment.contribution_id as contribution_id,
1365 contribution.source source,
1366 contribution.contribution_status_id as contribution_status_id,
1367 contribution.is_pay_later as is_pay_later
1368 FROM $componentTable component
1369 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1370 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1371 WHERE component.id = {$componentId}";
1373 $dao = CRM_Core_DAO
::executeQuery($query);
1375 while ($dao->fetch()) {
1376 if ($dao->contribution_id
&&
1377 $dao->is_pay_later
&&
1378 $dao->contribution_status_id
== $pendingStatusId &&
1379 strpos($dao->source
, $source) !== FALSE
1381 $contributionId = $dao->contribution_id
;
1386 return $contributionId;
1390 * Update contribution as well as related objects.
1392 * @param array $params
1393 * @param bool $processContributionObject
1396 * @throws \Exception
1398 public static function transitionComponents($params, $processContributionObject = FALSE) {
1399 // get minimum required values.
1400 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1401 $componentId = CRM_Utils_Array
::value('component_id', $params);
1402 $componentName = CRM_Utils_Array
::value('componentName', $params);
1403 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1404 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1406 // if we already processed contribution object pass previous status id.
1407 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1409 $updateResult = array();
1411 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1413 // we process only ( Completed, Cancelled, or Failed ) contributions.
1414 if (!$contributionId ||
1415 !in_array($contributionStatusId, array(
1416 array_search('Completed', $contributionStatuses),
1417 array_search('Cancelled', $contributionStatuses),
1418 array_search('Failed', $contributionStatuses),
1421 return $updateResult;
1424 if (!$componentName ||
!$componentId) {
1425 // get the related component details.
1426 $componentDetails = self
::getComponentDetails($contributionId);
1429 $componentDetails['contact_id'] = $contactId;
1430 $componentDetails['component'] = $componentName;
1432 if ($componentName == 'event') {
1433 $componentDetails['participant'] = $componentId;
1436 $componentDetails['membership'] = $componentId;
1440 if (!empty($componentDetails['contact_id'])) {
1441 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1447 // do check for required ids.
1448 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1449 return $updateResult;
1452 //now we are ready w/ required ids, start processing.
1454 $baseIPN = new CRM_Core_Payment_BaseIPN();
1456 $input = $ids = $objects = array();
1458 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1459 $ids['contribution'] = $contributionId;
1460 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1461 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1462 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1463 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1464 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1465 $ids['contributionRecur'] = NULL;
1466 $ids['contributionPage'] = NULL;
1468 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1469 CRM_Core_Error
::fatal();
1472 $memberships = &$objects['membership'];
1473 $participant = &$objects['participant'];
1474 $pledgePayment = &$objects['pledge_payment'];
1475 $contribution = &$objects['contribution'];
1477 if ($pledgePayment) {
1478 $pledgePaymentIDs = array();
1479 foreach ($pledgePayment as $key => $object) {
1480 $pledgePaymentIDs[] = $object->id
;
1482 $pledgeID = $pledgePayment[0]->pledge_id
;
1485 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1488 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1489 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1494 // we might want to process contribution object.
1495 $processContribution = FALSE;
1496 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1497 if (is_array($memberships)) {
1498 foreach ($memberships as $membership) {
1500 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1501 $membership->save();
1503 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1504 if ($processContributionObject) {
1505 $processContribution = TRUE;
1512 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1513 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1515 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1516 if ($processContributionObject) {
1517 $processContribution = TRUE;
1521 if ($pledgePayment) {
1522 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1524 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1525 if ($processContributionObject) {
1526 $processContribution = TRUE;
1530 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1531 if (is_array($memberships)) {
1532 foreach ($memberships as $membership) {
1534 $membership->status_id
= array_search('Expired', $membershipStatuses);
1535 $membership->save();
1537 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1538 if ($processContributionObject) {
1539 $processContribution = TRUE;
1545 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1546 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1548 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1549 if ($processContributionObject) {
1550 $processContribution = TRUE;
1554 if ($pledgePayment) {
1555 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1557 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1558 if ($processContributionObject) {
1559 $processContribution = TRUE;
1563 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1565 // only pending contribution related object processed.
1566 if ($previousContriStatusId &&
1567 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1569 // this is case when we already processed contribution object.
1570 return $updateResult;
1572 elseif (!$previousContriStatusId &&
1573 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1575 // this is case when we are going to process contribution object later.
1576 return $updateResult;
1579 if (is_array($memberships)) {
1580 foreach ($memberships as $membership) {
1585 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1586 $membership->membership_type_id
,
1587 $membership->is_test
, $membership->id
1590 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1591 // this picks up membership type changes during renewals
1593 SELECT membership_type_id
1594 FROM civicrm_membership_log
1595 WHERE membership_id=$membership->id
1598 $dao = new CRM_Core_DAO();
1600 if ($dao->fetch()) {
1601 if (!empty($dao->membership_type_id
)) {
1602 $membership->membership_type_id
= $dao->membership_type_id
;
1603 $membership->save();
1606 // else fall back to using current membership type
1609 // Figure out number of terms
1611 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1612 foreach ($lineitems as $lineitem) {
1613 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1614 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1616 // in case membership_num_terms comes through as null or zero
1617 $numterms = $numterms >= 1 ?
$numterms : 1;
1622 // CRM-15735-to update the membership status as per the contribution receive date
1623 if (!empty($params['receive_date'])) {
1624 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1625 $membership->end_date
,
1626 $membership->join_date
,
1627 $params['receive_date'],
1629 $membership->membership_type_id
,
1632 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1633 $membership->save();
1636 if ($currentMembership) {
1637 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1638 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1639 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1642 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1645 //get the status for membership.
1646 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1648 $dates['join_date'],
1651 $membership->membership_type_id
,
1655 $formattedParams = array(
1656 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1657 array_search('Current', $membershipStatuses)
1659 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1660 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1661 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1664 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1666 $membership->copyValues($formattedParams);
1667 $membership->save();
1669 //updating the membership log
1670 $membershipLog = array();
1671 $membershipLog = $formattedParams;
1672 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1673 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1675 $membershipLog['start_date'] = $logStartDate;
1676 $membershipLog['membership_id'] = $membership->id
;
1677 $membershipLog['modified_id'] = $membership->contact_id
;
1678 $membershipLog['modified_date'] = date('Ymd');
1679 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1681 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1683 //update related Memberships.
1684 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1686 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1689 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1690 if ($processContributionObject) {
1691 $processContribution = TRUE;
1694 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1700 $updatedStatusId = array_search('Registered', $participantStatuses);
1701 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1703 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1704 if ($processContributionObject) {
1705 $processContribution = TRUE;
1709 if ($pledgePayment) {
1710 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1712 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1713 if ($processContributionObject) {
1714 $processContribution = TRUE;
1719 // process contribution object.
1720 if ($processContribution) {
1721 $contributionParams = array();
1728 'payment_instrument_id',
1731 'financial_type_id',
1732 'contribution_status_id',
1733 'non_deductible_amount',
1737 foreach ($fields as $field) {
1738 if (empty($params[$field])) {
1741 $contributionParams[$field] = $params[$field];
1744 $ids = array('contribution' => $contributionId);
1745 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1748 return $updateResult;
1752 * Returns all contribution related object ids.
1754 * @param $contributionId
1758 public static function getComponentDetails($contributionId) {
1759 $componentDetails = $pledgePayment = array();
1760 if (!$contributionId) {
1761 return $componentDetails;
1765 SELECT c.id as contribution_id,
1766 c.contact_id as contact_id,
1767 mp.membership_id as membership_id,
1768 m.membership_type_id as membership_type_id,
1769 pp.participant_id as participant_id,
1770 p.event_id as event_id,
1771 pgp.id as pledge_payment_id
1772 FROM civicrm_contribution c
1773 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1774 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1775 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1776 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1777 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1778 WHERE c.id = $contributionId";
1780 $dao = CRM_Core_DAO
::executeQuery($query);
1781 $componentDetails = array();
1783 while ($dao->fetch()) {
1784 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1785 $componentDetails['contact_id'] = $dao->contact_id
;
1786 if ($dao->event_id
) {
1787 $componentDetails['event'] = $dao->event_id
;
1789 if ($dao->participant_id
) {
1790 $componentDetails['participant'] = $dao->participant_id
;
1792 if ($dao->membership_id
) {
1793 if (!isset($componentDetails['membership'])) {
1794 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1796 $componentDetails['membership'][] = $dao->membership_id
;
1797 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1799 if ($dao->pledge_payment_id
) {
1800 $pledgePayment[] = $dao->pledge_payment_id
;
1804 if ($pledgePayment) {
1805 $componentDetails['pledge_payment'] = $pledgePayment;
1808 return $componentDetails;
1812 * @param int $contactId
1813 * @param bool $includeSoftCredit
1815 * @return null|string
1817 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1822 $contactContributionsSQL = "
1823 SELECT contribution.id AS id
1824 FROM civicrm_contribution contribution
1825 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1827 $contactSoftCreditContributionsSQL = "
1828 SELECT contribution.id
1829 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1830 ON ( contribution.id = softContribution.contribution_id )
1831 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1832 $query = "SELECT count( x.id ) count FROM ( ";
1833 $query .= $contactContributionsSQL;
1835 if ($includeSoftCredit) {
1836 $query .= " UNION ";
1837 $query .= $contactSoftCreditContributionsSQL;
1842 return CRM_Core_DAO
::singleValueQuery($query);
1846 * Get individual id for onbehalf contribution
1848 * @param int $contributionId
1850 * @param int $contributorId
1854 * containing organization id and individual id
1856 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1860 if (!$contributionId) {
1864 // fetch contributor id if null
1865 if (!$contributorId) {
1866 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1867 $contributionId, 'contact_id'
1871 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1872 $activityTypeId = array_search('Contribution', $activityTypeIds);
1874 if ($activityTypeId && $contributorId) {
1876 SELECT civicrm_activity_contact.contact_id
1877 FROM civicrm_activity_contact
1878 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1879 WHERE civicrm_activity.activity_type_id = %1
1880 AND civicrm_activity.source_record_id = %2
1881 AND civicrm_activity_contact.record_type_id = %3
1884 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1885 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1888 1 => array($activityTypeId, 'Integer'),
1889 2 => array($contributionId, 'Integer'),
1890 3 => array($sourceID, 'Integer'),
1893 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1895 // for on behalf contribution source is individual and contributor is organization
1896 if ($sourceContactId && $sourceContactId != $contributorId) {
1897 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1898 // get rel type id for employee of relation
1899 foreach ($relationshipTypeIds as $id => $typeVals) {
1900 if ($typeVals['name_a_b'] == 'Employee of') {
1901 $relationshipTypeId = $id;
1906 $rel = new CRM_Contact_DAO_Relationship();
1907 $rel->relationship_type_id
= $relationshipTypeId;
1908 $rel->contact_id_a
= $sourceContactId;
1909 $rel->contact_id_b
= $contributorId;
1910 if ($rel->find(TRUE)) {
1911 $ids['individual_id'] = $rel->contact_id_a
;
1912 $ids['organization_id'] = $rel->contact_id_b
;
1923 public static function getContributionDates() {
1924 $config = CRM_Core_Config
::singleton();
1925 $currentMonth = date('m');
1926 $currentDay = date('d');
1927 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1928 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1929 (int ) $config->fiscalYearStart
['d'] > $currentDay
1932 $year = date('Y') - 1;
1937 $year = array('Y' => $year);
1938 $yearDate = $config->fiscalYearStart
;
1939 $yearDate = array_merge($year, $yearDate);
1940 $yearDate = CRM_Utils_Date
::format($yearDate);
1942 $monthDate = date('Ym') . '01';
1948 'yearDate' => $yearDate,
1949 'monthDate' => $monthDate,
1954 * Load objects relations to contribution object
1955 * Objects are stored in the $_relatedObjects property
1956 * In the first instance we are just moving functionality from BASEIpn -
1957 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1959 * Note that the unit test for the BaseIPN class tests this function
1961 * @param array $input
1962 * Input as delivered from Payment Processor.
1964 * Ids as Loaded by Payment Processor.
1965 * @param bool $required
1966 * Is Payment processor / contribution page required.
1967 * @param bool $loadAll
1968 * Load all related objects - even where id not passed in? (allows API to call this).
1973 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1975 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1976 if (empty($ids['contact']) && isset($this->contact_id
)) {
1977 $ids['contact'] = $this->contact_id
;
1980 if (empty($this->_component
)) {
1981 if (!empty($ids['event'])) {
1982 $this->_component
= 'event';
1985 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1988 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1989 $contributionType = new CRM_Financial_BAO_FinancialType();
1990 $contributionType->id
= $this->financial_type_id
;
1991 if (!$contributionType->find(TRUE)) {
1992 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1994 if (!empty($ids['contact'])) {
1995 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1996 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1997 $this->_relatedObjects
['contact']->find(TRUE);
1999 $this->_relatedObjects
['contributionType'] = $contributionType;
2001 if ($this->_component
== 'contribute') {
2002 // retrieve the other optional objects first so
2003 // stuff down the line can use this info and do things
2005 //in any case get the memberships associated with the contribution
2006 //because we now support multiple memberships w/ price set
2007 // see if there are any other memberships to be considered for same contribution.
2009 SELECT membership_id
2010 FROM civicrm_membership_payment
2011 WHERE contribution_id = %1 ";
2012 $params = array(1 => array($this->id
, 'Integer'));
2014 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2015 while ($dao->fetch()) {
2016 if ($dao->membership_id
) {
2017 if (!is_array($ids['membership'])) {
2018 $ids['membership'] = array();
2020 $ids['membership'][] = $dao->membership_id
;
2024 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2025 foreach ($ids['membership'] as $id) {
2027 $membership = new CRM_Member_BAO_Membership();
2028 $membership->id
= $id;
2029 if (!$membership->find(TRUE)) {
2030 throw new Exception("Could not find membership record: $id");
2032 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2033 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2034 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2035 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2036 $membership->free();
2041 if (!empty($ids['pledge_payment'])) {
2043 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2044 if (empty($paymentID)) {
2047 $payment = new CRM_Pledge_BAO_PledgePayment();
2048 $payment->id
= $paymentID;
2049 if (!$payment->find(TRUE)) {
2050 throw new Exception("Could not find pledge payment record: " . $paymentID);
2052 $this->_relatedObjects
['pledge_payment'][] = $payment;
2056 if (!empty($ids['contributionRecur'])) {
2057 $recur = new CRM_Contribute_BAO_ContributionRecur();
2058 $recur->id
= $ids['contributionRecur'];
2059 if (!$recur->find(TRUE)) {
2060 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2062 $this->_relatedObjects
['contributionRecur'] = &$recur;
2063 //get payment processor id from recur object.
2064 $paymentProcessorID = $recur->payment_processor_id
;
2066 //for normal contribution get the payment processor id.
2067 if (!$paymentProcessorID) {
2068 if ($this->contribution_page_id
) {
2069 // get the payment processor id from contribution page
2070 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2071 $this->contribution_page_id
,
2075 //fail to load payment processor id.
2076 elseif (empty($ids['pledge_payment'])) {
2077 $loadObjectSuccess = TRUE;
2079 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2081 return $loadObjectSuccess;
2086 // we are in event mode
2087 // make sure event exists and is valid
2088 $event = new CRM_Event_BAO_Event();
2089 $event->id
= $ids['event'];
2090 if ($ids['event'] &&
2093 throw new Exception("Could not find event: " . $ids['event']);
2096 $this->_relatedObjects
['event'] = &$event;
2098 $participant = new CRM_Event_BAO_Participant();
2099 $participant->id
= $ids['participant'];
2100 if ($ids['participant'] &&
2101 !$participant->find(TRUE)
2103 throw new Exception("Could not find participant: " . $ids['participant']);
2105 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2107 $this->_relatedObjects
['participant'] = &$participant;
2109 if (!$paymentProcessorID) {
2110 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2114 if ($paymentProcessorID) {
2115 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2116 $this->is_test ?
'test' : 'live'
2118 $ids['paymentProcessor'] = $paymentProcessorID;
2119 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2121 elseif ($required) {
2122 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2129 * Create array of message information - ie. return html version, txt version, to field
2131 * @param array $input
2132 * Incoming information.
2133 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2134 * just check presence of recur object but maintaining legacy approach
2137 * IDs of related objects.
2138 * @param array $values
2139 * Any values that may have already been compiled by calling process.
2140 * This is augmented by values 'gathered' by gatherMessageValues
2141 * @param bool $recur
2142 * @param bool $returnMessageText
2143 * Distinguishes between whether to send message or return.
2144 * message text. We are working towards this function ALWAYS returning message text & calling
2145 * function doing emails / pdfs with it
2151 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2152 if (empty($this->_relatedObjects
)) {
2153 $this->loadRelatedObjects($input, $ids);
2155 if (empty($this->_component
)) {
2156 $this->_component
= CRM_Utils_Array
::value('component', $input);
2159 //not really sure what params might be passed in but lets merge em into values
2160 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2161 $template = CRM_Core_Smarty
::singleton();
2162 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2163 //what does recur 'mean here - to do with payment processor return functionality but
2164 // what is the importance
2165 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2166 $paymentObject = &CRM_Core_Payment
::singleton(
2167 $this->is_test ?
'test' : 'live',
2168 $this->_relatedObjects
['paymentProcessor']
2171 $entityID = $entity = NULL;
2172 if (isset($ids['contribution'])) {
2173 $entity = 'contribution';
2174 $entityID = $ids['contribution'];
2176 if (!empty($ids['membership'])) {
2177 //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
2178 // 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
2179 // line having loaded an array
2180 $ids['membership'] = (array) $ids['membership'];
2181 $entity = 'membership';
2182 $entityID = $ids['membership'][0];
2185 $url = $paymentObject->subscriptionURL($entityID, $entity);
2186 $template->assign('cancelSubscriptionUrl', $url);
2188 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2189 $template->assign('updateSubscriptionBillingUrl', $url);
2191 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2192 $template->assign('updateSubscriptionUrl', $url);
2194 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2195 //direct mode showing billing block, so use directIPN for temporary
2196 $template->assign('contributeMode', 'directIPN');
2199 // todo remove strtolower - check consistency
2200 if (strtolower($this->_component
) == 'event') {
2201 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2202 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2206 $values['contribution_id'] = $this->id
;
2207 if (!empty($ids['related_contact'])) {
2208 $values['related_contact'] = $ids['related_contact'];
2209 if (isset($ids['onbehalf_dupe_alert'])) {
2210 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2212 $entityBlock = array(
2213 'contact_id' => $ids['contact'],
2214 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2215 'Home', 'id', 'name'
2218 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2219 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2222 if ($this->is_test
) {
2225 if (!empty($this->_relatedObjects
['membership'])) {
2226 foreach ($this->_relatedObjects
['membership'] as $membership) {
2227 if ($membership->id
) {
2228 $values['isMembership'] = TRUE;
2230 // need to set the membership values here
2231 $template->assign('membership_assign', 1);
2232 $template->assign('membership_name',
2233 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2235 $template->assign('mem_start_date', $membership->start_date
);
2236 $template->assign('mem_join_date', $membership->join_date
);
2237 $template->assign('mem_end_date', $membership->end_date
);
2238 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2239 $template->assign('mem_status', $membership_status);
2240 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2241 $template->assign('is_pay_later', 1);
2244 // if separate payment there are two contributions recorded and the
2245 // admin will need to send a receipt for each of them separately.
2246 // we dont link the two in the db (but can potentially infer it if needed)
2247 $template->assign('is_separate_payment', 0);
2249 if ($recur && $paymentObject) {
2250 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2251 $template->assign('cancelSubscriptionUrl', $url);
2252 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2253 $template->assign('updateSubscriptionBillingUrl', $url);
2254 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2255 $template->assign('updateSubscriptionUrl', $url);
2258 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2261 // otherwise if its about sending emails, continue sending without return, as we
2262 // don't want to exit the loop.
2267 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2273 * Gather values for contribution mail - this function has been created
2274 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2275 * Values related to the contribution in question are gathered
2277 * @param array $input
2278 * Input into function (probably from payment processor).
2279 * @param array $values
2281 * The set of ids related to the input.
2285 public function _gatherMessageValues($input, &$values, $ids = array()) {
2286 // set display address of contributor
2287 if ($this->address_id
) {
2288 $addressParams = array('id' => $this->address_id
);
2289 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2290 $addressDetails = array_values($addressDetails);
2291 $values['address'] = $addressDetails[0]['display'];
2293 if ($this->_component
== 'contribute') {
2294 if (isset($this->contribution_page_id
)) {
2295 CRM_Contribute_BAO_ContributionPage
::setValues(
2296 $this->contribution_page_id
,
2299 if ($this->contribution_page_id
) {
2300 // CRM-8254 - override default currency if applicable
2301 $config = CRM_Core_Config
::singleton();
2302 $config->defaultCurrency
= CRM_Utils_Array
::value(
2305 $config->defaultCurrency
2309 // no contribution page -probably back office
2311 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2312 $values['is_email_receipt'] = 1;
2313 $values['title'] = 'Contribution';
2315 // set lineItem for contribution
2317 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2318 if (!empty($lineItem)) {
2319 $itemId = key($lineItem);
2320 foreach ($lineItem as &$eachItem) {
2321 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2322 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2323 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2324 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2327 $values['lineItem'][0] = $lineItem;
2328 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2332 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2336 // if this is onbehalf of contribution then set related contact
2337 if (!empty($relatedContact['individual_id'])) {
2338 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2343 $eventParams = array(
2344 'id' => $this->_relatedObjects
['event']->id
,
2346 $values['event'] = array();
2348 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2350 //get location details
2351 $locationParams = array(
2352 'entity_id' => $this->_relatedObjects
['event']->id
,
2353 'entity_table' => 'civicrm_event',
2355 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2357 $ufJoinParams = array(
2358 'entity_table' => 'civicrm_event',
2359 'entity_id' => $ids['event'],
2360 'module' => 'CiviEvent',
2363 list($custom_pre_id,
2365 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2367 $values['custom_pre_id'] = $custom_pre_id;
2368 $values['custom_post_id'] = $custom_post_ids;
2370 // set lineItem for event contribution
2372 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2373 if (!empty($participantIds)) {
2374 foreach ($participantIds as $pIDs) {
2375 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2376 if (!CRM_Utils_System
::isNull($lineItem)) {
2377 $values['lineItem'][] = $lineItem;
2388 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2389 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2390 * Note we send directly from this function in some cases because it is only partly refactored
2391 * Don't call this function directly as the signature will change
2395 * @param CRM_Core_SMARTY $template
2396 * @param bool $recur
2397 * @param bool $returnMessageText
2401 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2402 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2403 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2404 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2405 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2406 $template->assign('useForMember', TRUE);
2408 //assign honor information to receipt message
2409 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2411 if (isset($softRecord['soft_credit'])) {
2412 //if id of contribution page is present
2413 if (!empty($values['id'])) {
2414 $values['honor'] = array(
2415 'honor_profile_values' => array(),
2416 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2417 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2419 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2421 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2422 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2425 //offline contribution
2426 $softCreditTypes = $softCredits = array();
2427 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2428 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2429 $softCredits[$key] = array(
2430 'Name' => $softCredit['contact_name'],
2431 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2434 $template->assign('softCreditTypes', $softCreditTypes);
2435 $template->assign('softCredits', $softCredits);
2439 $dao = new CRM_Contribute_DAO_ContributionProduct();
2440 $dao->contribution_id
= $this->id
;
2441 if ($dao->find(TRUE)) {
2442 $premiumId = $dao->product_id
;
2443 $template->assign('option', $dao->product_option
);
2445 $productDAO = new CRM_Contribute_DAO_Product();
2446 $productDAO->id
= $premiumId;
2447 $productDAO->find(TRUE);
2448 $template->assign('selectPremium', TRUE);
2449 $template->assign('product_name', $productDAO->name
);
2450 $template->assign('price', $productDAO->price
);
2451 $template->assign('sku', $productDAO->sku
);
2453 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2454 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2455 if (empty($amount) && isset($this->total_amount
)) {
2456 $amount = $this->total_amount
;
2458 $template->assign('amount', $amount);
2459 // add the new contribution values
2460 if (strtolower($this->_component
) == 'contribute') {
2462 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2463 $softDAO->contribution_id
= $this->id
;
2464 if ($softDAO->find(TRUE)) {
2465 $template->assign('pcpBlock', TRUE);
2466 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2467 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2468 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2470 //assign the pcp page title for email subject
2471 $pcpDAO = new CRM_PCP_DAO_PCP();
2472 $pcpDAO->id
= $softDAO->pcp_id
;
2473 if ($pcpDAO->find(TRUE)) {
2474 $template->assign('title', $pcpDAO->title
);
2479 if ($this->financial_type_id
) {
2480 $values['financial_type_id'] = $this->financial_type_id
;
2483 $template->assign('trxn_id', $this->trxn_id
);
2484 $template->assign('receive_date',
2485 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2487 $template->assign('contributeMode', 'notify');
2488 $template->assign('action', $this->is_test ?
1024 : 1);
2489 $template->assign('receipt_text',
2490 CRM_Utils_Array
::value('receipt_text',
2494 $template->assign('is_monetary', 1);
2495 $template->assign('is_recur', (bool) $recur);
2496 $template->assign('currency', $this->currency
);
2497 $template->assign('address', CRM_Utils_Address
::format($input));
2498 if ($this->_component
== 'event') {
2499 $template->assign('title', $values['event']['title']);
2500 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2501 $viewRoles = array();
2502 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2503 $viewRoles[] = $participantRoles[$v];
2505 $values['event']['participant_role'] = implode(', ', $viewRoles);
2506 $template->assign('event', $values['event']);
2507 $template->assign('location', $values['location']);
2508 $template->assign('customPre', $values['custom_pre_id']);
2509 $template->assign('customPost', $values['custom_post_id']);
2512 if ($this->_relatedObjects
['participant']->is_test
) {
2516 $values['params'] = array();
2517 //to get email of primary participant.
2518 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2519 $primaryAmount[] = array(
2520 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2521 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2523 //build an array of cId/pId of participants
2524 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2525 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2526 //send receipt to additional participant if exists
2527 if (count($additionalIDs)) {
2528 $template->assign('isPrimary', 0);
2529 $template->assign('customProfile', NULL);
2530 //set additionalParticipant true
2531 $values['params']['additionalParticipant'] = TRUE;
2532 foreach ($additionalIDs as $pId => $cId) {
2534 //to change the status pending to completed
2535 $additional = new CRM_Event_DAO_Participant();
2536 $additional->id
= $pId;
2537 $additional->contact_id
= $cId;
2538 $additional->find(TRUE);
2539 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2540 $additional->status_id
= 1;
2541 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2542 //if additional participant dont have email
2544 if (!$additionalParticipantInfo) {
2545 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2547 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2548 $primaryAmount[] = array(
2549 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2550 'amount' => $additional->fee_amount
,
2552 $additional->save();
2553 $additional->free();
2554 $template->assign('amount', $amount);
2555 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2559 //build an array of custom profile and assigning it to template
2560 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2562 if (count($customProfile)) {
2563 $template->assign('customProfile', $customProfile);
2566 // for primary contact
2567 $values['params']['additionalParticipant'] = FALSE;
2568 $template->assign('isPrimary', 1);
2569 $template->assign('amount', $primaryAmount);
2570 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2571 if ($this->payment_instrument_id
) {
2572 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2573 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2575 // carry paylater, since we did not created billing,
2576 // so need to pull email from primary location, CRM-4395
2577 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2583 * Check whether payment processor supports
2584 * cancellation of contribution subscription
2586 * @param int $contributionId
2589 * @param bool $isNotCancelled
2593 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2594 $cacheKeyString = "$contributionId";
2595 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2597 static $supportsCancel = array();
2599 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2600 $supportsCancel[$cacheKeyString] = FALSE;
2601 $isCancelled = FALSE;
2603 if ($isNotCancelled) {
2604 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2607 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2608 if (!empty($paymentObject)) {
2609 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2612 return $supportsCancel[$cacheKeyString];
2616 * Check whether subscription is already cancelled
2618 * @param int $contributionId
2622 * contribution status
2624 public static function isSubscriptionCancelled($contributionId) {
2626 SELECT cr.contribution_status_id
2627 FROM civicrm_contribution_recur cr
2628 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2629 WHERE con.id = %1 LIMIT 1";
2630 $params = array(1 => array($contributionId, 'Integer'));
2631 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2632 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2633 if ($status == 'Cancelled') {
2640 * Create all financial accounts entry
2642 * @param array $params
2643 * Contribution object, line item array and params for trxn.
2646 * @param array $financialTrxnValues
2648 * @return null|object
2650 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2651 $skipRecords = $update = $return = $isRelatedId = FALSE;
2653 $additionalParticipantId = array();
2654 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2656 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2657 $entityId = $params['participant_id'];
2658 $entityTable = 'civicrm_participant';
2659 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2661 elseif (!empty($params['membership_id'])) {
2662 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2663 // are created off one contribution should be handled elsewhere
2664 $entityId = $params['membership_id'];
2665 $entityTable = 'civicrm_membership';
2668 $entityId = $params['contribution']->id
;
2669 $entityTable = 'civicrm_contribution';
2672 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2673 $isRelatedId = TRUE;
2676 $entityID[] = $entityId;
2677 if (!empty($additionalParticipantId)) {
2678 $entityID +
= $additionalParticipantId;
2680 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2681 if (empty($params['prevContribution'])) {
2688 $statusId = $params['contribution']->contribution_status_id
;
2689 // CRM-13964 partial payment
2690 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2691 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2693 $partialAmtPay = $params['partial_amount_pay'];
2694 $partialAmtTotal = $params['partial_payment_total'];
2696 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2697 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2698 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2699 $params['total_amount'] = $partialAmtPay;
2701 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2702 if (empty($balanceTrxnInfo['trxn_id'])) {
2703 // create new balance transaction record
2704 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2705 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2707 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2708 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2709 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2710 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2711 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2712 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2713 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2714 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2715 $balanceTrxnParams['status_id'] = $statusId;
2716 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2717 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2718 if (!empty($params['payment_processor'])) {
2719 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2721 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2725 // build line item array if its not set in $params
2726 if (empty($params['line_item']) ||
$additionalParticipantId) {
2727 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2730 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2731 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2733 $skipRecords = TRUE;
2734 $pendingStatus = array(
2735 array_search('Pending', $contributionStatuses),
2736 array_search('In Progress', $contributionStatuses),
2738 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2739 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2740 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2742 elseif (!empty($params['payment_processor'])) {
2743 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2745 elseif (!empty($params['payment_instrument_id'])) {
2746 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2749 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2750 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2751 $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);
2754 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2755 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2756 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2759 //build financial transaction params
2760 $trxnParams = array(
2761 'contribution_id' => $params['contribution']->id
,
2762 'to_financial_account_id' => $params['to_financial_account_id'],
2763 'trxn_date' => date('YmdHis'),
2764 'total_amount' => $totalAmount,
2765 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2766 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2767 'currency' => $params['contribution']->currency
,
2768 'trxn_id' => $params['contribution']->trxn_id
,
2769 'status_id' => $statusId,
2770 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2771 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2774 if (!empty($params['payment_processor'])) {
2775 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2778 if (isset($fromFinancialAccountId)) {
2779 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2782 // consider external values passed for recording transaction entry
2783 if (!empty($financialTrxnValues)) {
2784 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2787 $params['trxnParams'] = $trxnParams;
2789 if (!empty($params['prevContribution'])) {
2790 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2791 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2792 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2793 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2794 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2796 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2797 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2798 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2800 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2801 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2804 //if financial type is changed
2805 if (!empty($params['financial_type_id']) &&
2806 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2808 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2809 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2810 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2811 if ($oldFinancialAccount != $newFinancialAccount) {
2812 $params['total_amount'] = 0;
2813 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2814 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2815 $params['prevContribution']->financial_type_id
, $relationTypeId);
2818 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2819 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2820 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2823 self
::updateFinancialAccounts($params, 'changeFinancialType');
2824 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2825 $params['financial_account_id'] = $newFinancialAccount;
2826 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2827 self
::updateFinancialAccounts($params);
2828 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2832 //Update contribution status
2833 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2834 if (!empty($params['contribution_status_id']) &&
2835 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2837 //Update Financial Records
2838 self
::updateFinancialAccounts($params, 'changedStatus');
2841 // change Payment Instrument for a Completed contribution
2842 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2843 // instrument is null and now new payment instrument is added along with the payment
2844 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2845 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2846 if (array_key_exists('payment_instrument_id', $params)) {
2847 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2848 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2849 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2851 //check if status is changed from Pending to Completed
2852 // do not update payment instrument changes for Pending to Completed
2853 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2854 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2856 // for all other statuses create new financial records
2857 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2858 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2859 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2862 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2863 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2864 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2866 // for any other payment instrument changes create new financial records
2867 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2868 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2869 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2871 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2872 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2874 // another special case when check number is changed, create new financial records
2875 // create financial trxn with negative amount
2876 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2877 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2878 // create financial trxn with positive amount
2879 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2880 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2881 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2885 //if Change contribution amount
2886 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2887 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2888 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2889 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2890 if (isset($totalAmount) &&
2891 $totalAmount != $params['prevContribution']->total_amount
2893 //Update Financial Records
2894 $params['trxnParams']['from_financial_account_id'] = NULL;
2895 self
::updateFinancialAccounts($params, 'changedAmount');
2900 // records finanical trxn and entity financial trxn
2901 // also make it available as return value
2902 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2903 $params['entity_id'] = $financialTxn->id
;
2906 // record line items and finacial items
2907 if (empty($params['skipLineItem'])) {
2908 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2911 // create batch entry if batch_id is passed
2912 if (!empty($params['batch_id'])) {
2913 $entityParams = array(
2914 'batch_id' => $params['batch_id'],
2915 'entity_table' => 'civicrm_financial_trxn',
2916 'entity_id' => $financialTxn->id
,
2918 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2921 // when a fee is charged
2922 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2923 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2926 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2927 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2929 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2930 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2931 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2933 unset($params['line_item']);
2939 * Update all financial accounts entry
2941 * @param array $params
2942 * Contribution object, line item array and params for trxn.
2944 * @param string $context
2947 * @param null $skipTrxn
2950 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2951 $itemAmount = $trxnID = NULL;
2952 //get all the statuses
2953 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2954 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2955 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2956 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2957 && $context == 'changePaymentInstrument'
2961 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2962 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2964 if ($context == 'changedStatus') {
2965 //get all the statuses
2966 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2968 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2969 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2970 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2972 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2974 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2975 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2977 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2978 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2979 $params['trxnParams']['to_financial_account_id'] = NULL;
2980 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2982 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2983 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2984 $financialTypeID, $relationTypeId);
2986 $itemAmount = $params['trxnParams']['total_amount'];
2988 elseif ($context == 'changePaymentInstrument') {
2989 if ($params['trxnParams']['total_amount'] < 0) {
2990 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2991 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2992 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2993 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2997 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2998 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3001 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3002 $params['entity_id'] = $trxn->id
;
3004 if ($context == 'changedStatus') {
3005 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3006 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3007 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3009 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3010 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3012 $entityParams = array(
3013 'entity_table' => 'civicrm_financial_item',
3014 'financial_trxn_id' => $trxn->id
,
3016 if (empty($params['line_item'])) {
3018 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3019 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3020 // & this can be removed
3023 foreach ($params['line_item'] as $fieldId => $fields) {
3024 foreach ($fields as $fieldValueId => $fieldValues) {
3026 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3027 2 => array($fieldValues['id'], 'Integer'),
3029 CRM_Core_DAO
::executeQuery($query, $fparams);
3031 1 => array($fieldValues['id'], 'Integer'),
3033 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3034 while ($financialItem->fetch()) {
3035 $entityParams['entity_id'] = $financialItem->id
;
3036 $entityParams['amount'] = $financialItem->amount
;
3037 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3044 if ($context != 'changePaymentInstrument') {
3045 $itemParams['entity_table'] = 'civicrm_line_item';
3046 $trxnIds['id'] = $params['entity_id'];
3047 foreach ($params['line_item'] as $fieldId => $fields) {
3048 foreach ($fields as $fieldValueId => $fieldValues) {
3049 $prevParams['entity_id'] = $fieldValues['id'];
3050 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3052 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3053 if ($params['contribution']->receive_date
) {
3054 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3057 $financialAccount = $prevfinancialItem->financial_account_id
;
3058 if (!empty($params['financial_account_id'])) {
3059 $financialAccount = $params['financial_account_id'];
3062 $currency = $params['prevContribution']->currency
;
3063 if ($params['contribution']->currency
) {
3064 $currency = $params['contribution']->currency
;
3067 if (!empty($params['is_quick_config'])) {
3068 $amount = $itemAmount;
3070 $amount = $params['total_amount'];
3074 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3075 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3079 $amount = $diff * $fieldValues['line_total'];
3082 $itemParams = array(
3083 'transaction_date' => $receiveDate,
3084 'contact_id' => $params['prevContribution']->contact_id
,
3085 'currency' => $currency,
3086 'amount' => $amount,
3087 'description' => $prevfinancialItem->description
,
3088 'status_id' => $prevfinancialItem->status_id
,
3089 'financial_account_id' => $financialAccount,
3090 'entity_table' => 'civicrm_line_item',
3091 'entity_id' => $fieldValues['id'],
3093 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3095 if ($fieldValues['tax_amount']) {
3096 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3097 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3098 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3099 $itemParams['description'] = $taxTerm;
3100 if ($fieldValues['financial_type_id']) {
3101 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3103 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3111 * Check status validation on update of a contribution
3113 * @param array $values
3114 * Previous form values before submit.
3116 * @param array $fields
3117 * The input form values.
3119 * @param array $errors
3124 public static function checkStatusValidation($values, &$fields, &$errors) {
3125 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3126 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3127 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3131 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3132 $checkStatus = array(
3133 'Cancelled' => array('Completed', 'Refunded'),
3134 'Completed' => array('Cancelled', 'Refunded'),
3135 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3136 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3137 'Refunded' => array('Cancelled', 'Completed'),
3140 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3141 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3142 1 => $contributionStatuses[$values['contribution_status_id']],
3143 2 => $contributionStatuses[$fields['contribution_status_id']],
3149 * Delete contribution of contact
3153 * @param int $contactId
3157 public static function deleteContactContribution($contactId) {
3158 $contribution = new CRM_Contribute_DAO_Contribution();
3159 $contribution->contact_id
= $contactId;
3160 $contribution->find();
3161 while ($contribution->fetch()) {
3162 self
::deleteContribution($contribution->id
);
3167 * Get options for a given contribution field.
3168 * @see CRM_Core_DAO::buildOptions
3170 * @param string $fieldName
3171 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3172 * @param array $props whatever is known about this dao object.
3174 * @return array|bool
3176 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3177 $className = __CLASS__
;
3179 switch ($fieldName) {
3180 // This field is not part of this object but the api supports it
3181 case 'payment_processor':
3182 $className = 'CRM_Contribute_BAO_ContributionPage';
3183 // Filter results by contribution page
3184 if (!empty($props['contribution_page_id'])) {
3185 $page = civicrm_api('contribution_page', 'getsingle', array(
3187 'id' => ($props['contribution_page_id']),
3189 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3190 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3194 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3195 case 'honor_type_id':
3196 $className = 'CRM_Contribute_BAO_ContributionSoft';
3197 $fieldName = 'soft_credit_type_id';
3198 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3201 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3205 * Validate financial type
3209 * @param int $financialTypeId
3210 * Financial Type id.
3212 * @param string $relationName
3214 * @return array|bool
3216 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3217 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3218 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3220 if (!$financialAccount) {
3221 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3228 * Function to record additional payment for partial and refund contributions
3230 * @param int $contributionId
3231 * is the invoice contribution id (got created after processing participant payment).
3232 * @param array $trxnsData
3233 * to take user provided input of transaction details.
3234 * @param string $paymentType
3235 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3236 * @param int $participantId
3238 * @return null|object
3240 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3241 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3242 $getInfoOf['id'] = $contributionId;
3243 $defaults = array();
3244 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3246 if ($paymentType == 'owed') {
3247 // build params for recording financial trxn entry
3248 $params['contribution'] = $contributionDAO;
3249 $params = array_merge($defaults, $params);
3250 $params['skipLineItem'] = TRUE;
3251 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3252 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3253 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3256 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3257 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3258 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3260 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3261 if (!empty($trxnId)) {
3262 $trxnId = $trxnId['trxn_id'];
3264 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3265 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3268 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3269 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3270 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3274 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3275 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3276 FROM civicrm_financial_trxn ft
3277 LEFT JOIN civicrm_entity_financial_trxn eft
3278 ON (ft.id = eft.financial_trxn_id)
3279 WHERE eft.entity_table = 'civicrm_contribution'
3280 AND eft.entity_id = {$contributionId}
3281 AND ft.to_financial_account_id != {$toFinancialAccount}
3282 AND ft.status_id = {$statusId}
3284 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3287 if ($contributionDAO->total_amount
== $sumOfPayments) {
3288 // update contribution status and
3289 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3290 $contributionDAO->contribution_status_id
= $statusId;
3291 $contributionDAO->cancel_date
= 'null';
3292 $contributionDAO->cancel_reason
= NULL;
3293 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3294 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3295 $contributionDAO->save();
3297 //Change status of financial record too
3298 $financialTrxn->status_id
= $statusId;
3299 $financialTrxn->save();
3301 // note : not using the self::add method,
3302 // the reason because it performs 'status change' related code execution for financial records
3303 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3304 // are coded below i.e. just updating financial_item status to 'Paid'
3306 if ($participantId) {
3307 // update participant status
3308 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3309 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3310 foreach ($ids as $val) {
3311 $participantUpdate['id'] = $val;
3312 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3313 CRM_Event_BAO_Participant
::add($participantUpdate);
3317 // update financial item statuses
3318 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3319 $paidStatus = array_search('Paid', $financialItemStatus);
3321 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3322 $sqlFinancialItemUpdate = "
3323 UPDATE civicrm_financial_item fi
3324 LEFT JOIN civicrm_entity_financial_trxn eft
3325 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3326 SET status_id = {$paidStatus}
3327 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3329 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3332 elseif ($paymentType == 'refund') {
3333 // build params for recording financial trxn entry
3334 $params['contribution'] = $contributionDAO;
3335 $params = array_merge($defaults, $params);
3336 $params['skipLineItem'] = TRUE;
3337 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3338 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3340 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3341 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3342 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3344 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3346 // note : not using the self::add method,
3347 // the reason because it performs 'status change' related code execution for financial records
3348 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3349 // are coded below i.e. just updating financial_item status to 'Paid'
3350 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3352 // add financial item entry
3353 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3354 $getLine['entity_id'] = $contributionDAO->id
;
3355 $getLine['entity_table'] = 'civicrm_contribution';
3356 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3357 if (!empty($lineItemId->id
)) {
3358 $addFinancialEntry = array(
3359 'transaction_date' => $financialTrxn->trxn_date
,
3360 'contact_id' => $contributionDAO->contact_id
,
3361 'amount' => $financialTrxn->total_amount
,
3362 'status_id' => array_search('Paid', $financialItemStatus),
3363 'entity_id' => $lineItemId->id
,
3364 'entity_table' => 'civicrm_line_item',
3366 $trxnIds['id'] = $financialTrxn->id
;
3367 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3369 if ($participantId) {
3370 // update participant status
3371 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3372 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3373 foreach ($ids as $val) {
3374 $participantUpdate['id'] = $val;
3375 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3376 CRM_Event_BAO_Participant
::add($participantUpdate);
3381 // activity creation
3382 if (!empty($financialTrxn)) {
3383 if ($participantId) {
3384 $inputParams['id'] = $participantId;
3387 $component = 'event';
3388 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3389 $entityObj = $entityObj[$participantId];
3391 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3393 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3395 return $financialTrxn;
3401 * @param $activityType
3403 * @param int $contributionId
3405 * @throws CRM_Core_Exception
3407 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3408 if ($component == 'event') {
3409 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3410 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3411 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3412 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3413 $targetCid = $entityObj->contact_id
;
3414 // source record id would be the contribution id
3415 $srcRecId = $contributionId;
3419 $activityParams = array(
3420 'source_contact_id' => $targetCid,
3421 'source_record_id' => $srcRecId,
3422 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3426 'subject' => $subject,
3427 'activity_date_time' => $date,
3428 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3432 'skipRecentView' => TRUE,
3435 // create activity with target contacts
3436 $session = CRM_Core_Session
::singleton();
3437 $id = $session->get('userID');
3439 $activityParams['source_contact_id'] = $id;
3440 $activityParams['target_contact_id'][] = $targetCid;
3442 CRM_Activity_BAO_Activity
::create($activityParams);
3446 * Get list of payments displayed by Contribute_Page_PaymentInfo
3450 * @param bool $getTrxnInfo
3451 * @param bool $usingLineTotal
3455 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3456 if ($component == 'event') {
3457 $entity = 'participant';
3458 $entityTable = 'civicrm_participant';
3459 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3461 if (!$contributionId) {
3462 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3463 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3464 $id = $primaryParticipantId;
3466 if (!$contributionId) {
3471 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3472 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3478 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3479 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3482 if (empty($total) ||
$usingLineTotal) {
3483 // for additional participants
3484 if ($entityTable == 'civicrm_participant') {
3485 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3487 foreach ($ids as $val) {
3488 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3492 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3496 $baseTrxnId = $total['trxn_id'];
3497 $total = $total['total_amount'];
3500 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3501 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3503 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3504 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3505 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3507 if ($paymentBalance == 0 && $contributionIsPayLater) {
3508 $paymentBalance = $total;
3511 $info['total'] = $total;
3512 $info['paid'] = $total - $paymentBalance;
3513 $info['balance'] = $paymentBalance;
3515 $info['component'] = $component;
3516 $info['payLater'] = $contributionIsPayLater;
3518 if ($getTrxnInfo && $baseTrxnId) {
3519 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3521 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3522 FROM civicrm_contribution con
3523 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3524 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3525 WHERE con.id = {$contributionId}
3528 // conditioned WHERE clause
3530 // if balance trxn exists don't include details of it in transaction info
3531 $sql .= " AND ft.id != {$baseTrxnId} ";
3533 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3535 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3536 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3537 while ($resultDAO->fetch()) {
3538 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3539 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3541 'total_amount' => $resultDAO->total_amount
,
3542 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3543 'payment_instrument' => $paidByLabel,
3544 'receive_date' => $resultDAO->trxn_date
,
3545 'trxn_id' => $resultDAO->trxn_id
,
3546 'status' => $statuses[$resultDAO->status_id
],
3548 if ($paidByName == 'Check') {
3549 $val['check_number'] = $resultDAO->check_number
;
3553 $info['transaction'] = $rows;
3559 * Get financial account id has 'Sales Tax Account is'
3560 * account relationship with financial type
3562 * @param int $financialTypeId
3564 * @return FinancialAccountId
3566 public static function getFinancialAccountId($financialTypeId) {
3567 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3568 $searchParams = array(
3569 'entity_table' => 'civicrm_financial_type',
3570 'entity_id' => $financialTypeId,
3571 'account_relationship' => $accountRel,
3574 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3576 return CRM_Utils_Array
::value('financial_account_id', $result);
3582 * @param array $params
3583 * @param bool $isLineItem
3587 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3588 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3590 // Update contribution.
3591 if (!empty($params['id'])) {
3592 $id = $params['id'];
3593 $values = $ids = array();
3594 $contrbutionParams = array('id' => $id);
3595 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3597 // To assign pervious finantial type on update of contribution
3598 if (!isset($params['financial_type_id'])) {
3599 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3601 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3602 // Assisn tax Amount on update of contrbution
3603 if (!empty($prevContributionValue->tax_amount
)) {
3604 $params['tax_amount'] = 'null';
3605 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3606 foreach ($params['line_item'] as $setID => $priceField) {
3607 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3608 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3615 // New Contrbution and update of contribution with tax rate financial type
3616 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3617 empty($params['skipLineItem']) && !$isLineItem
3619 $taxRateParams = $taxRates[$params['financial_type_id']];
3620 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3621 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3623 // Get Line Item on update of contribution
3624 if (isset($params['id'])) {
3625 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3628 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3630 foreach ($params['line_item'] as $setID => $priceField) {
3631 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3632 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3635 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3637 elseif (isset($params['api.line_item.create'])) {
3638 // Update total amount of contribution using lineItem
3639 $taxAmountArray = array();
3640 foreach ($params['api.line_item.create'] as $key => $value) {
3641 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3642 $taxRate = $taxRates[$value['financial_type_id']];
3643 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3644 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3647 $params['tax_amount'] = array_sum($taxAmountArray);
3648 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3651 // update line item of contrbution
3652 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3653 $taxRate = $taxRates[$params['financial_type_id']];
3654 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3655 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);