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
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 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
397 if (isset($params['soft_credit'])) {
398 $softParams = $params['soft_credit'];
400 if (!empty($softIDs)) {
401 foreach ($softIDs as $softID) {
402 if (!in_array($softID, $params['soft_credit_ids'])) {
403 $deleteParams = array('id' => $softID);
404 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
409 foreach ($softParams as $softParam) {
410 $softParam['contribution_id'] = $contribution->id
;
411 $softParam['currency'] = $contribution->currency
;
412 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
413 if (empty($softParam['amount'])) {
414 $softParam['amount'] = $contribution->total_amount
;
416 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
420 $transaction->commit();
422 // do not add to recent items for import, CRM-4399
423 if (empty($params['skipRecentView'])) {
424 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
425 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
427 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
428 $titleFields = array(
434 $retrieveRequired = 0;
435 foreach ($titleFields as $titleField) {
436 if (!isset($contribution->$titleField)) {
437 $retrieveRequired = 1;
441 if ($retrieveRequired == 1) {
442 $contribution->find(TRUE);
444 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
445 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
447 $recentOther = array();
448 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
449 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
450 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
454 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
455 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
456 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
460 // add the recently created Contribution
461 CRM_Utils_Recent
::add($title,
465 $contribution->contact_id
,
471 return $contribution;
475 * Get the values for pseudoconstants for name->value and reverse.
477 * @param array $defaults
478 * (reference) the default values, some of which need to be resolved.
479 * @param bool $reverse
480 * True if we want to resolve the values in the reverse direction (value -> name).
484 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
485 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
486 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
487 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
488 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
492 * convert associative array names to values
495 * This function is used by both the web form layer and the api. Note that
496 * the api needs the name => value conversion, also the view layer typically
497 * requires value => name conversion
499 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
500 $id = $property . '_id';
502 $src = $reverse ?
$property : $id;
503 $dst = $reverse ?
$id : $property;
505 if (!array_key_exists($src, $defaults)) {
509 $look = $reverse ?
array_flip($lookup) : $lookup;
511 if (is_array($look)) {
512 if (!array_key_exists($defaults[$src], $look)) {
516 $defaults[$dst] = $look[$defaults[$src]];
521 * Takes a bunch of params that are needed to match certain criteria and
522 * retrieves the relevant objects. We'll tweak this function to be more
523 * full featured over a period of time. This is the inverse function of
524 * create. It also stores all the retrieved values in the default array
526 * @param array $params
527 * (reference ) an assoc array of name/value pairs.
528 * @param array $defaults
529 * (reference ) an assoc array to hold the name / value pairs.
530 * in a hierarchical manner
532 * (reference) the array that holds all the db ids.
534 * @return CRM_Contribute_BAO_Contribution
536 public static function retrieve(&$params, &$defaults, &$ids) {
537 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
538 return $contribution;
542 * Combine all the importable fields from the lower levels object
544 * The ordering is important, since currently we do not have a weight
545 * scheme. Adding weight is super important and should be done in the
546 * next week or so, before this can be called complete.
548 * @param string $contactType
549 * @param bool $status
552 * array of importable Fields
554 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
555 if (!self
::$_importableFields) {
556 if (!self
::$_importableFields) {
557 self
::$_importableFields = array();
561 $fields = array('' => array('title' => ts('- do not import -')));
564 $fields = array('' => array('title' => ts('- Contribution Fields -')));
567 $note = CRM_Core_DAO_Note
::import();
568 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
569 unset($tmpFields['option_value']);
570 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
571 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
573 // Using new Dedupe rule.
575 'contact_type' => $contactType,
576 'used' => 'Unsupervised',
578 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
579 $tmpContactField = array();
580 if (is_array($fieldsArray)) {
581 foreach ($fieldsArray as $value) {
582 //skip if there is no dupe rule
583 if ($value == 'none') {
586 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
591 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
592 $tmpContactField[trim($value)] = $contactFields[trim($value)];
594 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
597 $title = $tmpContactField[trim($value)]['title'];
599 $tmpContactField[trim($value)]['title'] = $title;
603 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
604 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
605 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
606 $fields = array_merge($fields, $tmpContactField);
607 $fields = array_merge($fields, $tmpFields);
608 $fields = array_merge($fields, $note);
609 $fields = array_merge($fields, $optionFields);
610 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
611 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
612 self
::$_importableFields = $fields;
614 return self
::$_importableFields;
620 public static function &exportableFields() {
621 if (!self
::$_exportableFields) {
622 if (!self
::$_exportableFields) {
623 self
::$_exportableFields = array();
626 $impFields = CRM_Contribute_DAO_Contribution
::export();
627 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
628 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
629 $typeField = CRM_Financial_DAO_FinancialType
::export();
630 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
631 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
632 $contributionStatus = array(
633 'contribution_status' => array(
634 'title' => ts('Contribution Status'),
635 'name' => 'contribution_status',
636 'data_type' => CRM_Utils_Type
::T_STRING
,
640 $contributionPage = array(
641 'contribution_page' => array(
642 'title' => ts('Contribution Page'),
643 'name' => 'contribution_page',
644 'where' => 'civicrm_contribution_page.title',
645 'data_type' => CRM_Utils_Type
::T_STRING
648 $contributionNote = array(
649 'contribution_note' =>
651 'title' => ts('Contribution Note'),
652 'name' => 'contribution_note',
653 'data_type' => CRM_Utils_Type
::T_TEXT
,
657 $contributionRecurId = array(
658 'contribution_recur_id' => array(
659 'title' => ts('Recurring Contributions ID'),
660 'name' => 'contribution_recur_id',
661 'where' => 'civicrm_contribution.contribution_recur_id',
662 'data_type' => CRM_Utils_Type
::T_INT
,
666 $extraFields = array(
667 'contribution_batch' => array(
668 'title' => ts('Batch Name'),
672 $softCreditFields = array(
673 'contribution_soft_credit_name' => array(
674 'name' => 'contribution_soft_credit_name',
675 'title' => 'Soft Credit For',
676 'where' => 'civicrm_contact_d.display_name',
677 'data_type' => CRM_Utils_Type
::T_STRING
,
679 'contribution_soft_credit_amount' => array(
680 'name' => 'contribution_soft_credit_amount',
681 'title' => 'Soft Credit Amount',
682 'where' => 'civicrm_contribution_soft.amount',
683 'data_type' => CRM_Utils_Type
::T_MONEY
,
685 'contribution_soft_credit_type' => array(
686 'name' => 'contribution_soft_credit_type',
687 'title' => 'Soft Credit Type',
688 'where' => 'contribution_softcredit_type.label',
689 'data_type' => CRM_Utils_Type
::T_STRING
,
691 'contribution_soft_credit_contribution_id' => array(
692 'name' => 'contribution_soft_credit_contribution_id',
693 'title' => 'Soft Credit For Contribution ID',
694 'where' => 'civicrm_contribution_soft.contribution_id',
695 'data_type' => CRM_Utils_Type
::T_INT
,
699 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
700 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
701 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
704 self
::$_exportableFields = $fields;
707 return self
::$_exportableFields;
711 * @param null $status
712 * @param null $startDate
713 * @param null $endDate
717 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
721 $where[] = 'contribution_status_id = 1';
725 $where[] = 'contribution_status_id = 3';
730 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
733 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
736 $whereCond = implode(' AND ', $where);
739 SELECT sum( total_amount ) as total_amount,
740 count( civicrm_contribution.id ) as total_count,
742 FROM civicrm_contribution
743 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
745 AND ( is_test = 0 OR is_test IS NULL )
746 AND contact.is_deleted = 0
750 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
753 while ($dao->fetch()) {
754 $count +
= $dao->total_count
;
755 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
759 'amount' => implode(', ', $amount),
767 * Delete the indirect records associated with this contribution first
772 * $results no of deleted Contribution on success, false otherwise
775 public static function deleteContribution($id) {
776 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
778 $transaction = new CRM_Core_Transaction();
781 //delete activity record
783 'source_record_id' => $id,
784 // activity type id for contribution
785 'activity_type_id' => 6,
788 CRM_Activity_BAO_Activity
::deleteActivity($params);
790 //delete billing address if exists for this contribution.
791 self
::deleteAddress($id);
793 //update pledge and pledge payment, CRM-3961
794 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
796 // remove entry from civicrm_price_set_entity, CRM-5095
797 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
798 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
800 // cleanup line items.
801 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
803 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
804 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
806 if ($participantId) {
807 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
810 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
814 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
815 $noteId = key($note);
817 CRM_Core_BAO_Note
::del($noteId, FALSE);
820 $dao = new CRM_Contribute_DAO_Contribution();
823 $results = $dao->delete();
825 $transaction->commit();
827 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
829 // delete the recently created Contribution
830 $contributionRecent = array(
832 'type' => 'Contribution',
834 CRM_Utils_Recent
::del($contributionRecent);
840 * Check if there is a contribution with the same trxn_id or invoice_id
842 * @param array $input
843 * An assoc array of name/value pairs.
844 * @param array $duplicates
845 * (reference) store ids of duplicate contribs.
849 * true if duplicate, false otherwise
851 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
853 $id = CRM_Utils_Array
::value('id', $input);
855 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
856 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
862 $clause[] = "trxn_id = %1";
863 $input[1] = array($trxn_id, 'String');
867 $clause[] = "invoice_id = %2";
868 $input[2] = array($invoice_id, 'String');
871 if (empty($clause)) {
875 $clause = implode(' OR ', $clause);
877 $clause = "( $clause ) AND id != %3";
878 $input[3] = array($id, 'Integer');
881 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
882 $dao = CRM_Core_DAO
::executeQuery($query, $input);
884 while ($dao->fetch()) {
885 $duplicates[] = $dao->id
;
892 * Takes an associative array and creates a contribution_product object
894 * the function extract all the params it needs to initialize the create a
895 * contribution_product object. the params array could contain additional unused name/value
898 * @param array $params
899 * (reference) an assoc array of name/value pairs.
901 * @return CRM_Contribute_DAO_ContributionProduct
903 public static function addPremium(&$params) {
904 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
905 $contributionProduct->copyValues($params);
906 return $contributionProduct->save();
910 * Get list of contribution fields for profile
911 * For now we only allow custom contribution fields to be in
914 * @param bool $addExtraFields
915 * True if special fields needs to be added.
918 * the list of contribution fields
920 public static function getContributionFields($addExtraFields = TRUE) {
921 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
922 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
924 if ($addExtraFields) {
925 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
928 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
930 foreach ($contributionFields as $key => $var) {
931 if ($key == 'contribution_contact_id') {
934 elseif ($key == 'contribution_campaign_id') {
935 $var['title'] = ts('Campaign');
937 $fields[$key] = $var;
940 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
945 * Add extra fields specific to contribtion
948 public static function getSpecialContributionFields() {
949 $extraFields = array(
950 'contribution_soft_credit_name' => array(
951 'name' => 'contribution_soft_credit_name',
952 'title' => 'Soft Credit Name',
953 'headerPattern' => '/^soft_credit_name$/i',
954 'where' => 'civicrm_contact_d.display_name',
956 'contribution_soft_credit_email' => array(
957 'name' => 'contribution_soft_credit_email',
958 'title' => 'Soft Credit Email',
959 'headerPattern' => '/^soft_credit_email$/i',
960 'where' => 'soft_email.email',
962 'contribution_soft_credit_phone' => array(
963 'name' => 'contribution_soft_credit_phone',
964 'title' => 'Soft Credit Phone',
965 'headerPattern' => '/^soft_credit_phone$/i',
966 'where' => 'soft_phone.phone',
968 'contribution_soft_credit_contact_id' => array(
969 'name' => 'contribution_soft_credit_contact_id',
970 'title' => 'Soft Credit Contact ID',
971 'headerPattern' => '/^soft_credit_contact_id$/i',
972 'where' => 'civicrm_contribution_soft.contact_id',
984 public static function getCurrentandGoalAmount($pageID) {
986 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
987 FROM civicrm_contribution_page p,
988 civicrm_contribution c
989 WHERE p.id = c.contribution_page_id
991 AND c.cancel_date is null
995 $config = CRM_Core_Config
::singleton();
996 $params = array(1 => array($pageID, 'Integer'));
997 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1000 return array($dao->goal
, $dao->total
);
1003 return array(NULL, NULL);
1008 * Get list of contribution In Honor of contact Ids
1010 * @param int $honorId
1011 * In Honor of Contact ID.
1014 * list of contribution fields
1017 public static function getHonorContacts($honorId) {
1019 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1020 $honorDAO->contact_id
= $honorId;
1023 $type = CRM_Contribute_PseudoConstant
::financialType();
1025 while ($honorDAO->fetch()) {
1026 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1027 $contributionDAO->id
= $honorDAO->contribution_id
;
1029 if ($contributionDAO->find(TRUE)) {
1030 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1031 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1032 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1033 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1034 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1035 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1036 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1037 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1038 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1046 * Get the sort name of a contact for a particular contribution
1049 * Id of the contribution.
1051 * @return null|string
1052 * sort name of the contact if found
1054 public static function sortName($id) {
1055 $id = CRM_Utils_Type
::escape($id, 'Integer');
1058 SELECT civicrm_contact.sort_name
1059 FROM civicrm_contribution, civicrm_contact
1060 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1061 AND civicrm_contribution.id = {$id}
1063 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1067 * @param int $contactID
1071 public static function annual($contactID) {
1072 if (is_array($contactID)) {
1073 $contactIDs = implode(',', $contactID);
1076 $contactIDs = $contactID;
1079 $config = CRM_Core_Config
::singleton();
1080 $startDate = $endDate = NULL;
1082 $currentMonth = date('m');
1083 $currentDay = date('d');
1084 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1085 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1086 (int ) $config->fiscalYearStart
['d'] > $currentDay
1089 $year = date('Y') - 1;
1094 $nextYear = $year +
1;
1096 if ($config->fiscalYearStart
) {
1097 if ($config->fiscalYearStart
['M'] < 10) {
1098 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1100 if ($config->fiscalYearStart
['d'] < 10) {
1101 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1103 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1108 $startDate = "$year$monthDay";
1109 $endDate = "$nextYear$monthDay";
1112 SELECT count(*) as count,
1113 sum(total_amount) as amount,
1114 avg(total_amount) as average,
1116 FROM civicrm_contribution b
1117 WHERE b.contact_id IN ( $contactIDs )
1118 AND b.contribution_status_id = 1
1120 AND b.receive_date >= $startDate
1121 AND b.receive_date < $endDate
1124 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1126 $amount = $average = array();
1127 while ($dao->fetch()) {
1128 if ($dao->count
> 0 && $dao->amount
> 0) {
1129 $count +
= $dao->count
;
1130 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1131 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1137 implode(', ', $amount),
1138 implode(', ', $average),
1141 return array(0, 0, 0);
1145 * Check if there is a contribution with the params passed in.
1146 * Used for trxn_id,invoice_id and contribution_id
1148 * @param array $params
1149 * An assoc array of name/value pairs.
1152 * contribution id if success else NULL
1154 public static function checkDuplicateIds($params) {
1155 $dao = new CRM_Contribute_DAO_Contribution();
1159 foreach ($params as $k => $v) {
1161 $clause[] = "$k = '$v'";
1164 $clause = implode(' AND ', $clause);
1165 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1166 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1168 while ($dao->fetch()) {
1176 * Get the contribution details for component export
1178 * @param int $exportMode
1180 * @param string $componentIds
1187 public static function getContributionDetails($exportMode, $componentIds) {
1188 $paymentDetails = array();
1189 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1191 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1192 $componentSelect = " civicrm_participant_payment.participant_id id";
1193 $additionalClause = "
1194 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1195 AND civicrm_participant_payment.participant_id {$componentClause} )
1198 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1199 $componentSelect = " civicrm_membership_payment.membership_id id";
1200 $additionalClause = "
1201 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1202 AND civicrm_membership_payment.membership_id {$componentClause} )
1205 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1206 $componentSelect = " civicrm_pledge_payment.id id";
1207 $additionalClause = "
1208 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1209 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1213 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1214 trxn_id, {$componentSelect}
1215 FROM civicrm_contribution
1216 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1217 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1218 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1219 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1220 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1221 AND option_group_contribution_status.id = contribution_status.option_group_id )
1225 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1227 while ($dao->fetch()) {
1228 $paymentDetails[$dao->id
] = array(
1229 'total_amount' => $dao->total_amount
,
1230 'contribution_status' => $dao->status
,
1231 'receive_date' => $dao->receive_date
,
1232 'pay_instru' => $dao->payment_instrument
,
1233 'trxn_id' => $dao->trxn_id
,
1237 return $paymentDetails;
1241 * Create address associated with contribution record.
1243 * @param array $params
1244 * @param int $billingLocationTypeID
1249 public static function createAddress(&$params, $billingLocationTypeID) {
1250 $billingFields = array(
1253 'state_province_id',
1258 //build address array
1259 $addressParams = array();
1260 $addressParams['location_type_id'] = $billingLocationTypeID;
1261 $addressParams['is_billing'] = 1;
1263 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1264 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1265 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1266 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1268 foreach ($billingFields as $value) {
1269 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1272 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1274 return $address->id
;
1278 * Delete billing address record related contribution
1280 * @param int $contributionId
1281 * @param int $contactId
1284 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1286 $contactJoin = NULL;
1288 if ($contributionId) {
1289 $clauses[] = "cc.id = {$contributionId}";
1293 $clauses[] = "cco.id = {$contactId}";
1294 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1297 if (empty($clauses)) {
1298 CRM_Core_Error
::fatal();
1301 $condition = implode(' OR ', $clauses);
1305 FROM civicrm_address ca
1306 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1310 $dao = CRM_Core_DAO
::executeQuery($query);
1312 while ($dao->fetch()) {
1313 $params = array('id' => $dao->id
);
1314 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1319 * This function check online pending contribution associated w/
1320 * Online Event Registration or Online Membership signup.
1322 * @param int $componentId
1323 * Participant/membership id.
1324 * @param string $componentName
1328 * pending contribution id.
1330 public static function checkOnlinePendingContribution($componentId, $componentName) {
1331 $contributionId = NULL;
1332 if (!$componentId ||
1333 !in_array($componentName, array('Event', 'Membership'))
1335 return $contributionId;
1338 if ($componentName == 'Event') {
1339 $idName = 'participant_id';
1340 $componentTable = 'civicrm_participant';
1341 $paymentTable = 'civicrm_participant_payment';
1342 $source = ts('Online Event Registration');
1345 if ($componentName == 'Membership') {
1346 $idName = 'membership_id';
1347 $componentTable = 'civicrm_membership';
1348 $paymentTable = 'civicrm_membership_payment';
1349 $source = ts('Online Contribution');
1352 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1355 SELECT component.id as {$idName},
1356 componentPayment.contribution_id as contribution_id,
1357 contribution.source source,
1358 contribution.contribution_status_id as contribution_status_id,
1359 contribution.is_pay_later as is_pay_later
1360 FROM $componentTable component
1361 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1362 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1363 WHERE component.id = {$componentId}";
1365 $dao = CRM_Core_DAO
::executeQuery($query);
1367 while ($dao->fetch()) {
1368 if ($dao->contribution_id
&&
1369 $dao->is_pay_later
&&
1370 $dao->contribution_status_id
== $pendingStatusId &&
1371 strpos($dao->source
, $source) !== FALSE
1373 $contributionId = $dao->contribution_id
;
1378 return $contributionId;
1382 * Update contribution as well as related objects.
1384 public static function transitionComponents($params, $processContributionObject = FALSE) {
1385 // get minimum required values.
1386 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1387 $componentId = CRM_Utils_Array
::value('component_id', $params);
1388 $componentName = CRM_Utils_Array
::value('componentName', $params);
1389 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1390 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1392 // if we already processed contribution object pass previous status id.
1393 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1395 $updateResult = array();
1397 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1399 // we process only ( Completed, Cancelled, or Failed ) contributions.
1400 if (!$contributionId ||
1401 !in_array($contributionStatusId, array(
1402 array_search('Completed', $contributionStatuses),
1403 array_search('Cancelled', $contributionStatuses),
1404 array_search('Failed', $contributionStatuses),
1407 return $updateResult;
1410 if (!$componentName ||
!$componentId) {
1411 // get the related component details.
1412 $componentDetails = self
::getComponentDetails($contributionId);
1415 $componentDetails['contact_id'] = $contactId;
1416 $componentDetails['component'] = $componentName;
1418 if ($componentName == 'event') {
1419 $componentDetails['participant'] = $componentId;
1422 $componentDetails['membership'] = $componentId;
1426 if (!empty($componentDetails['contact_id'])) {
1427 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1433 // do check for required ids.
1434 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1435 return $updateResult;
1438 //now we are ready w/ required ids, start processing.
1440 $baseIPN = new CRM_Core_Payment_BaseIPN();
1442 $input = $ids = $objects = array();
1444 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1445 $ids['contribution'] = $contributionId;
1446 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1447 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1448 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1449 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1450 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1451 $ids['contributionRecur'] = NULL;
1452 $ids['contributionPage'] = NULL;
1454 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1455 CRM_Core_Error
::fatal();
1458 $memberships = &$objects['membership'];
1459 $participant = &$objects['participant'];
1460 $pledgePayment = &$objects['pledge_payment'];
1461 $contribution = &$objects['contribution'];
1463 if ($pledgePayment) {
1464 $pledgePaymentIDs = array();
1465 foreach ($pledgePayment as $key => $object) {
1466 $pledgePaymentIDs[] = $object->id
;
1468 $pledgeID = $pledgePayment[0]->pledge_id
;
1471 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1474 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1475 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1480 // we might want to process contribution object.
1481 $processContribution = FALSE;
1482 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1483 if (is_array($memberships)) {
1484 foreach ($memberships as $membership) {
1486 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1487 $membership->save();
1489 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1490 if ($processContributionObject) {
1491 $processContribution = TRUE;
1498 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1499 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1501 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1502 if ($processContributionObject) {
1503 $processContribution = TRUE;
1507 if ($pledgePayment) {
1508 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1510 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1511 if ($processContributionObject) {
1512 $processContribution = TRUE;
1516 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1517 if (is_array($memberships)) {
1518 foreach ($memberships as $membership) {
1520 $membership->status_id
= array_search('Expired', $membershipStatuses);
1521 $membership->save();
1523 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1524 if ($processContributionObject) {
1525 $processContribution = TRUE;
1531 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1532 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1534 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1535 if ($processContributionObject) {
1536 $processContribution = TRUE;
1540 if ($pledgePayment) {
1541 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1543 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1544 if ($processContributionObject) {
1545 $processContribution = TRUE;
1549 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1551 // only pending contribution related object processed.
1552 if ($previousContriStatusId &&
1553 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1555 // this is case when we already processed contribution object.
1556 return $updateResult;
1558 elseif (!$previousContriStatusId &&
1559 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1561 // this is case when we are going to process contribution object later.
1562 return $updateResult;
1565 if (is_array($memberships)) {
1566 foreach ($memberships as $membership) {
1571 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1572 $membership->membership_type_id
,
1573 $membership->is_test
, $membership->id
1576 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1577 // this picks up membership type changes during renewals
1579 SELECT membership_type_id
1580 FROM civicrm_membership_log
1581 WHERE membership_id=$membership->id
1584 $dao = new CRM_Core_DAO
;
1586 if ($dao->fetch()) {
1587 if (!empty($dao->membership_type_id
)) {
1588 $membership->membership_type_id
= $dao->membership_type_id
;
1589 $membership->save();
1592 // else fall back to using current membership type
1595 // Figure out number of terms
1597 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1598 foreach ($lineitems as $lineitem) {
1599 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1600 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1602 // in case membership_num_terms comes through as null or zero
1603 $numterms = $numterms >= 1 ?
$numterms : 1;
1608 // CRM-15735-to update the membership status as per the contribution receive date
1609 if (!empty($params['receive_date'])) {
1610 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1611 $membership->end_date
,
1612 $membership->join_date
,
1613 $params['receive_date'],
1615 $membership->membership_type_id
,
1618 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1619 $membership->save();
1622 if ($currentMembership) {
1623 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1624 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1625 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1628 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1631 //get the status for membership.
1632 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1634 $dates['join_date'],
1637 $membership->membership_type_id
,
1641 $formattedParams = array(
1642 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1643 array_search('Current', $membershipStatuses)
1645 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1646 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1647 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1650 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1652 $membership->copyValues($formattedParams);
1653 $membership->save();
1655 //updating the membership log
1656 $membershipLog = array();
1657 $membershipLog = $formattedParams;
1658 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1659 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1661 $membershipLog['start_date'] = $logStartDate;
1662 $membershipLog['membership_id'] = $membership->id
;
1663 $membershipLog['modified_id'] = $membership->contact_id
;
1664 $membershipLog['modified_date'] = date('Ymd');
1665 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1667 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1669 //update related Memberships.
1670 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1672 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1675 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1676 if ($processContributionObject) {
1677 $processContribution = TRUE;
1680 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1686 $updatedStatusId = array_search('Registered', $participantStatuses);
1687 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1689 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1690 if ($processContributionObject) {
1691 $processContribution = TRUE;
1695 if ($pledgePayment) {
1696 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1698 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1699 if ($processContributionObject) {
1700 $processContribution = TRUE;
1705 // process contribution object.
1706 if ($processContribution) {
1707 $contributionParams = array();
1714 'payment_instrument_id',
1717 'financial_type_id',
1718 'contribution_status_id',
1719 'non_deductible_amount',
1723 foreach ($fields as $field) {
1724 if (empty($params[$field])) {
1727 $contributionParams[$field] = $params[$field];
1730 $ids = array('contribution' => $contributionId);
1731 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1734 return $updateResult;
1738 * Returns all contribution related object ids.
1740 public static function getComponentDetails($contributionId) {
1741 $componentDetails = $pledgePayment = array();
1742 if (!$contributionId) {
1743 return $componentDetails;
1747 SELECT c.id as contribution_id,
1748 c.contact_id as contact_id,
1749 mp.membership_id as membership_id,
1750 m.membership_type_id as membership_type_id,
1751 pp.participant_id as participant_id,
1752 p.event_id as event_id,
1753 pgp.id as pledge_payment_id
1754 FROM civicrm_contribution c
1755 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1756 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1757 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1758 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1759 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1760 WHERE c.id = $contributionId";
1762 $dao = CRM_Core_DAO
::executeQuery($query);
1763 $componentDetails = array();
1765 while ($dao->fetch()) {
1766 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1767 $componentDetails['contact_id'] = $dao->contact_id
;
1768 if ($dao->event_id
) {
1769 $componentDetails['event'] = $dao->event_id
;
1771 if ($dao->participant_id
) {
1772 $componentDetails['participant'] = $dao->participant_id
;
1774 if ($dao->membership_id
) {
1775 if (!isset($componentDetails['membership'])) {
1776 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1778 $componentDetails['membership'][] = $dao->membership_id
;
1779 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1781 if ($dao->pledge_payment_id
) {
1782 $pledgePayment[] = $dao->pledge_payment_id
;
1786 if ($pledgePayment) {
1787 $componentDetails['pledge_payment'] = $pledgePayment;
1790 return $componentDetails;
1794 * @param int $contactId
1795 * @param bool $includeSoftCredit
1797 * @return null|string
1799 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1804 $contactContributionsSQL = "
1805 SELECT contribution.id AS id
1806 FROM civicrm_contribution contribution
1807 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1809 $contactSoftCreditContributionsSQL = "
1810 SELECT contribution.id
1811 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1812 ON ( contribution.id = softContribution.contribution_id )
1813 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1814 $query = "SELECT count( x.id ) count FROM ( ";
1815 $query .= $contactContributionsSQL;
1817 if ($includeSoftCredit) {
1818 $query .= " UNION ";
1819 $query .= $contactSoftCreditContributionsSQL;
1824 return CRM_Core_DAO
::singleValueQuery($query);
1828 * Get individual id for onbehalf contribution
1830 * @param int $contributionId
1832 * @param int $contributorId
1836 * containing organization id and individual id
1838 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1842 if (!$contributionId) {
1846 // fetch contributor id if null
1847 if (!$contributorId) {
1848 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1849 $contributionId, 'contact_id'
1853 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1854 $activityTypeId = array_search('Contribution', $activityTypeIds);
1856 if ($activityTypeId && $contributorId) {
1858 SELECT civicrm_activity_contact.contact_id
1859 FROM civicrm_activity_contact
1860 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1861 WHERE civicrm_activity.activity_type_id = %1
1862 AND civicrm_activity.source_record_id = %2
1863 AND civicrm_activity_contact.record_type_id = %3
1866 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1867 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1870 1 => array($activityTypeId, 'Integer'),
1871 2 => array($contributionId, 'Integer'),
1872 3 => array($sourceID, 'Integer'),
1875 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1877 // for on behalf contribution source is individual and contributor is organization
1878 if ($sourceContactId && $sourceContactId != $contributorId) {
1879 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1880 // get rel type id for employee of relation
1881 foreach ($relationshipTypeIds as $id => $typeVals) {
1882 if ($typeVals['name_a_b'] == 'Employee of') {
1883 $relationshipTypeId = $id;
1888 $rel = new CRM_Contact_DAO_Relationship();
1889 $rel->relationship_type_id
= $relationshipTypeId;
1890 $rel->contact_id_a
= $sourceContactId;
1891 $rel->contact_id_b
= $contributorId;
1892 if ($rel->find(TRUE)) {
1893 $ids['individual_id'] = $rel->contact_id_a
;
1894 $ids['organization_id'] = $rel->contact_id_b
;
1905 public static function getContributionDates() {
1906 $config = CRM_Core_Config
::singleton();
1907 $currentMonth = date('m');
1908 $currentDay = date('d');
1909 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1910 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1911 (int ) $config->fiscalYearStart
['d'] > $currentDay
1914 $year = date('Y') - 1;
1919 $year = array('Y' => $year);
1920 $yearDate = $config->fiscalYearStart
;
1921 $yearDate = array_merge($year, $yearDate);
1922 $yearDate = CRM_Utils_Date
::format($yearDate);
1924 $monthDate = date('Ym') . '01';
1930 'yearDate' => $yearDate,
1931 'monthDate' => $monthDate,
1936 * Load objects relations to contribution object
1937 * Objects are stored in the $_relatedObjects property
1938 * In the first instance we are just moving functionality from BASEIpn -
1939 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1941 * Note that the unit test for the BaseIPN class tests this function
1943 * @param array $input
1944 * Input as delivered from Payment Processor.
1946 * Ids as Loaded by Payment Processor.
1947 * @param bool $required
1948 * Is Payment processor / contribution page required.
1949 * @param bool $loadAll
1950 * Load all related objects - even where id not passed in? (allows API to call this).
1955 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1957 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1958 if (empty($ids['contact']) && isset($this->contact_id
)) {
1959 $ids['contact'] = $this->contact_id
;
1962 if (empty($this->_component
)) {
1963 if (!empty($ids['event'])) {
1964 $this->_component
= 'event';
1967 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1970 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1971 $contributionType = new CRM_Financial_BAO_FinancialType();
1972 $contributionType->id
= $this->financial_type_id
;
1973 if (!$contributionType->find(TRUE)) {
1974 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1976 if (!empty($ids['contact'])) {
1977 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1978 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1979 $this->_relatedObjects
['contact']->find(TRUE);
1981 $this->_relatedObjects
['contributionType'] = $contributionType;
1983 if ($this->_component
== 'contribute') {
1984 // retrieve the other optional objects first so
1985 // stuff down the line can use this info and do things
1987 //in any case get the memberships associated with the contribution
1988 //because we now support multiple memberships w/ price set
1989 // see if there are any other memberships to be considered for same contribution.
1991 SELECT membership_id
1992 FROM civicrm_membership_payment
1993 WHERE contribution_id = %1 ";
1994 $params = array(1 => array($this->id
, 'Integer'));
1996 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1997 while ($dao->fetch()) {
1998 if ($dao->membership_id
) {
1999 if (!is_array($ids['membership'])) {
2000 $ids['membership'] = array();
2002 $ids['membership'][] = $dao->membership_id
;
2006 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2007 foreach ($ids['membership'] as $id) {
2009 $membership = new CRM_Member_BAO_Membership();
2010 $membership->id
= $id;
2011 if (!$membership->find(TRUE)) {
2012 throw new Exception("Could not find membership record: $id");
2014 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2015 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2016 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2017 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2018 $membership->free();
2023 if (!empty($ids['pledge_payment'])) {
2025 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2026 if (empty($paymentID)) {
2029 $payment = new CRM_Pledge_BAO_PledgePayment();
2030 $payment->id
= $paymentID;
2031 if (!$payment->find(TRUE)) {
2032 throw new Exception("Could not find pledge payment record: " . $paymentID);
2034 $this->_relatedObjects
['pledge_payment'][] = $payment;
2038 if (!empty($ids['contributionRecur'])) {
2039 $recur = new CRM_Contribute_BAO_ContributionRecur();
2040 $recur->id
= $ids['contributionRecur'];
2041 if (!$recur->find(TRUE)) {
2042 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2044 $this->_relatedObjects
['contributionRecur'] = &$recur;
2045 //get payment processor id from recur object.
2046 $paymentProcessorID = $recur->payment_processor_id
;
2048 //for normal contribution get the payment processor id.
2049 if (!$paymentProcessorID) {
2050 if ($this->contribution_page_id
) {
2051 // get the payment processor id from contribution page
2052 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2053 $this->contribution_page_id
,
2057 //fail to load payment processor id.
2058 elseif (empty($ids['pledge_payment'])) {
2059 $loadObjectSuccess = TRUE;
2061 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2063 return $loadObjectSuccess;
2068 // we are in event mode
2069 // make sure event exists and is valid
2070 $event = new CRM_Event_BAO_Event();
2071 $event->id
= $ids['event'];
2072 if ($ids['event'] &&
2075 throw new Exception("Could not find event: " . $ids['event']);
2078 $this->_relatedObjects
['event'] = &$event;
2080 $participant = new CRM_Event_BAO_Participant();
2081 $participant->id
= $ids['participant'];
2082 if ($ids['participant'] &&
2083 !$participant->find(TRUE)
2085 throw new Exception("Could not find participant: " . $ids['participant']);
2087 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2089 $this->_relatedObjects
['participant'] = &$participant;
2091 if (!$paymentProcessorID) {
2092 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2096 if ($paymentProcessorID) {
2097 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2098 $this->is_test ?
'test' : 'live'
2100 $ids['paymentProcessor'] = $paymentProcessorID;
2101 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2103 elseif ($required) {
2104 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2111 * Create array of message information - ie. return html version, txt version, to field
2113 * @param array $input
2114 * Incoming information.
2115 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2116 * just check presence of recur object but maintaining legacy approach
2119 * IDs of related objects.
2120 * @param array $values
2121 * Any values that may have already been compiled by calling process.
2122 * This is augmented by values 'gathered' by gatherMessageValues
2123 * @param bool $recur
2124 * @param bool $returnMessageText
2125 * Distinguishes between whether to send message or return.
2126 * message text. We are working towards this function ALWAYS returning message text & calling
2127 * function doing emails / pdfs with it
2133 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2134 if (empty($this->_relatedObjects
)) {
2135 $this->loadRelatedObjects($input, $ids);
2137 if (empty($this->_component
)) {
2138 $this->_component
= CRM_Utils_Array
::value('component', $input);
2141 //not really sure what params might be passed in but lets merge em into values
2142 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2143 $template = CRM_Core_Smarty
::singleton();
2144 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2145 //what does recur 'mean here - to do with payment processor return functionality but
2146 // what is the importance
2147 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2148 $paymentObject = &CRM_Core_Payment
::singleton(
2149 $this->is_test ?
'test' : 'live',
2150 $this->_relatedObjects
['paymentProcessor']
2153 $entityID = $entity = NULL;
2154 if (isset($ids['contribution'])) {
2155 $entity = 'contribution';
2156 $entityID = $ids['contribution'];
2158 if (!empty($ids['membership'])) {
2159 //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
2160 // 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
2161 // line having loaded an array
2162 $ids['membership'] = (array) $ids['membership'];
2163 $entity = 'membership';
2164 $entityID = $ids['membership'][0];
2167 $url = $paymentObject->subscriptionURL($entityID, $entity);
2168 $template->assign('cancelSubscriptionUrl', $url);
2170 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2171 $template->assign('updateSubscriptionBillingUrl', $url);
2173 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2174 $template->assign('updateSubscriptionUrl', $url);
2176 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2177 //direct mode showing billing block, so use directIPN for temporary
2178 $template->assign('contributeMode', 'directIPN');
2181 // todo remove strtolower - check consistency
2182 if (strtolower($this->_component
) == 'event') {
2183 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2184 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2188 $values['contribution_id'] = $this->id
;
2189 if (!empty($ids['related_contact'])) {
2190 $values['related_contact'] = $ids['related_contact'];
2191 if (isset($ids['onbehalf_dupe_alert'])) {
2192 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2194 $entityBlock = array(
2195 'contact_id' => $ids['contact'],
2196 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2197 'Home', 'id', 'name'
2200 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2201 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2204 if ($this->is_test
) {
2207 if (!empty($this->_relatedObjects
['membership'])) {
2208 foreach ($this->_relatedObjects
['membership'] as $membership) {
2209 if ($membership->id
) {
2210 $values['isMembership'] = TRUE;
2212 // need to set the membership values here
2213 $template->assign('membership_assign', 1);
2214 $template->assign('membership_name',
2215 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2217 $template->assign('mem_start_date', $membership->start_date
);
2218 $template->assign('mem_join_date', $membership->join_date
);
2219 $template->assign('mem_end_date', $membership->end_date
);
2220 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2221 $template->assign('mem_status', $membership_status);
2222 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2223 $template->assign('is_pay_later', 1);
2226 // if separate payment there are two contributions recorded and the
2227 // admin will need to send a receipt for each of them separately.
2228 // we dont link the two in the db (but can potentially infer it if needed)
2229 $template->assign('is_separate_payment', 0);
2231 if ($recur && $paymentObject) {
2232 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2233 $template->assign('cancelSubscriptionUrl', $url);
2234 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2235 $template->assign('updateSubscriptionBillingUrl', $url);
2236 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2237 $template->assign('updateSubscriptionUrl', $url);
2240 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2243 // otherwise if its about sending emails, continue sending without return, as we
2244 // don't want to exit the loop.
2249 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2255 * Gather values for contribution mail - this function has been created
2256 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2257 * Values related to the contribution in question are gathered
2259 * @param array $input
2260 * Input into function (probably from payment processor).
2261 * @param array $values
2263 * The set of ids related to the input.
2267 public function _gatherMessageValues($input, &$values, $ids = array()) {
2268 // set display address of contributor
2269 if ($this->address_id
) {
2270 $addressParams = array('id' => $this->address_id
);
2271 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2272 $addressDetails = array_values($addressDetails);
2273 $values['address'] = $addressDetails[0]['display'];
2275 if ($this->_component
== 'contribute') {
2276 if (isset($this->contribution_page_id
)) {
2277 CRM_Contribute_BAO_ContributionPage
::setValues(
2278 $this->contribution_page_id
,
2281 if ($this->contribution_page_id
) {
2282 // CRM-8254 - override default currency if applicable
2283 $config = CRM_Core_Config
::singleton();
2284 $config->defaultCurrency
= CRM_Utils_Array
::value(
2287 $config->defaultCurrency
2291 // no contribution page -probably back office
2293 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2294 $values['is_email_receipt'] = 1;
2295 $values['title'] = 'Contribution';
2297 // set lineItem for contribution
2299 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2300 if (!empty($lineItem)) {
2301 $itemId = key($lineItem);
2302 foreach ($lineItem as &$eachItem) {
2303 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2304 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2305 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2306 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2309 $values['lineItem'][0] = $lineItem;
2310 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2314 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2318 // if this is onbehalf of contribution then set related contact
2319 if (!empty($relatedContact['individual_id'])) {
2320 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2325 $eventParams = array(
2326 'id' => $this->_relatedObjects
['event']->id
,
2328 $values['event'] = array();
2330 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2332 //get location details
2333 $locationParams = array(
2334 'entity_id' => $this->_relatedObjects
['event']->id
,
2335 'entity_table' => 'civicrm_event',
2337 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2339 $ufJoinParams = array(
2340 'entity_table' => 'civicrm_event',
2341 'entity_id' => $ids['event'],
2342 'module' => 'CiviEvent',
2345 list($custom_pre_id,
2347 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2349 $values['custom_pre_id'] = $custom_pre_id;
2350 $values['custom_post_id'] = $custom_post_ids;
2352 // set lineItem for event contribution
2354 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2355 if (!empty($participantIds)) {
2356 foreach ($participantIds as $pIDs) {
2357 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2358 if (!CRM_Utils_System
::isNull($lineItem)) {
2359 $values['lineItem'][] = $lineItem;
2370 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2371 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2372 * Note we send directly from this function in some cases because it is only partly refactored
2373 * Don't call this function directly as the signature will change
2377 * @param CRM_Core_SMARTY $template
2378 * @param bool $recur
2379 * @param bool $returnMessageText
2383 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2384 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2385 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2386 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2387 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2388 $template->assign('useForMember', TRUE);
2390 //assign honor information to receipt message
2391 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2393 if (isset($softRecord['soft_credit'])) {
2394 //if id of contribution page is present
2395 if (!empty($values['id'])) {
2396 $values['honor'] = array(
2397 'honor_profile_values' => array(),
2398 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2399 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2401 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2403 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2404 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2407 //offline contribution
2408 $softCreditTypes = $softCredits = array();
2409 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2410 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2411 $softCredits[$key] = array(
2412 'Name' => $softCredit['contact_name'],
2413 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2416 $template->assign('softCreditTypes', $softCreditTypes);
2417 $template->assign('softCredits', $softCredits);
2421 $dao = new CRM_Contribute_DAO_ContributionProduct();
2422 $dao->contribution_id
= $this->id
;
2423 if ($dao->find(TRUE)) {
2424 $premiumId = $dao->product_id
;
2425 $template->assign('option', $dao->product_option
);
2427 $productDAO = new CRM_Contribute_DAO_Product();
2428 $productDAO->id
= $premiumId;
2429 $productDAO->find(TRUE);
2430 $template->assign('selectPremium', TRUE);
2431 $template->assign('product_name', $productDAO->name
);
2432 $template->assign('price', $productDAO->price
);
2433 $template->assign('sku', $productDAO->sku
);
2435 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2436 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2437 if (empty($amount) && isset($this->total_amount
)) {
2438 $amount = $this->total_amount
;
2440 $template->assign('amount', $amount);
2441 // add the new contribution values
2442 if (strtolower($this->_component
) == 'contribute') {
2444 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2445 $softDAO->contribution_id
= $this->id
;
2446 if ($softDAO->find(TRUE)) {
2447 $template->assign('pcpBlock', TRUE);
2448 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2449 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2450 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2452 //assign the pcp page title for email subject
2453 $pcpDAO = new CRM_PCP_DAO_PCP();
2454 $pcpDAO->id
= $softDAO->pcp_id
;
2455 if ($pcpDAO->find(TRUE)) {
2456 $template->assign('title', $pcpDAO->title
);
2461 if ($this->financial_type_id
) {
2462 $values['financial_type_id'] = $this->financial_type_id
;
2466 $template->assign('trxn_id', $this->trxn_id
);
2467 $template->assign('receive_date',
2468 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2470 $template->assign('contributeMode', 'notify');
2471 $template->assign('action', $this->is_test ?
1024 : 1);
2472 $template->assign('receipt_text',
2473 CRM_Utils_Array
::value('receipt_text',
2477 $template->assign('is_monetary', 1);
2478 $template->assign('is_recur', (bool) $recur);
2479 $template->assign('currency', $this->currency
);
2480 $template->assign('address', CRM_Utils_Address
::format($input));
2481 if ($this->_component
== 'event') {
2482 $template->assign('title', $values['event']['title']);
2483 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2484 $viewRoles = array();
2485 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2486 $viewRoles[] = $participantRoles[$v];
2488 $values['event']['participant_role'] = implode(', ', $viewRoles);
2489 $template->assign('event', $values['event']);
2490 $template->assign('location', $values['location']);
2491 $template->assign('customPre', $values['custom_pre_id']);
2492 $template->assign('customPost', $values['custom_post_id']);
2495 if ($this->_relatedObjects
['participant']->is_test
) {
2499 $values['params'] = array();
2500 //to get email of primary participant.
2501 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2502 $primaryAmount[] = array(
2503 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2504 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2506 //build an array of cId/pId of participants
2507 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2508 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2509 //send receipt to additional participant if exists
2510 if (count($additionalIDs)) {
2511 $template->assign('isPrimary', 0);
2512 $template->assign('customProfile', NULL);
2513 //set additionalParticipant true
2514 $values['params']['additionalParticipant'] = TRUE;
2515 foreach ($additionalIDs as $pId => $cId) {
2517 //to change the status pending to completed
2518 $additional = new CRM_Event_DAO_Participant();
2519 $additional->id
= $pId;
2520 $additional->contact_id
= $cId;
2521 $additional->find(TRUE);
2522 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2523 $additional->status_id
= 1;
2524 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2525 //if additional participant dont have email
2527 if (!$additionalParticipantInfo) {
2528 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2530 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2531 $primaryAmount[] = array(
2532 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2533 'amount' => $additional->fee_amount
,
2535 $additional->save();
2536 $additional->free();
2537 $template->assign('amount', $amount);
2538 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2542 //build an array of custom profile and assigning it to template
2543 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2545 if (count($customProfile)) {
2546 $template->assign('customProfile', $customProfile);
2549 // for primary contact
2550 $values['params']['additionalParticipant'] = FALSE;
2551 $template->assign('isPrimary', 1);
2552 $template->assign('amount', $primaryAmount);
2553 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2554 if ($this->payment_instrument_id
) {
2555 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2556 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2558 // carry paylater, since we did not created billing,
2559 // so need to pull email from primary location, CRM-4395
2560 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2566 * Check whether payment processor supports
2567 * cancellation of contribution subscription
2569 * @param int $contributionId
2572 * @param bool $isNotCancelled
2576 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2577 $cacheKeyString = "$contributionId";
2578 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2580 static $supportsCancel = array();
2582 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2583 $supportsCancel[$cacheKeyString] = FALSE;
2584 $isCancelled = FALSE;
2586 if ($isNotCancelled) {
2587 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2590 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2591 if (!empty($paymentObject)) {
2592 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2595 return $supportsCancel[$cacheKeyString];
2599 * Check whether subscription is already cancelled
2601 * @param int $contributionId
2605 * contribution status
2607 public static function isSubscriptionCancelled($contributionId) {
2609 SELECT cr.contribution_status_id
2610 FROM civicrm_contribution_recur cr
2611 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2612 WHERE con.id = %1 LIMIT 1";
2613 $params = array(1 => array($contributionId, 'Integer'));
2614 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2615 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2616 if ($status == 'Cancelled') {
2623 * Create all financial accounts entry
2625 * @param array $params
2626 * Contribution object, line item array and params for trxn.
2629 * @param array $financialTrxnValues
2631 * @return null|object
2633 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2634 $skipRecords = $update = $return = $isRelatedId = FALSE;
2636 $additionalParticipantId = array();
2637 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2639 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2640 $entityId = $params['participant_id'];
2641 $entityTable = 'civicrm_participant';
2642 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2644 elseif (!empty($params['membership_id'])) {
2645 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2646 // are created off one contribution should be handled elsewhere
2647 $entityId = $params['membership_id'];
2648 $entityTable = 'civicrm_membership';
2651 $entityId = $params['contribution']->id
;
2652 $entityTable = 'civicrm_contribution';
2655 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2656 $isRelatedId = TRUE;
2659 $entityID[] = $entityId;
2660 if (!empty($additionalParticipantId)) {
2661 $entityID +
= $additionalParticipantId;
2663 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2664 if (empty($params['prevContribution'])) {
2671 $statusId = $params['contribution']->contribution_status_id
;
2672 // CRM-13964 partial payment
2673 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2674 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2676 $partialAmtPay = $params['partial_amount_pay'];
2677 $partialAmtTotal = $params['partial_payment_total'];
2679 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2680 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2681 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2682 $params['total_amount'] = $partialAmtPay;
2684 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2685 if (empty($balanceTrxnInfo['trxn_id'])) {
2686 // create new balance transaction record
2687 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2688 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2690 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2691 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2692 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2693 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2694 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2695 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2696 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2697 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2698 $balanceTrxnParams['status_id'] = $statusId;
2699 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2700 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2701 if (!empty($params['payment_processor'])) {
2702 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2704 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2708 // build line item array if its not set in $params
2709 if (empty($params['line_item']) ||
$additionalParticipantId) {
2710 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2713 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2714 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2716 $skipRecords = TRUE;
2717 $pendingStatus = array(
2718 array_search('Pending', $contributionStatuses),
2719 array_search('In Progress', $contributionStatuses),
2721 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2722 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2723 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2725 elseif (!empty($params['payment_processor'])) {
2726 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2728 elseif (!empty($params['payment_instrument_id'])) {
2729 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2732 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2733 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2734 $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);
2737 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2738 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2739 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2742 //build financial transaction params
2743 $trxnParams = array(
2744 'contribution_id' => $params['contribution']->id
,
2745 'to_financial_account_id' => $params['to_financial_account_id'],
2746 'trxn_date' => date('YmdHis'),
2747 'total_amount' => $totalAmount,
2748 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2749 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2750 'currency' => $params['contribution']->currency
,
2751 'trxn_id' => $params['contribution']->trxn_id
,
2752 'status_id' => $statusId,
2753 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2754 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2757 if (!empty($params['payment_processor'])) {
2758 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2761 if (isset($fromFinancialAccountId)) {
2762 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2765 // consider external values passed for recording transaction entry
2766 if (!empty($financialTrxnValues)) {
2767 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2770 $params['trxnParams'] = $trxnParams;
2772 if (!empty($params['prevContribution'])) {
2773 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2774 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2775 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2776 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2777 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2780 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2781 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2782 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2784 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2785 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2788 //if financial type is changed
2789 if (!empty($params['financial_type_id']) &&
2790 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2792 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2793 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2794 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2795 if ($oldFinancialAccount != $newFinancialAccount) {
2796 $params['total_amount'] = 0;
2797 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2798 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2799 $params['prevContribution']->financial_type_id
, $relationTypeId);
2802 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2803 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2804 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2807 self
::updateFinancialAccounts($params, 'changeFinancialType');
2808 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2809 $params['financial_account_id'] = $newFinancialAccount;
2810 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2811 self
::updateFinancialAccounts($params);
2812 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2816 //Update contribution status
2817 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2818 if (!empty($params['contribution_status_id']) &&
2819 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2821 //Update Financial Records
2822 self
::updateFinancialAccounts($params, 'changedStatus');
2825 // change Payment Instrument for a Completed contribution
2826 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2827 // instrument is null and now new payment instrument is added along with the payment
2828 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2829 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2830 if (array_key_exists('payment_instrument_id', $params)) {
2831 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2832 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2833 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2835 //check if status is changed from Pending to Completed
2836 // do not update payment instrument changes for Pending to Completed
2837 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2838 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2840 // for all other statuses create new financial records
2841 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2842 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2843 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2846 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2847 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2848 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2850 // for any other payment instrument changes create new financial records
2851 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2852 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2853 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2855 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2856 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2858 // another special case when check number is changed, create new financial records
2859 // create financial trxn with negative amount
2860 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2861 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2862 // create financial trxn with positive amount
2863 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2864 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2865 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2869 //if Change contribution amount
2870 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2871 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2872 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2873 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2874 if (isset($totalAmount) &&
2875 $totalAmount != $params['prevContribution']->total_amount
2877 //Update Financial Records
2878 $params['trxnParams']['from_financial_account_id'] = NULL;
2879 self
::updateFinancialAccounts($params, 'changedAmount');
2884 // records finanical trxn and entity financial trxn
2885 // also make it available as return value
2886 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2887 $params['entity_id'] = $financialTxn->id
;
2890 // record line items and finacial items
2891 if (empty($params['skipLineItem'])) {
2892 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2895 // create batch entry if batch_id is passed
2896 if (!empty($params['batch_id'])) {
2897 $entityParams = array(
2898 'batch_id' => $params['batch_id'],
2899 'entity_table' => 'civicrm_financial_trxn',
2900 'entity_id' => $financialTxn->id
,
2902 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2905 // when a fee is charged
2906 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2907 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2910 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2911 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2913 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2914 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2915 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2917 unset($params['line_item']);
2923 * Update all financial accounts entry
2925 * @param array $params
2926 * Contribution object, line item array and params for trxn.
2928 * @param string $context
2931 * @param null $skipTrxn
2934 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2935 $itemAmount = $trxnID = NULL;
2936 //get all the statuses
2937 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2938 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2939 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2940 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2941 && $context == 'changePaymentInstrument'
2945 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2946 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2948 if ($context == 'changedStatus') {
2949 //get all the statuses
2950 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2952 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2953 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2954 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2956 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2958 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2959 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2961 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2962 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2963 $params['trxnParams']['to_financial_account_id'] = NULL;
2964 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2966 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2967 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2968 $financialTypeID, $relationTypeId);
2970 $itemAmount = $params['trxnParams']['total_amount'];
2972 elseif ($context == 'changePaymentInstrument') {
2973 if ($params['trxnParams']['total_amount'] < 0) {
2974 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2975 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2976 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2977 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2981 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2982 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2985 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2986 $params['entity_id'] = $trxn->id
;
2988 if ($context == 'changedStatus') {
2989 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2990 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2991 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
2993 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2994 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2996 $entityParams = array(
2997 'entity_table' => 'civicrm_financial_item',
2998 'financial_trxn_id' => $trxn->id
,
3000 if (empty($params['line_item'])) {
3002 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3003 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3004 // & this can be removed
3007 foreach ($params['line_item'] as $fieldId => $fields) {
3008 foreach ($fields as $fieldValueId => $fieldValues) {
3010 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3011 2 => array($fieldValues['id'], 'Integer'),
3013 CRM_Core_DAO
::executeQuery($query, $fparams);
3015 1 => array($fieldValues['id'], 'Integer'),
3017 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3018 while ($financialItem->fetch()) {
3019 $entityParams['entity_id'] = $financialItem->id
;
3020 $entityParams['amount'] = $financialItem->amount
;
3021 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3028 if ($context != 'changePaymentInstrument') {
3029 $itemParams['entity_table'] = 'civicrm_line_item';
3030 $trxnIds['id'] = $params['entity_id'];
3031 foreach ($params['line_item'] as $fieldId => $fields) {
3032 foreach ($fields as $fieldValueId => $fieldValues) {
3033 $prevParams['entity_id'] = $fieldValues['id'];
3034 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3036 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3037 if ($params['contribution']->receive_date
) {
3038 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3041 $financialAccount = $prevfinancialItem->financial_account_id
;
3042 if (!empty($params['financial_account_id'])) {
3043 $financialAccount = $params['financial_account_id'];
3046 $currency = $params['prevContribution']->currency
;
3047 if ($params['contribution']->currency
) {
3048 $currency = $params['contribution']->currency
;
3051 if (!empty($params['is_quick_config'])) {
3052 $amount = $itemAmount;
3054 $amount = $params['total_amount'];
3058 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3059 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3063 $amount = $diff * $fieldValues['line_total'];
3066 $itemParams = array(
3067 'transaction_date' => $receiveDate,
3068 'contact_id' => $params['prevContribution']->contact_id
,
3069 'currency' => $currency,
3070 'amount' => $amount,
3071 'description' => $prevfinancialItem->description
,
3072 'status_id' => $prevfinancialItem->status_id
,
3073 'financial_account_id' => $financialAccount,
3074 'entity_table' => 'civicrm_line_item',
3075 'entity_id' => $fieldValues['id'],
3077 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3079 if ($fieldValues['tax_amount']) {
3080 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3081 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3082 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3083 $itemParams['description'] = $taxTerm;
3084 if ($fieldValues['financial_type_id']) {
3085 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3087 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3095 * Check status validation on update of a contribution
3097 * @param array $values
3098 * Previous form values before submit.
3100 * @param array $fields
3101 * The input form values.
3103 * @param array $errors
3108 public static function checkStatusValidation($values, &$fields, &$errors) {
3109 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3110 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3111 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3115 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3116 $checkStatus = array(
3117 'Cancelled' => array('Completed', 'Refunded'),
3118 'Completed' => array('Cancelled', 'Refunded'),
3119 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3120 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3121 'Refunded' => array('Cancelled', 'Completed'),
3124 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3125 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3126 1 => $contributionStatuses[$values['contribution_status_id']],
3127 2 => $contributionStatuses[$fields['contribution_status_id']],
3133 * Delete contribution of contact
3137 * @param int $contactId
3141 public static function deleteContactContribution($contactId) {
3142 $contribution = new CRM_Contribute_DAO_Contribution();
3143 $contribution->contact_id
= $contactId;
3144 $contribution->find();
3145 while ($contribution->fetch()) {
3146 self
::deleteContribution($contribution->id
);
3151 * Get options for a given contribution field.
3152 * @see CRM_Core_DAO::buildOptions
3154 * @param string $fieldName
3155 * @param string $context
3156 * @see CRM_Core_DAO::buildOptionsContext.
3157 * @param array $props
3158 * whatever is known about this dao object.
3160 * @return Array|bool
3162 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3163 $className = __CLASS__
;
3165 switch ($fieldName) {
3166 // This field is not part of this object but the api supports it
3167 case 'payment_processor':
3168 $className = 'CRM_Contribute_BAO_ContributionPage';
3169 // Filter results by contribution page
3170 if (!empty($props['contribution_page_id'])) {
3171 $page = civicrm_api('contribution_page', 'getsingle', array(
3173 'id' => ($props['contribution_page_id']),
3175 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3176 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3180 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3181 case 'honor_type_id':
3182 $className = 'CRM_Contribute_BAO_ContributionSoft';
3183 $fieldName = 'soft_credit_type_id';
3184 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3187 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3191 * Validate financial type
3195 * @param int $financialTypeId
3196 * Financial Type id.
3198 * @param string $relationName
3200 * @return array|bool
3202 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3203 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3204 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3206 if (!$financialAccount) {
3207 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3214 * Function to record additional payment for partial and refund contributions
3216 * @param int $contributionId
3217 * is the invoice contribution id (got created after processing participant payment).
3218 * @param array $trxnsData
3219 * to take user provided input of transaction details.
3220 * @param string $paymentType
3221 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3222 * @param int $participantId
3224 * @return null|object
3226 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3227 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3228 $getInfoOf['id'] = $contributionId;
3229 $defaults = array();
3230 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3232 if ($paymentType == 'owed') {
3233 // build params for recording financial trxn entry
3234 $params['contribution'] = $contributionDAO;
3235 $params = array_merge($defaults, $params);
3236 $params['skipLineItem'] = TRUE;
3237 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3238 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3239 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3242 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3243 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3244 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3246 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3247 if (!empty($trxnId)) {
3248 $trxnId = $trxnId['trxn_id'];
3250 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3251 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3254 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3255 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3256 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3260 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3261 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3262 FROM civicrm_financial_trxn ft
3263 LEFT JOIN civicrm_entity_financial_trxn eft
3264 ON (ft.id = eft.financial_trxn_id)
3265 WHERE eft.entity_table = 'civicrm_contribution'
3266 AND eft.entity_id = {$contributionId}
3267 AND ft.to_financial_account_id != {$toFinancialAccount}
3268 AND ft.status_id = {$statusId}
3270 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3273 if ($contributionDAO->total_amount
== $sumOfPayments) {
3274 // update contribution status and
3275 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3276 $contributionDAO->contribution_status_id
= $statusId;
3277 $contributionDAO->cancel_date
= 'null';
3278 $contributionDAO->cancel_reason
= NULL;
3279 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3280 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3281 $contributionDAO->save();
3283 //Change status of financial record too
3284 $financialTrxn->status_id
= $statusId;
3285 $financialTrxn->save();
3287 // note : not using the self::add method,
3288 // the reason because it performs 'status change' related code execution for financial records
3289 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3290 // are coded below i.e. just updating financial_item status to 'Paid'
3292 if ($participantId) {
3293 // update participant status
3294 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3295 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3296 foreach ($ids as $val) {
3297 $participantUpdate['id'] = $val;
3298 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3299 CRM_Event_BAO_Participant
::add($participantUpdate);
3303 // update financial item statuses
3304 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3305 $paidStatus = array_search('Paid', $financialItemStatus);
3307 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3308 $sqlFinancialItemUpdate = "
3309 UPDATE civicrm_financial_item fi
3310 LEFT JOIN civicrm_entity_financial_trxn eft
3311 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3312 SET status_id = {$paidStatus}
3313 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3315 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3318 elseif ($paymentType == 'refund') {
3319 // build params for recording financial trxn entry
3320 $params['contribution'] = $contributionDAO;
3321 $params = array_merge($defaults, $params);
3322 $params['skipLineItem'] = TRUE;
3323 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3324 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3326 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3327 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3328 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3330 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3332 // note : not using the self::add method,
3333 // the reason because it performs 'status change' related code execution for financial records
3334 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3335 // are coded below i.e. just updating financial_item status to 'Paid'
3336 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3338 // add financial item entry
3339 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3340 $getLine['entity_id'] = $contributionDAO->id
;
3341 $getLine['entity_table'] = 'civicrm_contribution';
3342 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3343 if (!empty($lineItemId->id
)) {
3344 $addFinancialEntry = array(
3345 'transaction_date' => $financialTrxn->trxn_date
,
3346 'contact_id' => $contributionDAO->contact_id
,
3347 'amount' => $financialTrxn->total_amount
,
3348 'status_id' => array_search('Paid', $financialItemStatus),
3349 'entity_id' => $lineItemId->id
,
3350 'entity_table' => 'civicrm_line_item',
3352 $trxnIds['id'] = $financialTrxn->id
;
3353 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3355 if ($participantId) {
3356 // update participant status
3357 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3358 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3359 foreach ($ids as $val) {
3360 $participantUpdate['id'] = $val;
3361 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3362 CRM_Event_BAO_Participant
::add($participantUpdate);
3367 // activity creation
3368 if (!empty($financialTrxn)) {
3369 if ($participantId) {
3370 $inputParams['id'] = $participantId;
3373 $component = 'event';
3374 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3375 $entityObj = $entityObj[$participantId];
3377 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3379 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3381 return $financialTrxn;
3387 * @param $activityType
3389 * @param int $contributionId
3391 * @throws CRM_Core_Exception
3393 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3394 if ($component == 'event') {
3395 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3396 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3397 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3398 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3399 $targetCid = $entityObj->contact_id
;
3400 // source record id would be the contribution id
3401 $srcRecId = $contributionId;
3405 $activityParams = array(
3406 'source_contact_id' => $targetCid,
3407 'source_record_id' => $srcRecId,
3408 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3412 'subject' => $subject,
3413 'activity_date_time' => $date,
3414 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3418 'skipRecentView' => TRUE,
3421 // create activity with target contacts
3422 $session = CRM_Core_Session
::singleton();
3423 $id = $session->get('userID');
3425 $activityParams['source_contact_id'] = $id;
3426 $activityParams['target_contact_id'][] = $targetCid;
3428 CRM_Activity_BAO_Activity
::create($activityParams);
3432 * Get list of payments displayed by Contribute_Page_PaymentInfo
3436 * @param bool $getTrxnInfo
3437 * @param bool $usingLineTotal
3441 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3442 if ($component == 'event') {
3443 $entity = 'participant';
3444 $entityTable = 'civicrm_participant';
3445 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3447 if (!$contributionId) {
3448 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3449 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3450 $id = $primaryParticipantId;
3452 if (!$contributionId) {
3457 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3458 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3464 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3465 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3468 if (empty($total) ||
$usingLineTotal) {
3469 // for additional participants
3470 if ($entityTable == 'civicrm_participant') {
3471 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3473 foreach ($ids as $val) {
3474 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3478 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3482 $baseTrxnId = $total['trxn_id'];
3483 $total = $total['total_amount'];
3486 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3487 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3489 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3490 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3491 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3493 if ($paymentBalance == 0 && $contributionIsPayLater) {
3494 $paymentBalance = $total;
3497 $info['total'] = $total;
3498 $info['paid'] = $total - $paymentBalance;
3499 $info['balance'] = $paymentBalance;
3501 $info['component'] = $component;
3502 $info['payLater'] = $contributionIsPayLater;
3504 if ($getTrxnInfo && $baseTrxnId) {
3505 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3507 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3508 FROM civicrm_contribution con
3509 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3510 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3511 WHERE con.id = {$contributionId}
3514 // conditioned WHERE clause
3516 // if balance trxn exists don't include details of it in transaction info
3517 $sql .= " AND ft.id != {$baseTrxnId} ";
3519 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3521 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3522 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3523 while ($resultDAO->fetch()) {
3524 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3525 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3527 'total_amount' => $resultDAO->total_amount
,
3528 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3529 'payment_instrument' => $paidByLabel,
3530 'receive_date' => $resultDAO->trxn_date
,
3531 'trxn_id' => $resultDAO->trxn_id
,
3532 'status' => $statuses[$resultDAO->status_id
],
3534 if ($paidByName == 'Check') {
3535 $val['check_number'] = $resultDAO->check_number
;
3539 $info['transaction'] = $rows;
3545 * Get financial account id has 'Sales Tax Account is'
3546 * account relationship with financial type
3548 * @param int $financialTypeId
3550 * @return FinancialAccountId
3552 public static function getFinancialAccountId($financialTypeId) {
3553 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3554 $searchParams = array(
3555 'entity_table' => 'civicrm_financial_type',
3556 'entity_id' => $financialTypeId,
3557 'account_relationship' => $accountRel,
3560 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3562 return CRM_Utils_Array
::value('financial_account_id', $result);
3565 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3566 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3568 // Update contribution
3569 if (!empty($params['id'])) {
3570 $id = $params['id'];
3571 $values = $ids = array();
3572 $contrbutionParams = array('id' => $id);
3573 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3575 // To assign pervious finantial type on update of contribution
3576 if (!isset($params['financial_type_id'])) {
3577 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3579 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3580 // Assisn tax Amount on update of contrbution
3581 if (!empty($prevContributionValue->tax_amount
)) {
3582 $params['tax_amount'] = 'null';
3583 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3584 foreach ($params['line_item'] as $setID => $priceField) {
3585 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3586 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3593 // New Contrbution and update of contribution with tax rate financial type
3594 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3595 empty($params['skipLineItem']) && !$isLineItem
3597 $taxRateParams = $taxRates[$params['financial_type_id']];
3598 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3599 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3601 // Get Line Item on update of contribution
3602 if (isset($params['id'])) {
3603 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3606 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3608 foreach ($params['line_item'] as $setID => $priceField) {
3609 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3610 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3613 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3615 elseif (isset($params['api.line_item.create'])) {
3616 // Update total amount of contribution using lineItem
3617 $taxAmountArray = array();
3618 foreach ($params['api.line_item.create'] as $key => $value) {
3619 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3620 $taxRate = $taxRates[$value['financial_type_id']];
3621 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3622 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3625 $params['tax_amount'] = array_sum($taxAmountArray);
3626 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3629 // update line item of contrbution
3630 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3631 $taxRate = $taxRates[$params['financial_type_id']];
3632 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3633 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);