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
43 static $_importableFields = NULL;
46 * Static field for all the contribution information that we can potentially export
51 static $_exportableFields = NULL;
54 * Field for all the objects related to this contribution
55 * @var array of objects (e.g membership object, participant object)
57 public $_relatedObjects = array();
60 * Field for the component - either 'event' (participant) or 'contribute'
61 * (any item related to a contribution page e.g. membership, pledge, contribution)
62 * This is used for composing messages because they have dependency on the
63 * contribution_page or event page - although over time we may eliminate that
65 * @var string component or event
67 public $_component = NULL;
75 * @return \CRM_Contribute_DAO_Contribution
80 public function __construct() {
81 parent
::__construct();
85 * Takes an associative array and creates a contribution object
87 * the function extract all the params it needs to initialize the create a
88 * contribution object. the params array could contain additional unused name/value
91 * @param array $params
92 * (reference ) an assoc array of name/value pairs.
94 * The array that holds all the db ids.
96 * @return CRM_Contribute_BAO_Contribution object
99 public static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
105 $duplicates = array();
106 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
107 $error = CRM_Core_Error
::singleton();
108 $d = implode(', ', $duplicates);
109 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
112 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
117 // first clean up all the money fields
118 $moneyFields = array(
122 'non_deductible_amount',
125 //if priceset is used, no need to cleanup money
126 if (!empty($params['skipCleanMoney'])) {
127 unset($moneyFields[0]);
130 foreach ($moneyFields as $field) {
131 if (isset($params[$field])) {
132 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
136 //set defaults in create mode
137 if (!$contributionID) {
138 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
139 self
::calculateMissingAmountParams($params);
142 if (!empty($params['payment_instrument_id'])) {
143 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
144 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
145 $params['check_number'] = 'null';
149 $setPrevContribution = TRUE;
150 // CRM-13964 partial payment
151 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
152 $partialAmtTotal = $params['partial_payment_total'];
153 $partialAmtPay = $params['partial_amount_pay'];
154 $params['total_amount'] = $partialAmtTotal;
155 if ($partialAmtPay < $partialAmtTotal) {
156 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
157 $params['is_pay_later'] = 0;
158 $setPrevContribution = FALSE;
162 if ($contributionID) {
163 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
166 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
168 $contribution = new CRM_Contribute_BAO_Contribution();
169 $contribution->copyValues($params);
171 $contribution->id
= $contributionID;
173 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
174 $config = CRM_Core_Config
::singleton();
175 $contribution->currency
= $config->defaultCurrency
;
178 if ($contributionID && $setPrevContribution) {
179 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
182 $result = $contribution->save();
184 // Add financial_trxn details as part of fix for CRM-4724
185 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
186 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
188 //add Account details
189 $params['contribution'] = $contribution;
190 self
::recordFinancialAccounts($params);
192 // reset the group contact cache for this group
193 CRM_Contact_BAO_GroupContactCache
::remove();
195 if ($contributionID) {
196 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
199 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
206 * Get defaults for new entity
209 public static function getDefaults() {
211 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
212 FALSE, FALSE, FALSE, 'AND is_default = 1')
214 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
219 * Given the list of params in the params array, fetch the object
220 * and store the values in the values array
222 * @param array $params
223 * Input parameters to find object.
224 * @param array $values
225 * Output values of the object.
227 * The array that holds all the db ids.
229 * @return CRM_Contribute_BAO_Contribution|null the found object or null
232 public static function &getValues($params, &$values, &$ids) {
233 if (empty($params)) {
236 $contribution = new CRM_Contribute_BAO_Contribution();
238 $contribution->copyValues($params);
240 if ($contribution->find(TRUE)) {
241 $ids['contribution'] = $contribution->id
;
243 CRM_Core_DAO
::storeValues($contribution, $values);
245 return $contribution;
247 $null = NULL; // return by reference
252 * @param array $params
256 public static function calculateMissingAmountParams(&$params) {
257 if (!isset($params['fee_amount'])) {
258 if (isset($params['total_amount']) && isset($params['net_amount'])) {
259 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
262 $params['fee_amount'] = 0;
265 if (!isset($params['net_amount'])) {
266 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
271 * Get the number of terms for this contribution for a given membership type
272 * based on querying the line item table and relevant price field values
273 * Note that any one contribution should only be able to have one line item relating to a particular membership
276 * @param int $membershipTypeID
278 * @param int $contributionID
282 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
283 $numTerms = CRM_Core_DAO
::singleValueQuery("
284 SELECT membership_num_terms FROM civicrm_line_item li
285 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
286 WHERE contribution_id = %1 AND membership_type_id = %2",
287 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
289 // default of 1 is precautionary
290 return empty($numTerms) ?
1 : $numTerms;
294 * Takes an associative array and creates a contribution object
296 * @param array $params
297 * (reference ) an assoc array of name/value pairs.
299 * The array that holds all the db ids.
301 * @return CRM_Contribute_BAO_Contribution object
304 public static function create(&$params, $ids = array()) {
305 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
306 foreach ($dateFields as $df) {
307 if (isset($params[$df])) {
308 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
312 $transaction = new CRM_Core_Transaction();
314 $contribution = self
::add($params, $ids);
316 if (is_a($contribution, 'CRM_Core_Error')) {
317 $transaction->rollback();
318 return $contribution;
321 $params['contribution_id'] = $contribution->id
;
323 if (!empty($params['custom']) &&
324 is_array($params['custom'])
326 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
329 $session = CRM_Core_Session
::singleton();
331 if (!empty($params['note'])) {
333 'entity_table' => 'civicrm_contribution',
334 'note' => $params['note'],
335 'entity_id' => $contribution->id
,
336 'contact_id' => $session->get('userID'),
337 'modified_date' => date('Ymd'),
339 if (!$noteParams['contact_id']) {
340 $noteParams['contact_id'] = $params['contact_id'];
342 CRM_Core_BAO_Note
::add($noteParams);
345 // make entry in batch entity batch table
346 if (!empty($params['batch_id'])) {
347 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
348 $titleFields = array(
354 $retrieveRequired = 0;
355 foreach ($titleFields as $titleField) {
356 if (!isset($contribution->$titleField)) {
357 $retrieveRequired = 1;
361 if ($retrieveRequired == 1) {
362 $contribution->find(TRUE);
366 // check if activity record exist for this contribution, if
368 $activity = new CRM_Activity_DAO_Activity();
369 $activity->source_record_id
= $contribution->id
;
370 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
374 if (!$activity->find(TRUE)) {
375 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
378 // CRM-13237 : if activity record found, update it with campaign id of contribution
379 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
382 // Handle soft credit and / or link to personal campaign page
383 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
385 //Delete PCP against this contribution and create new on submitted PCP information
386 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
388 $deleteParams = array('id' => $pcpId);
389 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
391 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
392 $softParams = array();
393 $softParams['contribution_id'] = $contribution->id
;
394 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
395 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
396 $pcp['pcp_made_through_id'], 'contact_id'
398 $softParams['currency'] = $contribution->currency
;
399 $softParams['amount'] = $contribution->total_amount
;
400 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
401 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
402 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
403 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
404 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
406 if (isset($params['soft_credit'])) {
407 $softParams = $params['soft_credit'];
409 if (!empty($softIDs)) {
410 foreach ($softIDs as $softID) {
411 if (!in_array($softID, $params['soft_credit_ids'])) {
412 $deleteParams = array('id' => $softID);
413 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
418 foreach ($softParams as $softParam) {
419 $softParam['contribution_id'] = $contribution->id
;
420 $softParam['currency'] = $contribution->currency
;
421 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
422 if (empty($softParam['amount'])) {
423 $softParam['amount'] = $contribution->total_amount
;
425 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
429 $transaction->commit();
431 // do not add to recent items for import, CRM-4399
432 if (empty($params['skipRecentView'])) {
433 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
434 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
436 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
437 $titleFields = array(
443 $retrieveRequired = 0;
444 foreach ($titleFields as $titleField) {
445 if (!isset($contribution->$titleField)) {
446 $retrieveRequired = 1;
450 if ($retrieveRequired == 1) {
451 $contribution->find(TRUE);
453 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
454 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
456 $recentOther = array();
457 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
458 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
459 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
463 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
464 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
465 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
469 // add the recently created Contribution
470 CRM_Utils_Recent
::add($title,
474 $contribution->contact_id
,
480 return $contribution;
484 * Get the values for pseudoconstants for name->value and reverse.
486 * @param array $defaults
487 * (reference) the default values, some of which need to be resolved.
488 * @param bool $reverse
489 * True if we want to resolve the values in the reverse direction (value -> name).
494 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
495 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
496 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
497 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
498 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
502 * This function is used to convert associative array names to values
505 * This function is used by both the web form layer and the api. Note that
506 * the api needs the name => value conversion, also the view layer typically
507 * requires value => name conversion
509 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
510 $id = $property . '_id';
512 $src = $reverse ?
$property : $id;
513 $dst = $reverse ?
$id : $property;
515 if (!array_key_exists($src, $defaults)) {
519 $look = $reverse ?
array_flip($lookup) : $lookup;
521 if (is_array($look)) {
522 if (!array_key_exists($defaults[$src], $look)) {
526 $defaults[$dst] = $look[$defaults[$src]];
531 * Takes a bunch of params that are needed to match certain criteria and
532 * retrieves the relevant objects. We'll tweak this function to be more
533 * full featured over a period of time. This is the inverse function of
534 * create. It also stores all the retrieved values in the default array
536 * @param array $params
537 * (reference ) an assoc array of name/value pairs.
538 * @param array $defaults
539 * (reference ) an assoc array to hold the name / value pairs.
540 * in a hierarchical manner
542 * (reference) the array that holds all the db ids.
544 * @return CRM_Contribute_BAO_Contribution object
547 public static function retrieve(&$params, &$defaults, &$ids) {
548 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
549 return $contribution;
553 * Combine all the importable fields from the lower levels object
555 * The ordering is important, since currently we do not have a weight
556 * scheme. Adding weight is super important and should be done in the
557 * next week or so, before this can be called complete.
559 * @param string $contactType
560 * @param bool $status
562 * @return array array of importable Fields
565 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
566 if (!self
::$_importableFields) {
567 if (!self
::$_importableFields) {
568 self
::$_importableFields = array();
572 $fields = array('' => array('title' => ts('- do not import -')));
575 $fields = array('' => array('title' => ts('- Contribution Fields -')));
578 $note = CRM_Core_DAO_Note
::import();
579 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
580 unset($tmpFields['option_value']);
581 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
582 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
584 // Using new Dedupe rule.
586 'contact_type' => $contactType,
587 'used' => 'Unsupervised',
589 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
590 $tmpContactField = array();
591 if (is_array($fieldsArray)) {
592 foreach ($fieldsArray as $value) {
593 //skip if there is no dupe rule
594 if ($value == 'none') {
597 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
602 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
603 $tmpContactField[trim($value)] = $contactFields[trim($value)];
605 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
608 $title = $tmpContactField[trim($value)]['title'];
610 $tmpContactField[trim($value)]['title'] = $title;
614 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
615 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
616 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
617 $fields = array_merge($fields, $tmpContactField);
618 $fields = array_merge($fields, $tmpFields);
619 $fields = array_merge($fields, $note);
620 $fields = array_merge($fields, $optionFields);
621 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
622 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
623 self
::$_importableFields = $fields;
625 return self
::$_importableFields;
631 public static function &exportableFields() {
632 if (!self
::$_exportableFields) {
633 if (!self
::$_exportableFields) {
634 self
::$_exportableFields = array();
637 $impFields = CRM_Contribute_DAO_Contribution
::export();
638 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
639 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
640 $typeField = CRM_Financial_DAO_FinancialType
::export();
641 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
642 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
643 $contributionStatus = array(
644 'contribution_status' => array(
645 'title' => ts('Contribution Status'),
646 'name' => 'contribution_status',
647 'data_type' => CRM_Utils_Type
::T_STRING
651 $contributionNote = array(
652 'contribution_note' =>
654 'title' => ts('Contribution Note'),
655 'name' => 'contribution_note',
656 'data_type' => CRM_Utils_Type
::T_TEXT
660 $contributionRecurId = array(
661 'contribution_recur_id' => array(
662 'title' => ts('Recurring Contributions ID'),
663 'name' => 'contribution_recur_id',
664 'where' => 'civicrm_contribution.contribution_recur_id',
665 'data_type' => CRM_Utils_Type
::T_INT
669 $extraFields = array(
670 'contribution_batch' => array(
671 'title' => ts('Batch Name')
675 $softCreditFields = array(
676 'contribution_soft_credit_name' => array(
677 'name' => 'contribution_soft_credit_name',
678 'title' => 'Soft Credit For',
679 'where' => 'civicrm_contact_d.display_name',
680 'data_type' => CRM_Utils_Type
::T_STRING
682 'contribution_soft_credit_amount' => array(
683 'name' => 'contribution_soft_credit_amount',
684 'title' => 'Soft Credit Amount',
685 'where' => 'civicrm_contribution_soft.amount',
686 'data_type' => CRM_Utils_Type
::T_MONEY
688 'contribution_soft_credit_type' => array(
689 'name' => 'contribution_soft_credit_type',
690 'title' => 'Soft Credit Type',
691 'where' => 'contribution_softcredit_type.label',
692 'data_type' => CRM_Utils_Type
::T_STRING
694 'contribution_soft_credit_contribution_id' => array(
695 'name' => 'contribution_soft_credit_contribution_id',
696 'title' => 'Soft Credit For Contribution ID',
697 'where' => 'civicrm_contribution_soft.contribution_id',
698 'data_type' => CRM_Utils_Type
::T_INT
702 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
703 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
704 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
707 self
::$_exportableFields = $fields;
710 return self
::$_exportableFields;
714 * @param null $status
715 * @param null $startDate
716 * @param null $endDate
720 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
724 $where[] = 'contribution_status_id = 1';
728 $where[] = 'contribution_status_id = 3';
733 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
736 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
739 $whereCond = implode(' AND ', $where);
742 SELECT sum( total_amount ) as total_amount,
743 count( civicrm_contribution.id ) as total_count,
745 FROM civicrm_contribution
746 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
748 AND ( is_test = 0 OR is_test IS NULL )
749 AND contact.is_deleted = 0
753 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
756 while ($dao->fetch()) {
757 $count +
= $dao->total_count
;
758 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
762 'amount' => implode(', ', $amount),
770 * Delete the indirect records associated with this contribution first
774 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
777 public static function deleteContribution($id) {
778 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
780 $transaction = new CRM_Core_Transaction();
783 //delete activity record
785 'source_record_id' => $id,
786 // activity type id for contribution
787 'activity_type_id' => 6,
790 CRM_Activity_BAO_Activity
::deleteActivity($params);
792 //delete billing address if exists for this contribution.
793 self
::deleteAddress($id);
795 //update pledge and pledge payment, CRM-3961
796 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
798 // remove entry from civicrm_price_set_entity, CRM-5095
799 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
800 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
802 // cleanup line items.
803 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
805 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
806 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
808 if ($participantId) {
809 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
812 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
816 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
817 $noteId = key($note);
819 CRM_Core_BAO_Note
::del($noteId, FALSE);
822 $dao = new CRM_Contribute_DAO_Contribution();
825 $results = $dao->delete();
827 $transaction->commit();
829 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
831 // delete the recently created Contribution
832 $contributionRecent = array(
834 'type' => 'Contribution',
836 CRM_Utils_Recent
::del($contributionRecent);
842 * Check if there is a contribution with the same trxn_id or invoice_id
844 * @param array $input
845 * An assoc array of name/value pairs.
846 * @param array $duplicates
847 * (reference ) store ids of duplicate contribs.
851 * @return boolean true if duplicate, false otherwise
854 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
856 $id = CRM_Utils_Array
::value('id', $input);
858 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
859 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
865 $clause[] = "trxn_id = %1";
866 $input[1] = array($trxn_id, 'String');
870 $clause[] = "invoice_id = %2";
871 $input[2] = array($invoice_id, 'String');
874 if (empty($clause)) {
878 $clause = implode(' OR ', $clause);
880 $clause = "( $clause ) AND id != %3";
881 $input[3] = array($id, 'Integer');
884 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
885 $dao = CRM_Core_DAO
::executeQuery($query, $input);
887 while ($dao->fetch()) {
888 $duplicates[] = $dao->id
;
895 * Takes an associative array and creates a contribution_product object
897 * the function extract all the params it needs to initialize the create a
898 * contribution_product object. the params array could contain additional unused name/value
901 * @param array $params
902 * (reference ) an assoc array of name/value pairs.
904 * @return CRM_Contribute_BAO_ContributionProduct object
907 public static function addPremium(&$params) {
908 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
909 $contributionProduct->copyValues($params);
910 return $contributionProduct->save();
914 * Get list of contribution fields for profile
915 * For now we only allow custom contribution fields to be in
918 * @param bool $addExtraFields
919 * True if special fields needs to be added.
921 * @return array the list of contribution fields
924 public static function getContributionFields($addExtraFields = TRUE) {
925 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
926 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
928 if ($addExtraFields) {
929 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
932 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
934 foreach ($contributionFields as $key => $var) {
935 if ($key == 'contribution_contact_id') {
938 elseif ($key == 'contribution_campaign_id') {
939 $var['title'] = ts('Campaign');
941 $fields[$key] = $var;
944 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
949 * Add extra fields specific to contribtion
953 public static function getSpecialContributionFields() {
954 $extraFields = array(
955 'contribution_soft_credit_name' => array(
956 'name' => 'contribution_soft_credit_name',
957 'title' => 'Soft Credit Name',
958 'headerPattern' => '/^soft_credit_name$/i',
959 'where' => 'civicrm_contact_d.display_name',
961 'contribution_soft_credit_email' => array(
962 'name' => 'contribution_soft_credit_email',
963 'title' => 'Soft Credit Email',
964 'headerPattern' => '/^soft_credit_email$/i',
965 'where' => 'soft_email.email',
967 'contribution_soft_credit_phone' => array(
968 'name' => 'contribution_soft_credit_phone',
969 'title' => 'Soft Credit Phone',
970 'headerPattern' => '/^soft_credit_phone$/i',
971 'where' => 'soft_phone.phone',
973 'contribution_soft_credit_contact_id' => array(
974 'name' => 'contribution_soft_credit_contact_id',
975 'title' => 'Soft Credit Contact ID',
976 'headerPattern' => '/^soft_credit_contact_id$/i',
977 'where' => 'civicrm_contribution_soft.contact_id',
989 public static function getCurrentandGoalAmount($pageID) {
991 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
992 FROM civicrm_contribution_page p,
993 civicrm_contribution c
994 WHERE p.id = c.contribution_page_id
996 AND c.cancel_date is null
1000 $config = CRM_Core_Config
::singleton();
1001 $params = array(1 => array($pageID, 'Integer'));
1002 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1004 if ($dao->fetch()) {
1005 return array($dao->goal
, $dao->total
);
1008 return array(NULL, NULL);
1013 * Get list of contribution In Honor of contact Ids
1015 * @param int $honorId
1016 * In Honor of Contact ID.
1018 * @return return the list of contribution fields
1022 public static function getHonorContacts($honorId) {
1024 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1025 $honorDAO->contact_id
= $honorId;
1028 $type = CRM_Contribute_PseudoConstant
::financialType();
1030 while ($honorDAO->fetch()) {
1031 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1032 $contributionDAO->id
= $honorDAO->contribution_id
;
1034 if ($contributionDAO->find(TRUE)) {
1035 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1036 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1037 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1038 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1039 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1040 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1041 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1042 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1043 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1051 * Get the sort name of a contact for a particular contribution
1054 * Id of the contribution.
1056 * @return null|string sort name of the contact if found
1059 public static function sortName($id) {
1060 $id = CRM_Utils_Type
::escape($id, 'Integer');
1063 SELECT civicrm_contact.sort_name
1064 FROM civicrm_contribution, civicrm_contact
1065 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1066 AND civicrm_contribution.id = {$id}
1068 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1072 * @param int $contactID
1076 public static function annual($contactID) {
1077 if (is_array($contactID)) {
1078 $contactIDs = implode(',', $contactID);
1081 $contactIDs = $contactID;
1084 $config = CRM_Core_Config
::singleton();
1085 $startDate = $endDate = NULL;
1087 $currentMonth = date('m');
1088 $currentDay = date('d');
1089 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1090 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1091 (int ) $config->fiscalYearStart
['d'] > $currentDay
1094 $year = date('Y') - 1;
1099 $nextYear = $year +
1;
1101 if ($config->fiscalYearStart
) {
1102 if ($config->fiscalYearStart
['M'] < 10) {
1103 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1105 if ($config->fiscalYearStart
['d'] < 10) {
1106 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1108 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1113 $startDate = "$year$monthDay";
1114 $endDate = "$nextYear$monthDay";
1117 SELECT count(*) as count,
1118 sum(total_amount) as amount,
1119 avg(total_amount) as average,
1121 FROM civicrm_contribution b
1122 WHERE b.contact_id IN ( $contactIDs )
1123 AND b.contribution_status_id = 1
1125 AND b.receive_date >= $startDate
1126 AND b.receive_date < $endDate
1129 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1131 $amount = $average = array();
1132 while ($dao->fetch()) {
1133 if ($dao->count
> 0 && $dao->amount
> 0) {
1134 $count +
= $dao->count
;
1135 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1136 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1142 implode(', ', $amount),
1143 implode(', ', $average),
1146 return array(0, 0, 0);
1150 * Check if there is a contribution with the params passed in.
1151 * Used for trxn_id,invoice_id and contribution_id
1153 * @param array $params
1154 * An assoc array of name/value pairs.
1156 * @return array contribution id if success else NULL
1159 public static function checkDuplicateIds($params) {
1160 $dao = new CRM_Contribute_DAO_Contribution();
1164 foreach ($params as $k => $v) {
1166 $clause[] = "$k = '$v'";
1169 $clause = implode(' AND ', $clause);
1170 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1171 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1173 while ($dao->fetch()) {
1181 * Get the contribution details for component export
1183 * @param int $exportMode
1185 * @param string $componentIds
1188 * @return array associated array
1192 public static function getContributionDetails($exportMode, $componentIds) {
1193 $paymentDetails = array();
1194 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1196 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1197 $componentSelect = " civicrm_participant_payment.participant_id id";
1198 $additionalClause = "
1199 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1200 AND civicrm_participant_payment.participant_id {$componentClause} )
1203 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1204 $componentSelect = " civicrm_membership_payment.membership_id id";
1205 $additionalClause = "
1206 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1207 AND civicrm_membership_payment.membership_id {$componentClause} )
1210 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1211 $componentSelect = " civicrm_pledge_payment.id id";
1212 $additionalClause = "
1213 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1214 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1218 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1219 trxn_id, {$componentSelect}
1220 FROM civicrm_contribution
1221 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1222 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1223 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1224 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1225 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1226 AND option_group_contribution_status.id = contribution_status.option_group_id )
1230 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1232 while ($dao->fetch()) {
1233 $paymentDetails[$dao->id
] = array(
1234 'total_amount' => $dao->total_amount
,
1235 'contribution_status' => $dao->status
,
1236 'receive_date' => $dao->receive_date
,
1237 'pay_instru' => $dao->payment_instrument
,
1238 'trxn_id' => $dao->trxn_id
,
1242 return $paymentDetails;
1246 * Create address associated with contribution record.
1248 * @param array $params
1249 * An associated array.
1250 * @param int $billingLocationTypeID
1252 * @return address id
1255 public static function createAddress(&$params, $billingLocationTypeID) {
1256 $billingFields = array(
1259 'state_province_id',
1264 //build address array
1265 $addressParams = array();
1266 $addressParams['location_type_id'] = $billingLocationTypeID;
1267 $addressParams['is_billing'] = 1;
1269 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1270 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1271 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1272 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1274 foreach ($billingFields as $value) {
1275 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1278 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1280 return $address->id
;
1284 * Delete billing address record related contribution
1286 * @param int $contributionId
1287 * @param int $contactId
1291 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1293 $contactJoin = NULL;
1295 if ($contributionId) {
1296 $clauses[] = "cc.id = {$contributionId}";
1300 $clauses[] = "cco.id = {$contactId}";
1301 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1304 if (empty($clauses)) {
1305 CRM_Core_Error
::fatal();
1308 $condition = implode(' OR ', $clauses);
1312 FROM civicrm_address ca
1313 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1317 $dao = CRM_Core_DAO
::executeQuery($query);
1319 while ($dao->fetch()) {
1320 $params = array('id' => $dao->id
);
1321 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1326 * This function check online pending contribution associated w/
1327 * Online Event Registration or Online Membership signup.
1329 * @param int $componentId
1330 * Participant/membership id.
1331 * @param string $componentName
1334 * @return $contributionId pending contribution id.
1337 public static function checkOnlinePendingContribution($componentId, $componentName) {
1338 $contributionId = NULL;
1339 if (!$componentId ||
1340 !in_array($componentName, array('Event', 'Membership'))
1342 return $contributionId;
1345 if ($componentName == 'Event') {
1346 $idName = 'participant_id';
1347 $componentTable = 'civicrm_participant';
1348 $paymentTable = 'civicrm_participant_payment';
1349 $source = ts('Online Event Registration');
1352 if ($componentName == 'Membership') {
1353 $idName = 'membership_id';
1354 $componentTable = 'civicrm_membership';
1355 $paymentTable = 'civicrm_membership_payment';
1356 $source = ts('Online Contribution');
1359 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1362 SELECT component.id as {$idName},
1363 componentPayment.contribution_id as contribution_id,
1364 contribution.source source,
1365 contribution.contribution_status_id as contribution_status_id,
1366 contribution.is_pay_later as is_pay_later
1367 FROM $componentTable component
1368 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1369 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1370 WHERE component.id = {$componentId}";
1372 $dao = CRM_Core_DAO
::executeQuery($query);
1374 while ($dao->fetch()) {
1375 if ($dao->contribution_id
&&
1376 $dao->is_pay_later
&&
1377 $dao->contribution_status_id
== $pendingStatusId &&
1378 strpos($dao->source
, $source) !== FALSE
1380 $contributionId = $dao->contribution_id
;
1385 return $contributionId;
1389 * This function update contribution as well as related objects.
1391 public static function transitionComponents($params, $processContributionObject = FALSE) {
1392 // get minimum required values.
1393 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1394 $componentId = CRM_Utils_Array
::value('component_id', $params);
1395 $componentName = CRM_Utils_Array
::value('componentName', $params);
1396 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1397 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1399 // if we already processed contribution object pass previous status id.
1400 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1402 $updateResult = array();
1404 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1406 // we process only ( Completed, Cancelled, or Failed ) contributions.
1407 if (!$contributionId ||
1408 !in_array($contributionStatusId, array(
1409 array_search('Completed', $contributionStatuses),
1410 array_search('Cancelled', $contributionStatuses),
1411 array_search('Failed', $contributionStatuses),
1414 return $updateResult;
1417 if (!$componentName ||
!$componentId) {
1418 // get the related component details.
1419 $componentDetails = self
::getComponentDetails($contributionId);
1422 $componentDetails['contact_id'] = $contactId;
1423 $componentDetails['component'] = $componentName;
1425 if ($componentName == 'event') {
1426 $componentDetails['participant'] = $componentId;
1429 $componentDetails['membership'] = $componentId;
1433 if (!empty($componentDetails['contact_id'])) {
1434 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1440 // do check for required ids.
1441 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1442 return $updateResult;
1445 //now we are ready w/ required ids, start processing.
1447 $baseIPN = new CRM_Core_Payment_BaseIPN();
1449 $input = $ids = $objects = array();
1451 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1452 $ids['contribution'] = $contributionId;
1453 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1454 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1455 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1456 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1457 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1458 $ids['contributionRecur'] = NULL;
1459 $ids['contributionPage'] = NULL;
1461 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1462 CRM_Core_Error
::fatal();
1465 $memberships = &$objects['membership'];
1466 $participant = &$objects['participant'];
1467 $pledgePayment = &$objects['pledge_payment'];
1468 $contribution = &$objects['contribution'];
1470 if ($pledgePayment) {
1471 $pledgePaymentIDs = array();
1472 foreach ($pledgePayment as $key => $object) {
1473 $pledgePaymentIDs[] = $object->id
;
1475 $pledgeID = $pledgePayment[0]->pledge_id
;
1478 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1481 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1482 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1487 // we might want to process contribution object.
1488 $processContribution = FALSE;
1489 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1490 if (is_array($memberships)) {
1491 foreach ($memberships as $membership) {
1493 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1494 $membership->save();
1496 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1497 if ($processContributionObject) {
1498 $processContribution = TRUE;
1505 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1506 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1508 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1509 if ($processContributionObject) {
1510 $processContribution = TRUE;
1514 if ($pledgePayment) {
1515 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1517 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1518 if ($processContributionObject) {
1519 $processContribution = TRUE;
1523 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1524 if (is_array($memberships)) {
1525 foreach ($memberships as $membership) {
1527 $membership->status_id
= array_search('Expired', $membershipStatuses);
1528 $membership->save();
1530 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1531 if ($processContributionObject) {
1532 $processContribution = TRUE;
1538 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1539 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1541 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1542 if ($processContributionObject) {
1543 $processContribution = TRUE;
1547 if ($pledgePayment) {
1548 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1550 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1551 if ($processContributionObject) {
1552 $processContribution = TRUE;
1556 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1558 // only pending contribution related object processed.
1559 if ($previousContriStatusId &&
1560 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1562 // this is case when we already processed contribution object.
1563 return $updateResult;
1565 elseif (!$previousContriStatusId &&
1566 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1568 // this is case when we are going to process contribution object later.
1569 return $updateResult;
1572 if (is_array($memberships)) {
1573 foreach ($memberships as $membership) {
1578 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1579 $membership->membership_type_id
,
1580 $membership->is_test
, $membership->id
1583 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1584 // this picks up membership type changes during renewals
1586 SELECT membership_type_id
1587 FROM civicrm_membership_log
1588 WHERE membership_id=$membership->id
1591 $dao = new CRM_Core_DAO
;
1593 if ($dao->fetch()) {
1594 if (!empty($dao->membership_type_id
)) {
1595 $membership->membership_type_id
= $dao->membership_type_id
;
1596 $membership->save();
1599 // else fall back to using current membership type
1602 // Figure out number of terms
1604 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1605 foreach ($lineitems as $lineitem) {
1606 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1607 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1609 // in case membership_num_terms comes through as null or zero
1610 $numterms = $numterms >= 1 ?
$numterms : 1;
1615 // CRM-15735-to update the membership status as per the contribution receive date
1616 if (!empty($params['receive_date'])) {
1617 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1618 $membership->end_date
,
1619 $membership->join_date
,
1620 $params['receive_date'],
1622 $membership->membership_type_id
,
1625 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1626 $membership->save();
1629 if ($currentMembership) {
1630 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1631 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1632 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1635 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1638 //get the status for membership.
1639 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1641 $dates['join_date'],
1644 $membership->membership_type_id
,
1648 $formattedParams = array(
1649 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1650 array_search('Current', $membershipStatuses)
1652 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1653 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1654 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1657 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1659 $membership->copyValues($formattedParams);
1660 $membership->save();
1662 //updating the membership log
1663 $membershipLog = array();
1664 $membershipLog = $formattedParams;
1665 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1666 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1668 $membershipLog['start_date'] = $logStartDate;
1669 $membershipLog['membership_id'] = $membership->id
;
1670 $membershipLog['modified_id'] = $membership->contact_id
;
1671 $membershipLog['modified_date'] = date('Ymd');
1672 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1674 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1676 //update related Memberships.
1677 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1679 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1682 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1683 if ($processContributionObject) {
1684 $processContribution = TRUE;
1687 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1693 $updatedStatusId = array_search('Registered', $participantStatuses);
1694 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1696 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1697 if ($processContributionObject) {
1698 $processContribution = TRUE;
1702 if ($pledgePayment) {
1703 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1705 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1706 if ($processContributionObject) {
1707 $processContribution = TRUE;
1712 // process contribution object.
1713 if ($processContribution) {
1714 $contributionParams = array();
1721 'payment_instrument_id',
1724 'financial_type_id',
1725 'contribution_status_id',
1726 'non_deductible_amount',
1730 foreach ($fields as $field) {
1731 if (empty($params[$field])) {
1734 $contributionParams[$field] = $params[$field];
1737 $ids = array('contribution' => $contributionId);
1738 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1741 return $updateResult;
1745 * This function returns all contribution related object ids.
1747 public static function getComponentDetails($contributionId) {
1748 $componentDetails = $pledgePayment = array();
1749 if (!$contributionId) {
1750 return $componentDetails;
1754 SELECT c.id as contribution_id,
1755 c.contact_id as contact_id,
1756 mp.membership_id as membership_id,
1757 m.membership_type_id as membership_type_id,
1758 pp.participant_id as participant_id,
1759 p.event_id as event_id,
1760 pgp.id as pledge_payment_id
1761 FROM civicrm_contribution c
1762 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1763 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1764 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1765 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1766 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1767 WHERE c.id = $contributionId";
1769 $dao = CRM_Core_DAO
::executeQuery($query);
1770 $componentDetails = array();
1772 while ($dao->fetch()) {
1773 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1774 $componentDetails['contact_id'] = $dao->contact_id
;
1775 if ($dao->event_id
) {
1776 $componentDetails['event'] = $dao->event_id
;
1778 if ($dao->participant_id
) {
1779 $componentDetails['participant'] = $dao->participant_id
;
1781 if ($dao->membership_id
) {
1782 if (!isset($componentDetails['membership'])) {
1783 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1785 $componentDetails['membership'][] = $dao->membership_id
;
1786 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1788 if ($dao->pledge_payment_id
) {
1789 $pledgePayment[] = $dao->pledge_payment_id
;
1793 if ($pledgePayment) {
1794 $componentDetails['pledge_payment'] = $pledgePayment;
1797 return $componentDetails;
1801 * @param int $contactId
1802 * @param bool $includeSoftCredit
1804 * @return null|string
1806 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1811 $contactContributionsSQL = "
1812 SELECT contribution.id AS id
1813 FROM civicrm_contribution contribution
1814 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1816 $contactSoftCreditContributionsSQL = "
1817 SELECT contribution.id
1818 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1819 ON ( contribution.id = softContribution.contribution_id )
1820 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1821 $query = "SELECT count( x.id ) count FROM ( ";
1822 $query .= $contactContributionsSQL;
1824 if ($includeSoftCredit) {
1825 $query .= " UNION ";
1826 $query .= $contactSoftCreditContributionsSQL;
1831 return CRM_Core_DAO
::singleValueQuery($query);
1835 * Get individual id for onbehalf contribution
1837 * @param int $contributionId
1839 * @param int $contributorId
1842 * @return array $ids containing organization id and individual id
1844 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1848 if (!$contributionId) {
1852 // fetch contributor id if null
1853 if (!$contributorId) {
1854 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1855 $contributionId, 'contact_id'
1859 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1860 $activityTypeId = array_search('Contribution', $activityTypeIds);
1862 if ($activityTypeId && $contributorId) {
1864 SELECT civicrm_activity_contact.contact_id
1865 FROM civicrm_activity_contact
1866 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1867 WHERE civicrm_activity.activity_type_id = %1
1868 AND civicrm_activity.source_record_id = %2
1869 AND civicrm_activity_contact.record_type_id = %3
1872 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1873 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1876 1 => array($activityTypeId, 'Integer'),
1877 2 => array($contributionId, 'Integer'),
1878 3 => array($sourceID, 'Integer'),
1881 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1883 // for on behalf contribution source is individual and contributor is organization
1884 if ($sourceContactId && $sourceContactId != $contributorId) {
1885 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1886 // get rel type id for employee of relation
1887 foreach ($relationshipTypeIds as $id => $typeVals) {
1888 if ($typeVals['name_a_b'] == 'Employee of') {
1889 $relationshipTypeId = $id;
1894 $rel = new CRM_Contact_DAO_Relationship();
1895 $rel->relationship_type_id
= $relationshipTypeId;
1896 $rel->contact_id_a
= $sourceContactId;
1897 $rel->contact_id_b
= $contributorId;
1898 if ($rel->find(TRUE)) {
1899 $ids['individual_id'] = $rel->contact_id_a
;
1900 $ids['organization_id'] = $rel->contact_id_b
;
1912 public static function getContributionDates() {
1913 $config = CRM_Core_Config
::singleton();
1914 $currentMonth = date('m');
1915 $currentDay = date('d');
1916 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1917 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1918 (int ) $config->fiscalYearStart
['d'] > $currentDay
1921 $year = date('Y') - 1;
1926 $year = array('Y' => $year);
1927 $yearDate = $config->fiscalYearStart
;
1928 $yearDate = array_merge($year, $yearDate);
1929 $yearDate = CRM_Utils_Date
::format($yearDate);
1931 $monthDate = date('Ym') . '01';
1937 'yearDate' => $yearDate,
1938 'monthDate' => $monthDate,
1943 * Load objects relations to contribution object
1944 * Objects are stored in the $_relatedObjects property
1945 * In the first instance we are just moving functionality from BASEIpn -
1946 * see http://issues.civicrm.org/jira/browse/CRM-9996
1948 * @param array $input
1949 * Input as delivered from Payment Processor.
1951 * Ids as Loaded by Payment Processor.
1952 * @param bool $required
1953 * Is Payment processor / contribution page required.
1954 * @param bool $loadAll
1955 * Load all related objects - even where id not passed in? (allows API to call this).
1956 * Note that the unit test for the BaseIPN class tests this function
1961 * @param bool $required
1962 * @param bool $loadAll
1967 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1969 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1970 if (empty($ids['contact']) && isset($this->contact_id
)) {
1971 $ids['contact'] = $this->contact_id
;
1974 if (empty($this->_component
)) {
1975 if (!empty($ids['event'])) {
1976 $this->_component
= 'event';
1979 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1982 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1983 $contributionType = new CRM_Financial_BAO_FinancialType();
1984 $contributionType->id
= $this->financial_type_id
;
1985 if (!$contributionType->find(TRUE)) {
1986 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1988 if (!empty($ids['contact'])) {
1989 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1990 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1991 $this->_relatedObjects
['contact']->find(TRUE);
1993 $this->_relatedObjects
['contributionType'] = $contributionType;
1995 if ($this->_component
== 'contribute') {
1996 // retrieve the other optional objects first so
1997 // stuff down the line can use this info and do things
1999 //in any case get the memberships associated with the contribution
2000 //because we now support multiple memberships w/ price set
2001 // see if there are any other memberships to be considered for same contribution.
2003 SELECT membership_id
2004 FROM civicrm_membership_payment
2005 WHERE contribution_id = %1 ";
2006 $params = array(1 => array($this->id
, 'Integer'));
2008 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2009 while ($dao->fetch()) {
2010 if ($dao->membership_id
) {
2011 if (!is_array($ids['membership'])) {
2012 $ids['membership'] = array();
2014 $ids['membership'][] = $dao->membership_id
;
2018 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2019 foreach ($ids['membership'] as $id) {
2021 $membership = new CRM_Member_BAO_Membership();
2022 $membership->id
= $id;
2023 if (!$membership->find(TRUE)) {
2024 throw new Exception("Could not find membership record: $id");
2026 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2027 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2028 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2029 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2030 $membership->free();
2035 if (!empty($ids['pledge_payment'])) {
2037 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2038 if (empty($paymentID)) {
2041 $payment = new CRM_Pledge_BAO_PledgePayment();
2042 $payment->id
= $paymentID;
2043 if (!$payment->find(TRUE)) {
2044 throw new Exception("Could not find pledge payment record: " . $paymentID);
2046 $this->_relatedObjects
['pledge_payment'][] = $payment;
2050 if (!empty($ids['contributionRecur'])) {
2051 $recur = new CRM_Contribute_BAO_ContributionRecur();
2052 $recur->id
= $ids['contributionRecur'];
2053 if (!$recur->find(TRUE)) {
2054 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2056 $this->_relatedObjects
['contributionRecur'] = &$recur;
2057 //get payment processor id from recur object.
2058 $paymentProcessorID = $recur->payment_processor_id
;
2060 //for normal contribution get the payment processor id.
2061 if (!$paymentProcessorID) {
2062 if ($this->contribution_page_id
) {
2063 // get the payment processor id from contribution page
2064 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2065 $this->contribution_page_id
,
2069 //fail to load payment processor id.
2070 elseif (empty($ids['pledge_payment'])) {
2071 $loadObjectSuccess = TRUE;
2073 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2075 return $loadObjectSuccess;
2080 // we are in event mode
2081 // make sure event exists and is valid
2082 $event = new CRM_Event_BAO_Event();
2083 $event->id
= $ids['event'];
2084 if ($ids['event'] &&
2087 throw new Exception("Could not find event: " . $ids['event']);
2090 $this->_relatedObjects
['event'] = &$event;
2092 $participant = new CRM_Event_BAO_Participant();
2093 $participant->id
= $ids['participant'];
2094 if ($ids['participant'] &&
2095 !$participant->find(TRUE)
2097 throw new Exception("Could not find participant: " . $ids['participant']);
2099 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2101 $this->_relatedObjects
['participant'] = &$participant;
2103 if (!$paymentProcessorID) {
2104 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2108 if ($paymentProcessorID) {
2109 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2110 $this->is_test ?
'test' : 'live'
2112 $ids['paymentProcessor'] = $paymentProcessorID;
2113 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2115 elseif ($required) {
2116 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2123 * Create array of message information - ie. return html version, txt version, to field
2125 * @param array $input
2126 * Incoming information.
2127 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2128 * just check presence of recur object but maintaining legacy approach
2131 * IDs of related objects.
2132 * @param array $values
2133 * Any values that may have already been compiled by calling process.
2134 * This is augmented by values 'gathered' by gatherMessageValues
2135 * @param bool $returnMessageText
2136 * Distinguishes between whether to send message or return.
2137 * message text. We are working towards this function ALWAYS returning message text & calling
2138 * function doing emails / pdfs with it
2139 * @return array $messageArray - messages
2145 * @param bool $recur
2146 * @param bool $returnMessageText
2150 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2151 if (empty($this->_relatedObjects
)) {
2152 $this->loadRelatedObjects($input, $ids);
2154 if (empty($this->_component
)) {
2155 $this->_component
= CRM_Utils_Array
::value('component', $input);
2158 //not really sure what params might be passed in but lets merge em into values
2159 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2160 $template = CRM_Core_Smarty
::singleton();
2161 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2162 //what does recur 'mean here - to do with payment processor return functionality but
2163 // what is the importance
2164 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2165 $paymentObject = &CRM_Core_Payment
::singleton(
2166 $this->is_test ?
'test' : 'live',
2167 $this->_relatedObjects
['paymentProcessor']
2170 $entityID = $entity = NULL;
2171 if (isset($ids['contribution'])) {
2172 $entity = 'contribution';
2173 $entityID = $ids['contribution'];
2175 if (!empty($ids['membership'])) {
2176 //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
2177 // 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
2178 // line having loaded an array
2179 $ids['membership'] = (array) $ids['membership'];
2180 $entity = 'membership';
2181 $entityID = $ids['membership'][0];
2184 $url = $paymentObject->subscriptionURL($entityID, $entity);
2185 $template->assign('cancelSubscriptionUrl', $url);
2187 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2188 $template->assign('updateSubscriptionBillingUrl', $url);
2190 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2191 $template->assign('updateSubscriptionUrl', $url);
2193 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2194 //direct mode showing billing block, so use directIPN for temporary
2195 $template->assign('contributeMode', 'directIPN');
2198 // todo remove strtolower - check consistency
2199 if (strtolower($this->_component
) == 'event') {
2200 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2201 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2205 $values['contribution_id'] = $this->id
;
2206 if (!empty($ids['related_contact'])) {
2207 $values['related_contact'] = $ids['related_contact'];
2208 if (isset($ids['onbehalf_dupe_alert'])) {
2209 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2211 $entityBlock = array(
2212 'contact_id' => $ids['contact'],
2213 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2214 'Home', 'id', 'name'
2217 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2218 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2221 if ($this->is_test
) {
2224 if (!empty($this->_relatedObjects
['membership'])) {
2225 foreach ($this->_relatedObjects
['membership'] as $membership) {
2226 if ($membership->id
) {
2227 $values['isMembership'] = TRUE;
2229 // need to set the membership values here
2230 $template->assign('membership_assign', 1);
2231 $template->assign('membership_name',
2232 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2234 $template->assign('mem_start_date', $membership->start_date
);
2235 $template->assign('mem_join_date', $membership->join_date
);
2236 $template->assign('mem_end_date', $membership->end_date
);
2237 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2238 $template->assign('mem_status', $membership_status);
2239 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2240 $template->assign('is_pay_later', 1);
2243 // if separate payment there are two contributions recorded and the
2244 // admin will need to send a receipt for each of them separately.
2245 // we dont link the two in the db (but can potentially infer it if needed)
2246 $template->assign('is_separate_payment', 0);
2248 if ($recur && $paymentObject) {
2249 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2250 $template->assign('cancelSubscriptionUrl', $url);
2251 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2252 $template->assign('updateSubscriptionBillingUrl', $url);
2253 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2254 $template->assign('updateSubscriptionUrl', $url);
2257 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2260 // otherwise if its about sending emails, continue sending without return, as we
2261 // don't want to exit the loop.
2266 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2272 * Gather values for contribution mail - this function has been created
2273 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2274 * Values related to the contribution in question are gathered
2276 * @param array $input
2277 * Input into function (probably from payment processor).
2279 * The set of ids related to the inpurt.
2281 * @return array $values
2283 * NB don't add direct calls to the function as we intend to change the signature
2292 public function _gatherMessageValues($input, &$values, $ids = array()) {
2293 // set display address of contributor
2294 if ($this->address_id
) {
2295 $addressParams = array('id' => $this->address_id
);
2296 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2297 $addressDetails = array_values($addressDetails);
2298 $values['address'] = $addressDetails[0]['display'];
2300 if ($this->_component
== 'contribute') {
2301 if (isset($this->contribution_page_id
)) {
2302 CRM_Contribute_BAO_ContributionPage
::setValues(
2303 $this->contribution_page_id
,
2306 if ($this->contribution_page_id
) {
2307 // CRM-8254 - override default currency if applicable
2308 $config = CRM_Core_Config
::singleton();
2309 $config->defaultCurrency
= CRM_Utils_Array
::value(
2312 $config->defaultCurrency
2316 // no contribution page -probably back office
2318 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2319 $values['is_email_receipt'] = 1;
2320 $values['title'] = 'Contribution';
2322 // set lineItem for contribution
2324 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2325 if (!empty($lineItem)) {
2326 $itemId = key($lineItem);
2327 foreach ($lineItem as &$eachItem) {
2328 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2329 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2330 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2331 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2334 $values['lineItem'][0] = $lineItem;
2335 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2339 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2343 // if this is onbehalf of contribution then set related contact
2344 if (!empty($relatedContact['individual_id'])) {
2345 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2350 $eventParams = array(
2351 'id' => $this->_relatedObjects
['event']->id
,
2353 $values['event'] = array();
2355 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2357 //get location details
2358 $locationParams = array(
2359 'entity_id' => $this->_relatedObjects
['event']->id
,
2360 'entity_table' => 'civicrm_event',
2362 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2364 $ufJoinParams = array(
2365 'entity_table' => 'civicrm_event',
2366 'entity_id' => $ids['event'],
2367 'module' => 'CiviEvent',
2370 list($custom_pre_id,
2372 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2374 $values['custom_pre_id'] = $custom_pre_id;
2375 $values['custom_post_id'] = $custom_post_ids;
2377 // set lineItem for event contribution
2379 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2380 if (!empty($participantIds)) {
2381 foreach ($participantIds as $pIDs) {
2382 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2383 if (!CRM_Utils_System
::isNull($lineItem)) {
2384 $values['lineItem'][] = $lineItem;
2395 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2396 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2397 * Note we send directly from this function in some cases because it is only partly refactored
2398 * Don't call this function directly as the signature will change
2404 * @param bool $recur
2405 * @param bool $returnMessageText
2409 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2410 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2411 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2412 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2413 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2414 $template->assign('useForMember', TRUE);
2416 //assign honor information to receipt message
2417 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2419 if (isset($softRecord['soft_credit'])) {
2420 //if id of contribution page is present
2421 if (!empty($values['id'])) {
2422 $values['honor'] = array(
2423 'honor_profile_values' => array(),
2424 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2425 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2427 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2429 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2430 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2433 //offline contribution
2434 $softCreditTypes = $softCredits = array();
2435 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2436 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2437 $softCredits[$key] = array(
2438 'Name' => $softCredit['contact_name'],
2439 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2442 $template->assign('softCreditTypes', $softCreditTypes);
2443 $template->assign('softCredits', $softCredits);
2447 $dao = new CRM_Contribute_DAO_ContributionProduct();
2448 $dao->contribution_id
= $this->id
;
2449 if ($dao->find(TRUE)) {
2450 $premiumId = $dao->product_id
;
2451 $template->assign('option', $dao->product_option
);
2453 $productDAO = new CRM_Contribute_DAO_Product();
2454 $productDAO->id
= $premiumId;
2455 $productDAO->find(TRUE);
2456 $template->assign('selectPremium', TRUE);
2457 $template->assign('product_name', $productDAO->name
);
2458 $template->assign('price', $productDAO->price
);
2459 $template->assign('sku', $productDAO->sku
);
2461 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2462 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2463 if (empty($amount) && isset($this->total_amount
)) {
2464 $amount = $this->total_amount
;
2466 $template->assign('amount', $amount);
2467 // add the new contribution values
2468 if (strtolower($this->_component
) == 'contribute') {
2470 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2471 $softDAO->contribution_id
= $this->id
;
2472 if ($softDAO->find(TRUE)) {
2473 $template->assign('pcpBlock', TRUE);
2474 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2475 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2476 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2478 //assign the pcp page title for email subject
2479 $pcpDAO = new CRM_PCP_DAO_PCP();
2480 $pcpDAO->id
= $softDAO->pcp_id
;
2481 if ($pcpDAO->find(TRUE)) {
2482 $template->assign('title', $pcpDAO->title
);
2487 if ($this->financial_type_id
) {
2488 $values['financial_type_id'] = $this->financial_type_id
;
2492 $template->assign('trxn_id', $this->trxn_id
);
2493 $template->assign('receive_date',
2494 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2496 $template->assign('contributeMode', 'notify');
2497 $template->assign('action', $this->is_test ?
1024 : 1);
2498 $template->assign('receipt_text',
2499 CRM_Utils_Array
::value('receipt_text',
2503 $template->assign('is_monetary', 1);
2504 $template->assign('is_recur', (bool) $recur);
2505 $template->assign('currency', $this->currency
);
2506 $template->assign('address', CRM_Utils_Address
::format($input));
2507 if ($this->_component
== 'event') {
2508 $template->assign('title', $values['event']['title']);
2509 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2510 $viewRoles = array();
2511 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2512 $viewRoles[] = $participantRoles[$v];
2514 $values['event']['participant_role'] = implode(', ', $viewRoles);
2515 $template->assign('event', $values['event']);
2516 $template->assign('location', $values['location']);
2517 $template->assign('customPre', $values['custom_pre_id']);
2518 $template->assign('customPost', $values['custom_post_id']);
2521 if ($this->_relatedObjects
['participant']->is_test
) {
2525 $values['params'] = array();
2526 //to get email of primary participant.
2527 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2528 $primaryAmount[] = array(
2529 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2530 'amount' => $this->_relatedObjects
['participant']->fee_amount
2532 //build an array of cId/pId of participants
2533 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2534 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2535 //send receipt to additional participant if exists
2536 if (count($additionalIDs)) {
2537 $template->assign('isPrimary', 0);
2538 $template->assign('customProfile', NULL);
2539 //set additionalParticipant true
2540 $values['params']['additionalParticipant'] = TRUE;
2541 foreach ($additionalIDs as $pId => $cId) {
2543 //to change the status pending to completed
2544 $additional = new CRM_Event_DAO_Participant();
2545 $additional->id
= $pId;
2546 $additional->contact_id
= $cId;
2547 $additional->find(TRUE);
2548 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2549 $additional->status_id
= 1;
2550 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2551 //if additional participant dont have email
2553 if (!$additionalParticipantInfo) {
2554 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2556 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2557 $primaryAmount[] = array(
2558 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2559 'amount' => $additional->fee_amount
2561 $additional->save();
2562 $additional->free();
2563 $template->assign('amount', $amount);
2564 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2568 //build an array of custom profile and assigning it to template
2569 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2571 if (count($customProfile)) {
2572 $template->assign('customProfile', $customProfile);
2575 // for primary contact
2576 $values['params']['additionalParticipant'] = FALSE;
2577 $template->assign('isPrimary', 1);
2578 $template->assign('amount', $primaryAmount);
2579 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2580 if ($this->payment_instrument_id
) {
2581 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2582 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2584 // carry paylater, since we did not created billing,
2585 // so need to pull email from primary location, CRM-4395
2586 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2592 * Check whether payment processor supports
2593 * cancellation of contribution subscription
2595 * @param int $contributionId
2598 * @param bool $isNotCancelled
2603 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2604 $cacheKeyString = "$contributionId";
2605 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2607 static $supportsCancel = array();
2609 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2610 $supportsCancel[$cacheKeyString] = FALSE;
2611 $isCancelled = FALSE;
2613 if ($isNotCancelled) {
2614 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2617 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2618 if (!empty($paymentObject)) {
2619 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2622 return $supportsCancel[$cacheKeyString];
2626 * Check whether subscription is already cancelled
2628 * @param int $contributionId
2631 * @return string $status contribution status
2634 public static function isSubscriptionCancelled($contributionId) {
2636 SELECT cr.contribution_status_id
2637 FROM civicrm_contribution_recur cr
2638 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2639 WHERE con.id = %1 LIMIT 1";
2640 $params = array(1 => array($contributionId, 'Integer'));
2641 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2642 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2643 if ($status == 'Cancelled') {
2650 * Create all financial accounts entry
2652 * @param array $params
2653 * Contribution object, line item array and params for trxn.
2656 * @param array $financialTrxnValues
2658 * @return null|object
2661 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2662 $skipRecords = $update = $return = $isRelatedId = FALSE;
2664 $additionalParticipantId = array();
2665 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2667 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2668 $entityId = $params['participant_id'];
2669 $entityTable = 'civicrm_participant';
2670 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2672 elseif (!empty($params['membership_id'])) {
2673 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2674 // are created off one contribution should be handled elsewhere
2675 $entityId = $params['membership_id'];
2676 $entityTable = 'civicrm_membership';
2679 $entityId = $params['contribution']->id
;
2680 $entityTable = 'civicrm_contribution';
2683 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2684 $isRelatedId = TRUE;
2687 $entityID[] = $entityId;
2688 if (!empty($additionalParticipantId)) {
2689 $entityID +
= $additionalParticipantId;
2691 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2692 if (empty($params['prevContribution'])) {
2699 $statusId = $params['contribution']->contribution_status_id
;
2700 // CRM-13964 partial payment
2701 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2702 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2704 $partialAmtPay = $params['partial_amount_pay'];
2705 $partialAmtTotal = $params['partial_payment_total'];
2707 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2708 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2709 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2710 $params['total_amount'] = $partialAmtPay;
2712 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2713 if (empty($balanceTrxnInfo['trxn_id'])) {
2714 // create new balance transaction record
2715 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2716 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2718 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2719 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2720 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2721 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2722 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2723 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2724 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2725 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2726 $balanceTrxnParams['status_id'] = $statusId;
2727 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2728 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2729 if (!empty($params['payment_processor'])) {
2730 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2732 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2736 // build line item array if its not set in $params
2737 if (empty($params['line_item']) ||
$additionalParticipantId) {
2738 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2741 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2742 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2744 $skipRecords = TRUE;
2745 $pendingStatus = array(
2746 array_search('Pending', $contributionStatuses),
2747 array_search('In Progress', $contributionStatuses)
2749 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2750 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2751 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2753 elseif (!empty($params['payment_processor'])) {
2754 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2756 elseif (!empty($params['payment_instrument_id'])) {
2757 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2760 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2761 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2762 $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);
2765 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2766 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2767 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2770 //build financial transaction params
2771 $trxnParams = array(
2772 'contribution_id' => $params['contribution']->id
,
2773 'to_financial_account_id' => $params['to_financial_account_id'],
2774 'trxn_date' => date('YmdHis'),
2775 'total_amount' => $totalAmount,
2776 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2777 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2778 'currency' => $params['contribution']->currency
,
2779 'trxn_id' => $params['contribution']->trxn_id
,
2780 'status_id' => $statusId,
2781 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2782 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2785 if (!empty($params['payment_processor'])) {
2786 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2789 if (isset($fromFinancialAccountId)) {
2790 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2793 // consider external values passed for recording transaction entry
2794 if (!empty($financialTrxnValues)) {
2795 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2798 $params['trxnParams'] = $trxnParams;
2800 if (!empty($params['prevContribution'])) {
2801 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2802 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2803 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2804 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2805 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2808 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2809 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2810 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2812 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2813 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2816 //if financial type is changed
2817 if (!empty($params['financial_type_id']) &&
2818 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2820 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2821 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2822 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2823 if ($oldFinancialAccount != $newFinancialAccount) {
2824 $params['total_amount'] = 0;
2825 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2826 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2827 $params['prevContribution']->financial_type_id
, $relationTypeId);
2830 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2831 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2832 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2835 self
::updateFinancialAccounts($params, 'changeFinancialType');
2836 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2837 $params['financial_account_id'] = $newFinancialAccount;
2838 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2839 self
::updateFinancialAccounts($params);
2840 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2844 //Update contribution status
2845 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2846 if (!empty($params['contribution_status_id']) &&
2847 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2849 //Update Financial Records
2850 self
::updateFinancialAccounts($params, 'changedStatus');
2853 // change Payment Instrument for a Completed contribution
2854 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2855 // instrument is null and now new payment instrument is added along with the payment
2856 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2857 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2858 if (array_key_exists('payment_instrument_id', $params)) {
2859 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2860 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2861 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2863 //check if status is changed from Pending to Completed
2864 // do not update payment instrument changes for Pending to Completed
2865 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2866 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2868 // for all other statuses create new financial records
2869 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2870 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2871 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2874 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2875 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2876 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2878 // for any other payment instrument changes create new financial records
2879 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2880 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2881 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2883 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2884 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2886 // another special case when check number is changed, create new financial records
2887 // create financial trxn with negative amount
2888 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2889 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2890 // create financial trxn with positive amount
2891 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2892 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2893 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2897 //if Change contribution amount
2898 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2899 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2900 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2901 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2902 if (isset($totalAmount) &&
2903 $totalAmount != $params['prevContribution']->total_amount
2905 //Update Financial Records
2906 $params['trxnParams']['from_financial_account_id'] = NULL;
2907 self
::updateFinancialAccounts($params, 'changedAmount');
2912 // records finanical trxn and entity financial trxn
2913 // also make it available as return value
2914 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2915 $params['entity_id'] = $financialTxn->id
;
2918 // record line items and finacial items
2919 if (empty($params['skipLineItem'])) {
2920 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2923 // create batch entry if batch_id is passed
2924 if (!empty($params['batch_id'])) {
2925 $entityParams = array(
2926 'batch_id' => $params['batch_id'],
2927 'entity_table' => 'civicrm_financial_trxn',
2928 'entity_id' => $financialTxn->id
,
2930 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2933 // when a fee is charged
2934 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2935 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2938 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2939 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2941 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2942 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2943 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2945 unset($params['line_item']);
2951 * Update all financial accounts entry
2953 * @param array $params
2954 * Contribution object, line item array and params for trxn.
2956 * @param string $context
2959 * @param null $skipTrxn
2963 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2964 $itemAmount = $trxnID = NULL;
2965 //get all the statuses
2966 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2967 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2968 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2969 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2970 && $context == 'changePaymentInstrument'
2974 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2975 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2977 if ($context == 'changedStatus') {
2978 //get all the statuses
2979 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2981 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2982 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2983 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2985 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2987 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2988 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2990 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2991 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2992 $params['trxnParams']['to_financial_account_id'] = NULL;
2993 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2995 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2996 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2997 $financialTypeID, $relationTypeId);
2999 $itemAmount = $params['trxnParams']['total_amount'];
3001 elseif ($context == 'changePaymentInstrument') {
3002 if ($params['trxnParams']['total_amount'] < 0) {
3003 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3004 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3005 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3006 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3010 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3011 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3014 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3015 $params['entity_id'] = $trxn->id
;
3017 if ($context == 'changedStatus') {
3018 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3019 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3020 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3022 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3023 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3025 $entityParams = array(
3026 'entity_table' => 'civicrm_financial_item',
3027 'financial_trxn_id' => $trxn->id
,
3029 if (empty($params['line_item'])) {
3031 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3032 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3033 // & this can be removed
3036 foreach ($params['line_item'] as $fieldId => $fields) {
3037 foreach ($fields as $fieldValueId => $fieldValues) {
3039 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3040 2 => array($fieldValues['id'], 'Integer'),
3042 CRM_Core_DAO
::executeQuery($query, $fparams);
3044 1 => array($fieldValues['id'], 'Integer'),
3046 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3047 while ($financialItem->fetch()) {
3048 $entityParams['entity_id'] = $financialItem->id
;
3049 $entityParams['amount'] = $financialItem->amount
;
3050 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3057 if ($context != 'changePaymentInstrument') {
3058 $itemParams['entity_table'] = 'civicrm_line_item';
3059 $trxnIds['id'] = $params['entity_id'];
3060 foreach ($params['line_item'] as $fieldId => $fields) {
3061 foreach ($fields as $fieldValueId => $fieldValues) {
3062 $prevParams['entity_id'] = $fieldValues['id'];
3063 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3065 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3066 if ($params['contribution']->receive_date
) {
3067 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3070 $financialAccount = $prevfinancialItem->financial_account_id
;
3071 if (!empty($params['financial_account_id'])) {
3072 $financialAccount = $params['financial_account_id'];
3075 $currency = $params['prevContribution']->currency
;
3076 if ($params['contribution']->currency
) {
3077 $currency = $params['contribution']->currency
;
3080 if (!empty($params['is_quick_config'])) {
3081 $amount = $itemAmount;
3083 $amount = $params['total_amount'];
3087 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3088 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3092 $amount = $diff * $fieldValues['line_total'];
3095 $itemParams = array(
3096 'transaction_date' => $receiveDate,
3097 'contact_id' => $params['prevContribution']->contact_id
,
3098 'currency' => $currency,
3099 'amount' => $amount,
3100 'description' => $prevfinancialItem->description
,
3101 'status_id' => $prevfinancialItem->status_id
,
3102 'financial_account_id' => $financialAccount,
3103 'entity_table' => 'civicrm_line_item',
3104 'entity_id' => $fieldValues['id']
3106 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3108 if ($fieldValues['tax_amount']) {
3109 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3110 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3111 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3112 $itemParams['description'] = $taxTerm;
3113 if ($fieldValues['financial_type_id']) {
3114 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3116 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3124 * Check status validation on update of a contribution
3126 * @param array $values
3127 * Previous form values before submit.
3129 * @param array $fields
3130 * The input form values.
3132 * @param array $errors
3138 public static function checkStatusValidation($values, &$fields, &$errors) {
3139 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3140 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3141 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3145 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3146 $checkStatus = array(
3147 'Cancelled' => array('Completed', 'Refunded'),
3148 'Completed' => array('Cancelled', 'Refunded'),
3149 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3150 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3151 'Refunded' => array('Cancelled', 'Completed')
3154 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3155 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3156 1 => $contributionStatuses[$values['contribution_status_id']],
3157 2 => $contributionStatuses[$fields['contribution_status_id']]
3163 * Delete contribution of contact
3167 * @param int $contactId
3172 public static function deleteContactContribution($contactId) {
3173 $contribution = new CRM_Contribute_DAO_Contribution();
3174 $contribution->contact_id
= $contactId;
3175 $contribution->find();
3176 while ($contribution->fetch()) {
3177 self
::deleteContribution($contribution->id
);
3182 * Get options for a given contribution field.
3183 * @see CRM_Core_DAO::buildOptions
3185 * @param string $fieldName
3186 * @param string $context
3187 * : @see CRM_Core_DAO::buildOptionsContext.
3188 * @param array $props
3189 * : whatever is known about this dao object.
3191 * @return Array|bool
3193 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3194 $className = __CLASS__
;
3196 switch ($fieldName) {
3197 // This field is not part of this object but the api supports it
3198 case 'payment_processor':
3199 $className = 'CRM_Contribute_BAO_ContributionPage';
3200 // Filter results by contribution page
3201 if (!empty($props['contribution_page_id'])) {
3202 $page = civicrm_api('contribution_page', 'getsingle', array(
3204 'id' => ($props['contribution_page_id'])
3206 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3207 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3210 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3211 case 'honor_type_id':
3212 $className = 'CRM_Contribute_BAO_ContributionSoft';
3213 $fieldName = 'soft_credit_type_id';
3214 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3217 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3221 * Validate financial type
3225 * @param int $financialTypeId
3226 * Financial Type id.
3228 * @param string $relationName
3230 * @return array|bool
3233 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3234 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3235 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3237 if (!$financialAccount) {
3238 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3245 * Function to record additional payment for partial and refund contributions
3247 * @param int $contributionId
3248 * : is the invoice contribution id (got created after processing participant payment).
3249 * @param array $trxnData
3250 * : to take user provided input of transaction details.
3251 * @param string $paymentType
3252 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3255 * @param int $contributionId
3257 * @param string $paymentType
3258 * @param int $participantId
3260 * @return null|object
3262 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3263 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3264 $getInfoOf['id'] = $contributionId;
3265 $defaults = array();
3266 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3268 if ($paymentType == 'owed') {
3269 // build params for recording financial trxn entry
3270 $params['contribution'] = $contributionDAO;
3271 $params = array_merge($defaults, $params);
3272 $params['skipLineItem'] = TRUE;
3273 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3274 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3275 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3278 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3279 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3280 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3282 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3283 if (!empty($trxnId)) {
3284 $trxnId = $trxnId['trxn_id'];
3286 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3287 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3290 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3291 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3292 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3296 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3297 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3298 FROM civicrm_financial_trxn ft
3299 LEFT JOIN civicrm_entity_financial_trxn eft
3300 ON (ft.id = eft.financial_trxn_id)
3301 WHERE eft.entity_table = 'civicrm_contribution'
3302 AND eft.entity_id = {$contributionId}
3303 AND ft.to_financial_account_id != {$toFinancialAccount}
3304 AND ft.status_id = {$statusId}
3306 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3309 if ($contributionDAO->total_amount
== $sumOfPayments) {
3310 // update contribution status and
3311 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3312 $contributionDAO->contribution_status_id
= $statusId;
3313 $contributionDAO->cancel_date
= 'null';
3314 $contributionDAO->cancel_reason
= NULL;
3315 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3316 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3317 $contributionDAO->save();
3319 //Change status of financial record too
3320 $financialTrxn->status_id
= $statusId;
3321 $financialTrxn->save();
3323 // note : not using the self::add method,
3324 // the reason because it performs 'status change' related code execution for financial records
3325 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3326 // are coded below i.e. just updating financial_item status to 'Paid'
3328 if ($participantId) {
3329 // update participant status
3330 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3331 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3332 foreach ($ids as $val) {
3333 $participantUpdate['id'] = $val;
3334 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3335 CRM_Event_BAO_Participant
::add($participantUpdate);
3339 // update financial item statuses
3340 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3341 $paidStatus = array_search('Paid', $financialItemStatus);
3343 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3344 $sqlFinancialItemUpdate = "
3345 UPDATE civicrm_financial_item fi
3346 LEFT JOIN civicrm_entity_financial_trxn eft
3347 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3348 SET status_id = {$paidStatus}
3349 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3351 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3354 elseif ($paymentType == 'refund') {
3355 // build params for recording financial trxn entry
3356 $params['contribution'] = $contributionDAO;
3357 $params = array_merge($defaults, $params);
3358 $params['skipLineItem'] = TRUE;
3359 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3360 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3362 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3363 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3364 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3366 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3368 // note : not using the self::add method,
3369 // the reason because it performs 'status change' related code execution for financial records
3370 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3371 // are coded below i.e. just updating financial_item status to 'Paid'
3372 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3374 // add financial item entry
3375 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3376 $getLine['entity_id'] = $contributionDAO->id
;
3377 $getLine['entity_table'] = 'civicrm_contribution';
3378 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3379 if (!empty($lineItemId->id
)) {
3380 $addFinancialEntry = array(
3381 'transaction_date' => $financialTrxn->trxn_date
,
3382 'contact_id' => $contributionDAO->contact_id
,
3383 'amount' => $financialTrxn->total_amount
,
3384 'status_id' => array_search('Paid', $financialItemStatus),
3385 'entity_id' => $lineItemId->id
,
3386 'entity_table' => 'civicrm_line_item'
3388 $trxnIds['id'] = $financialTrxn->id
;
3389 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3391 if ($participantId) {
3392 // update participant status
3393 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3394 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3395 foreach ($ids as $val) {
3396 $participantUpdate['id'] = $val;
3397 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3398 CRM_Event_BAO_Participant
::add($participantUpdate);
3403 // activity creation
3404 if (!empty($financialTrxn)) {
3405 if ($participantId) {
3406 $inputParams['id'] = $participantId;
3409 $component = 'event';
3410 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3411 $entityObj = $entityObj[$participantId];
3413 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3415 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3417 return $financialTrxn;
3423 * @param $activityType
3425 * @param int $contributionId
3427 * @throws CRM_Core_Exception
3429 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3430 if ($component == 'event') {
3431 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3432 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3433 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3434 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3435 $targetCid = $entityObj->contact_id
;
3436 // source record id would be the contribution id
3437 $srcRecId = $contributionId;
3441 $activityParams = array(
3442 'source_contact_id' => $targetCid,
3443 'source_record_id' => $srcRecId,
3444 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3448 'subject' => $subject,
3449 'activity_date_time' => $date,
3450 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3454 'skipRecentView' => TRUE,
3457 // create activity with target contacts
3458 $session = CRM_Core_Session
::singleton();
3459 $id = $session->get('userID');
3461 $activityParams['source_contact_id'] = $id;
3462 $activityParams['target_contact_id'][] = $targetCid;
3464 CRM_Activity_BAO_Activity
::create($activityParams);
3468 * Get list of payments displayed by Contribute_Page_PaymentInfo
3472 * @param bool $getTrxnInfo
3473 * @param bool $usingLineTotal
3477 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3478 if ($component == 'event') {
3479 $entity = 'participant';
3480 $entityTable = 'civicrm_participant';
3481 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3483 if (!$contributionId) {
3484 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3485 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3486 $id = $primaryParticipantId;
3488 if (!$contributionId) {
3493 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3494 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3500 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3501 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3504 if (empty($total) ||
$usingLineTotal) {
3505 // for additional participants
3506 if ($entityTable == 'civicrm_participant') {
3507 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3509 foreach ($ids as $val) {
3510 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3514 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3518 $baseTrxnId = $total['trxn_id'];
3519 $total = $total['total_amount'];
3522 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3523 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3525 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3526 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3527 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3529 if ($paymentBalance == 0 && $contributionIsPayLater) {
3530 $paymentBalance = $total;
3533 $info['total'] = $total;
3534 $info['paid'] = $total - $paymentBalance;
3535 $info['balance'] = $paymentBalance;
3537 $info['component'] = $component;
3538 $info['payLater'] = $contributionIsPayLater;
3540 if ($getTrxnInfo && $baseTrxnId) {
3541 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3543 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3544 FROM civicrm_contribution con
3545 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3546 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3547 WHERE con.id = {$contributionId}
3550 // conditioned WHERE clause
3552 // if balance trxn exists don't include details of it in transaction info
3553 $sql .= " AND ft.id != {$baseTrxnId} ";
3555 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3557 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3558 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3559 while ($resultDAO->fetch()) {
3560 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3561 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3563 'total_amount' => $resultDAO->total_amount
,
3564 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3565 'payment_instrument' => $paidByLabel,
3566 'receive_date' => $resultDAO->trxn_date
,
3567 'trxn_id' => $resultDAO->trxn_id
,
3568 'status' => $statuses[$resultDAO->status_id
],
3570 if ($paidByName == 'Check') {
3571 $val['check_number'] = $resultDAO->check_number
;
3575 $info['transaction'] = $rows;
3581 * Get financial account id has 'Sales Tax Account is'
3582 * account relationship with financial type
3584 * @param int $financialTypeId
3586 * @return FinancialAccountId
3588 public static function getFinancialAccountId($financialTypeId) {
3589 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3590 $searchParams = array(
3591 'entity_table' => 'civicrm_financial_type',
3592 'entity_id' => $financialTypeId,
3593 'account_relationship' => $accountRel,
3596 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3598 return CRM_Utils_Array
::value('financial_account_id', $result);
3601 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3602 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3604 // Update contribution
3605 if (!empty($params['id'])) {
3606 $id = $params['id'];
3607 $values = $ids = array();
3608 $contrbutionParams = array('id' => $id);
3609 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3611 // To assign pervious finantial type on update of contribution
3612 if (!isset($params['financial_type_id'])) {
3613 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3615 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3616 // Assisn tax Amount on update of contrbution
3617 if (!empty($prevContributionValue->tax_amount
)) {
3618 $params['tax_amount'] = 'null';
3619 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3620 foreach ($params['line_item'] as $setID => $priceField) {
3621 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3622 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3629 // New Contrbution and update of contribution with tax rate financial type
3630 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3631 empty($params['skipLineItem']) && !$isLineItem
3633 $taxRateParams = $taxRates[$params['financial_type_id']];
3634 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3635 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3637 // Get Line Item on update of contribution
3638 if (isset($params['id'])) {
3639 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3642 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3644 foreach ($params['line_item'] as $setID => $priceField) {
3645 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3646 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3649 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3651 elseif (isset($params['api.line_item.create'])) {
3652 // Update total amount of contribution using lineItem
3653 $taxAmountArray = array();
3654 foreach ($params['api.line_item.create'] as $key => $value) {
3655 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3656 $taxRate = $taxRates[$value['financial_type_id']];
3657 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3658 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3661 $params['tax_amount'] = array_sum($taxAmountArray);
3662 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3665 // update line item of contrbution
3666 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3667 $taxRate = $taxRates[$params['financial_type_id']];
3668 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3669 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);