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
79 public function __construct() {
80 parent
::__construct();
84 * Takes an associative array and creates a contribution object
86 * the function extract all the params it needs to initialize the create a
87 * contribution object. the params array could contain additional unused name/value
90 * @param array $params
91 * (reference ) an assoc array of name/value pairs.
93 * The array that holds all the db ids.
95 * @return CRM_Contribute_BAO_Contribution
98 public static function add(&$params, $ids = array()) {
102 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
103 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
104 $duplicates = array();
105 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
106 $error = CRM_Core_Error
::singleton();
107 $d = implode(', ', $duplicates);
108 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
111 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
116 // first clean up all the money fields
117 $moneyFields = array(
121 'non_deductible_amount',
124 //if priceset is used, no need to cleanup money
125 if (!empty($params['skipCleanMoney'])) {
126 unset($moneyFields[0]);
129 foreach ($moneyFields as $field) {
130 if (isset($params[$field])) {
131 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
135 //set defaults in create mode
136 if (!$contributionID) {
137 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
138 self
::calculateMissingAmountParams($params);
141 if (!empty($params['payment_instrument_id'])) {
142 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
143 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
144 $params['check_number'] = 'null';
148 $setPrevContribution = TRUE;
149 // CRM-13964 partial payment
150 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
151 $partialAmtTotal = $params['partial_payment_total'];
152 $partialAmtPay = $params['partial_amount_pay'];
153 $params['total_amount'] = $partialAmtTotal;
154 if ($partialAmtPay < $partialAmtTotal) {
155 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
156 $params['is_pay_later'] = 0;
157 $setPrevContribution = FALSE;
161 if ($contributionID) {
162 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
165 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
167 $contribution = new CRM_Contribute_BAO_Contribution();
168 $contribution->copyValues($params);
170 $contribution->id
= $contributionID;
172 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
173 $config = CRM_Core_Config
::singleton();
174 $contribution->currency
= $config->defaultCurrency
;
177 if ($contributionID && $setPrevContribution) {
178 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
181 $result = $contribution->save();
183 // Add financial_trxn details as part of fix for CRM-4724
184 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
185 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
187 //add Account details
188 $params['contribution'] = $contribution;
189 self
::recordFinancialAccounts($params);
191 // reset the group contact cache for this group
192 CRM_Contact_BAO_GroupContactCache
::remove();
194 if ($contributionID) {
195 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
198 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
205 * Get defaults for new entity
208 public static function getDefaults() {
210 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
211 FALSE, FALSE, FALSE, 'AND is_default = 1')
213 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
218 * Given the list of params in the params array, fetch the object
219 * and store the values in the values array
221 * @param array $params
222 * Input parameters to find object.
223 * @param array $values
224 * Output values of the object.
226 * The array that holds all the db ids.
228 * @return CRM_Contribute_BAO_Contribution|null the found object or null
231 public static function &getValues($params, &$values, &$ids) {
232 if (empty($params)) {
235 $contribution = new CRM_Contribute_BAO_Contribution();
237 $contribution->copyValues($params);
239 if ($contribution->find(TRUE)) {
240 $ids['contribution'] = $contribution->id
;
242 CRM_Core_DAO
::storeValues($contribution, $values);
244 return $contribution;
246 $null = NULL; // return by reference
251 * @param array $params
255 public static function calculateMissingAmountParams(&$params) {
256 if (!isset($params['fee_amount'])) {
257 if (isset($params['total_amount']) && isset($params['net_amount'])) {
258 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
261 $params['fee_amount'] = 0;
264 if (!isset($params['net_amount'])) {
265 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
270 * Get the number of terms for this contribution for a given membership type
271 * based on querying the line item table and relevant price field values
272 * Note that any one contribution should only be able to have one line item relating to a particular membership
275 * @param int $membershipTypeID
277 * @param int $contributionID
281 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
282 $numTerms = CRM_Core_DAO
::singleValueQuery("
283 SELECT membership_num_terms FROM civicrm_line_item li
284 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
285 WHERE contribution_id = %1 AND membership_type_id = %2",
286 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
288 // default of 1 is precautionary
289 return empty($numTerms) ?
1 : $numTerms;
293 * Takes an associative array and creates a contribution object
295 * @param array $params
296 * (reference ) an assoc array of name/value pairs.
298 * The array that holds all the db ids.
300 * @return CRM_Contribute_BAO_Contribution
303 public static function create(&$params, $ids = array()) {
304 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
305 foreach ($dateFields as $df) {
306 if (isset($params[$df])) {
307 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
311 $transaction = new CRM_Core_Transaction();
313 $contribution = self
::add($params, $ids);
315 if (is_a($contribution, 'CRM_Core_Error')) {
316 $transaction->rollback();
317 return $contribution;
320 $params['contribution_id'] = $contribution->id
;
322 if (!empty($params['custom']) &&
323 is_array($params['custom'])
325 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
328 $session = CRM_Core_Session
::singleton();
330 if (!empty($params['note'])) {
332 'entity_table' => 'civicrm_contribution',
333 'note' => $params['note'],
334 'entity_id' => $contribution->id
,
335 'contact_id' => $session->get('userID'),
336 'modified_date' => date('Ymd'),
338 if (!$noteParams['contact_id']) {
339 $noteParams['contact_id'] = $params['contact_id'];
341 CRM_Core_BAO_Note
::add($noteParams);
344 // make entry in batch entity batch table
345 if (!empty($params['batch_id'])) {
346 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
347 $titleFields = array(
353 $retrieveRequired = 0;
354 foreach ($titleFields as $titleField) {
355 if (!isset($contribution->$titleField)) {
356 $retrieveRequired = 1;
360 if ($retrieveRequired == 1) {
361 $contribution->find(TRUE);
365 // check if activity record exist for this contribution, if
367 $activity = new CRM_Activity_DAO_Activity();
368 $activity->source_record_id
= $contribution->id
;
369 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
373 if (!$activity->find(TRUE)) {
374 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
377 // CRM-13237 : if activity record found, update it with campaign id of contribution
378 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
381 // Handle soft credit and / or link to personal campaign page
382 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
384 //Delete PCP against this contribution and create new on submitted PCP information
385 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
387 $deleteParams = array('id' => $pcpId);
388 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
390 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
391 $softParams = array();
392 $softParams['contribution_id'] = $contribution->id
;
393 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
394 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
395 $pcp['pcp_made_through_id'], 'contact_id'
397 $softParams['currency'] = $contribution->currency
;
398 $softParams['amount'] = $contribution->total_amount
;
399 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
400 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
401 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
402 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
403 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
405 if (isset($params['soft_credit'])) {
406 $softParams = $params['soft_credit'];
408 if (!empty($softIDs)) {
409 foreach ($softIDs as $softID) {
410 if (!in_array($softID, $params['soft_credit_ids'])) {
411 $deleteParams = array('id' => $softID);
412 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
417 foreach ($softParams as $softParam) {
418 $softParam['contribution_id'] = $contribution->id
;
419 $softParam['currency'] = $contribution->currency
;
420 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
421 if (empty($softParam['amount'])) {
422 $softParam['amount'] = $contribution->total_amount
;
424 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
428 $transaction->commit();
430 // do not add to recent items for import, CRM-4399
431 if (empty($params['skipRecentView'])) {
432 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
433 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
435 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
436 $titleFields = array(
442 $retrieveRequired = 0;
443 foreach ($titleFields as $titleField) {
444 if (!isset($contribution->$titleField)) {
445 $retrieveRequired = 1;
449 if ($retrieveRequired == 1) {
450 $contribution->find(TRUE);
452 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
453 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
455 $recentOther = array();
456 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
457 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
458 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
462 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
463 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
464 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
468 // add the recently created Contribution
469 CRM_Utils_Recent
::add($title,
473 $contribution->contact_id
,
479 return $contribution;
483 * Get the values for pseudoconstants for name->value and reverse.
485 * @param array $defaults
486 * (reference) the default values, some of which need to be resolved.
487 * @param bool $reverse
488 * True if we want to resolve the values in the reverse direction (value -> name).
493 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
494 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
495 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
496 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
497 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
501 * convert associative array names to values
504 * This function is used by both the web form layer and the api. Note that
505 * the api needs the name => value conversion, also the view layer typically
506 * requires value => name conversion
508 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
509 $id = $property . '_id';
511 $src = $reverse ?
$property : $id;
512 $dst = $reverse ?
$id : $property;
514 if (!array_key_exists($src, $defaults)) {
518 $look = $reverse ?
array_flip($lookup) : $lookup;
520 if (is_array($look)) {
521 if (!array_key_exists($defaults[$src], $look)) {
525 $defaults[$dst] = $look[$defaults[$src]];
530 * Takes a bunch of params that are needed to match certain criteria and
531 * retrieves the relevant objects. We'll tweak this function to be more
532 * full featured over a period of time. This is the inverse function of
533 * create. It also stores all the retrieved values in the default array
535 * @param array $params
536 * (reference ) an assoc array of name/value pairs.
537 * @param array $defaults
538 * (reference ) an assoc array to hold the name / value pairs.
539 * in a hierarchical manner
541 * (reference) the array that holds all the db ids.
543 * @return CRM_Contribute_BAO_Contribution
546 public static function retrieve(&$params, &$defaults, &$ids) {
547 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
548 return $contribution;
552 * Combine all the importable fields from the lower levels object
554 * The ordering is important, since currently we do not have a weight
555 * scheme. Adding weight is super important and should be done in the
556 * next week or so, before this can be called complete.
558 * @param string $contactType
559 * @param bool $status
562 * array of importable Fields
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
775 * $results no of deleted Contribution on success, false otherwise
779 public static function deleteContribution($id) {
780 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
782 $transaction = new CRM_Core_Transaction();
785 //delete activity record
787 'source_record_id' => $id,
788 // activity type id for contribution
789 'activity_type_id' => 6,
792 CRM_Activity_BAO_Activity
::deleteActivity($params);
794 //delete billing address if exists for this contribution.
795 self
::deleteAddress($id);
797 //update pledge and pledge payment, CRM-3961
798 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
800 // remove entry from civicrm_price_set_entity, CRM-5095
801 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
802 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
804 // cleanup line items.
805 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
807 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
808 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
810 if ($participantId) {
811 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
814 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
818 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
819 $noteId = key($note);
821 CRM_Core_BAO_Note
::del($noteId, FALSE);
824 $dao = new CRM_Contribute_DAO_Contribution();
827 $results = $dao->delete();
829 $transaction->commit();
831 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
833 // delete the recently created Contribution
834 $contributionRecent = array(
836 'type' => 'Contribution',
838 CRM_Utils_Recent
::del($contributionRecent);
844 * Check if there is a contribution with the same trxn_id or invoice_id
846 * @param array $input
847 * An assoc array of name/value pairs.
848 * @param array $duplicates
849 * (reference) store ids of duplicate contribs.
853 * true if duplicate, false otherwise
856 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
858 $id = CRM_Utils_Array
::value('id', $input);
860 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
861 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
867 $clause[] = "trxn_id = %1";
868 $input[1] = array($trxn_id, 'String');
872 $clause[] = "invoice_id = %2";
873 $input[2] = array($invoice_id, 'String');
876 if (empty($clause)) {
880 $clause = implode(' OR ', $clause);
882 $clause = "( $clause ) AND id != %3";
883 $input[3] = array($id, 'Integer');
886 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
887 $dao = CRM_Core_DAO
::executeQuery($query, $input);
889 while ($dao->fetch()) {
890 $duplicates[] = $dao->id
;
897 * Takes an associative array and creates a contribution_product object
899 * the function extract all the params it needs to initialize the create a
900 * contribution_product object. the params array could contain additional unused name/value
903 * @param array $params
904 * (reference) an assoc array of name/value pairs.
906 * @return CRM_Contribute_DAO_ContributionProduct
909 public static function addPremium(&$params) {
910 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
911 $contributionProduct->copyValues($params);
912 return $contributionProduct->save();
916 * Get list of contribution fields for profile
917 * For now we only allow custom contribution fields to be in
920 * @param bool $addExtraFields
921 * True if special fields needs to be added.
924 * the list of contribution fields
927 public static function getContributionFields($addExtraFields = TRUE) {
928 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
929 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
931 if ($addExtraFields) {
932 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
935 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
937 foreach ($contributionFields as $key => $var) {
938 if ($key == 'contribution_contact_id') {
941 elseif ($key == 'contribution_campaign_id') {
942 $var['title'] = ts('Campaign');
944 $fields[$key] = $var;
947 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
952 * Add extra fields specific to contribtion
956 public static function getSpecialContributionFields() {
957 $extraFields = array(
958 'contribution_soft_credit_name' => array(
959 'name' => 'contribution_soft_credit_name',
960 'title' => 'Soft Credit Name',
961 'headerPattern' => '/^soft_credit_name$/i',
962 'where' => 'civicrm_contact_d.display_name',
964 'contribution_soft_credit_email' => array(
965 'name' => 'contribution_soft_credit_email',
966 'title' => 'Soft Credit Email',
967 'headerPattern' => '/^soft_credit_email$/i',
968 'where' => 'soft_email.email',
970 'contribution_soft_credit_phone' => array(
971 'name' => 'contribution_soft_credit_phone',
972 'title' => 'Soft Credit Phone',
973 'headerPattern' => '/^soft_credit_phone$/i',
974 'where' => 'soft_phone.phone',
976 'contribution_soft_credit_contact_id' => array(
977 'name' => 'contribution_soft_credit_contact_id',
978 'title' => 'Soft Credit Contact ID',
979 'headerPattern' => '/^soft_credit_contact_id$/i',
980 'where' => 'civicrm_contribution_soft.contact_id',
992 public static function getCurrentandGoalAmount($pageID) {
994 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
995 FROM civicrm_contribution_page p,
996 civicrm_contribution c
997 WHERE p.id = c.contribution_page_id
999 AND c.cancel_date is null
1003 $config = CRM_Core_Config
::singleton();
1004 $params = array(1 => array($pageID, 'Integer'));
1005 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1007 if ($dao->fetch()) {
1008 return array($dao->goal
, $dao->total
);
1011 return array(NULL, NULL);
1016 * Get list of contribution In Honor of contact Ids
1018 * @param int $honorId
1019 * In Honor of Contact ID.
1022 * list of contribution fields
1026 public static function getHonorContacts($honorId) {
1028 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1029 $honorDAO->contact_id
= $honorId;
1032 $type = CRM_Contribute_PseudoConstant
::financialType();
1034 while ($honorDAO->fetch()) {
1035 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1036 $contributionDAO->id
= $honorDAO->contribution_id
;
1038 if ($contributionDAO->find(TRUE)) {
1039 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1040 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1041 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1042 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1043 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1044 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1045 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1046 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1047 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1055 * Get the sort name of a contact for a particular contribution
1058 * Id of the contribution.
1060 * @return null|string
1061 * sort name of the contact if found
1064 public static function sortName($id) {
1065 $id = CRM_Utils_Type
::escape($id, 'Integer');
1068 SELECT civicrm_contact.sort_name
1069 FROM civicrm_contribution, civicrm_contact
1070 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1071 AND civicrm_contribution.id = {$id}
1073 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1077 * @param int $contactID
1081 public static function annual($contactID) {
1082 if (is_array($contactID)) {
1083 $contactIDs = implode(',', $contactID);
1086 $contactIDs = $contactID;
1089 $config = CRM_Core_Config
::singleton();
1090 $startDate = $endDate = NULL;
1092 $currentMonth = date('m');
1093 $currentDay = date('d');
1094 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1095 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1096 (int ) $config->fiscalYearStart
['d'] > $currentDay
1099 $year = date('Y') - 1;
1104 $nextYear = $year +
1;
1106 if ($config->fiscalYearStart
) {
1107 if ($config->fiscalYearStart
['M'] < 10) {
1108 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1110 if ($config->fiscalYearStart
['d'] < 10) {
1111 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1113 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1118 $startDate = "$year$monthDay";
1119 $endDate = "$nextYear$monthDay";
1122 SELECT count(*) as count,
1123 sum(total_amount) as amount,
1124 avg(total_amount) as average,
1126 FROM civicrm_contribution b
1127 WHERE b.contact_id IN ( $contactIDs )
1128 AND b.contribution_status_id = 1
1130 AND b.receive_date >= $startDate
1131 AND b.receive_date < $endDate
1134 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1136 $amount = $average = array();
1137 while ($dao->fetch()) {
1138 if ($dao->count
> 0 && $dao->amount
> 0) {
1139 $count +
= $dao->count
;
1140 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1141 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1147 implode(', ', $amount),
1148 implode(', ', $average),
1151 return array(0, 0, 0);
1155 * Check if there is a contribution with the params passed in.
1156 * Used for trxn_id,invoice_id and contribution_id
1158 * @param array $params
1159 * An assoc array of name/value pairs.
1162 * contribution id if success else NULL
1165 public static function checkDuplicateIds($params) {
1166 $dao = new CRM_Contribute_DAO_Contribution();
1170 foreach ($params as $k => $v) {
1172 $clause[] = "$k = '$v'";
1175 $clause = implode(' AND ', $clause);
1176 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1177 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1179 while ($dao->fetch()) {
1187 * Get the contribution details for component export
1189 * @param int $exportMode
1191 * @param string $componentIds
1199 public static function getContributionDetails($exportMode, $componentIds) {
1200 $paymentDetails = array();
1201 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1203 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1204 $componentSelect = " civicrm_participant_payment.participant_id id";
1205 $additionalClause = "
1206 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1207 AND civicrm_participant_payment.participant_id {$componentClause} )
1210 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1211 $componentSelect = " civicrm_membership_payment.membership_id id";
1212 $additionalClause = "
1213 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1214 AND civicrm_membership_payment.membership_id {$componentClause} )
1217 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1218 $componentSelect = " civicrm_pledge_payment.id id";
1219 $additionalClause = "
1220 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1221 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1225 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1226 trxn_id, {$componentSelect}
1227 FROM civicrm_contribution
1228 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1229 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1230 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1231 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1232 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1233 AND option_group_contribution_status.id = contribution_status.option_group_id )
1237 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1239 while ($dao->fetch()) {
1240 $paymentDetails[$dao->id
] = array(
1241 'total_amount' => $dao->total_amount
,
1242 'contribution_status' => $dao->status
,
1243 'receive_date' => $dao->receive_date
,
1244 'pay_instru' => $dao->payment_instrument
,
1245 'trxn_id' => $dao->trxn_id
,
1249 return $paymentDetails;
1253 * Create address associated with contribution record.
1255 * @param array $params
1256 * @param int $billingLocationTypeID
1262 public static function createAddress(&$params, $billingLocationTypeID) {
1263 $billingFields = array(
1266 'state_province_id',
1271 //build address array
1272 $addressParams = array();
1273 $addressParams['location_type_id'] = $billingLocationTypeID;
1274 $addressParams['is_billing'] = 1;
1276 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1277 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1278 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1279 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1281 foreach ($billingFields as $value) {
1282 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1285 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1287 return $address->id
;
1291 * Delete billing address record related contribution
1293 * @param int $contributionId
1294 * @param int $contactId
1298 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1300 $contactJoin = NULL;
1302 if ($contributionId) {
1303 $clauses[] = "cc.id = {$contributionId}";
1307 $clauses[] = "cco.id = {$contactId}";
1308 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1311 if (empty($clauses)) {
1312 CRM_Core_Error
::fatal();
1315 $condition = implode(' OR ', $clauses);
1319 FROM civicrm_address ca
1320 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1324 $dao = CRM_Core_DAO
::executeQuery($query);
1326 while ($dao->fetch()) {
1327 $params = array('id' => $dao->id
);
1328 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1333 * This function check online pending contribution associated w/
1334 * Online Event Registration or Online Membership signup.
1336 * @param int $componentId
1337 * Participant/membership id.
1338 * @param string $componentName
1342 * pending contribution id.
1345 public static function checkOnlinePendingContribution($componentId, $componentName) {
1346 $contributionId = NULL;
1347 if (!$componentId ||
1348 !in_array($componentName, array('Event', 'Membership'))
1350 return $contributionId;
1353 if ($componentName == 'Event') {
1354 $idName = 'participant_id';
1355 $componentTable = 'civicrm_participant';
1356 $paymentTable = 'civicrm_participant_payment';
1357 $source = ts('Online Event Registration');
1360 if ($componentName == 'Membership') {
1361 $idName = 'membership_id';
1362 $componentTable = 'civicrm_membership';
1363 $paymentTable = 'civicrm_membership_payment';
1364 $source = ts('Online Contribution');
1367 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1370 SELECT component.id as {$idName},
1371 componentPayment.contribution_id as contribution_id,
1372 contribution.source source,
1373 contribution.contribution_status_id as contribution_status_id,
1374 contribution.is_pay_later as is_pay_later
1375 FROM $componentTable component
1376 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1377 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1378 WHERE component.id = {$componentId}";
1380 $dao = CRM_Core_DAO
::executeQuery($query);
1382 while ($dao->fetch()) {
1383 if ($dao->contribution_id
&&
1384 $dao->is_pay_later
&&
1385 $dao->contribution_status_id
== $pendingStatusId &&
1386 strpos($dao->source
, $source) !== FALSE
1388 $contributionId = $dao->contribution_id
;
1393 return $contributionId;
1397 * Update contribution as well as related objects.
1399 public static function transitionComponents($params, $processContributionObject = FALSE) {
1400 // get minimum required values.
1401 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1402 $componentId = CRM_Utils_Array
::value('component_id', $params);
1403 $componentName = CRM_Utils_Array
::value('componentName', $params);
1404 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1405 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1407 // if we already processed contribution object pass previous status id.
1408 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1410 $updateResult = array();
1412 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1414 // we process only ( Completed, Cancelled, or Failed ) contributions.
1415 if (!$contributionId ||
1416 !in_array($contributionStatusId, array(
1417 array_search('Completed', $contributionStatuses),
1418 array_search('Cancelled', $contributionStatuses),
1419 array_search('Failed', $contributionStatuses),
1422 return $updateResult;
1425 if (!$componentName ||
!$componentId) {
1426 // get the related component details.
1427 $componentDetails = self
::getComponentDetails($contributionId);
1430 $componentDetails['contact_id'] = $contactId;
1431 $componentDetails['component'] = $componentName;
1433 if ($componentName == 'event') {
1434 $componentDetails['participant'] = $componentId;
1437 $componentDetails['membership'] = $componentId;
1441 if (!empty($componentDetails['contact_id'])) {
1442 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1448 // do check for required ids.
1449 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1450 return $updateResult;
1453 //now we are ready w/ required ids, start processing.
1455 $baseIPN = new CRM_Core_Payment_BaseIPN();
1457 $input = $ids = $objects = array();
1459 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1460 $ids['contribution'] = $contributionId;
1461 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1462 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1463 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1464 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1465 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1466 $ids['contributionRecur'] = NULL;
1467 $ids['contributionPage'] = NULL;
1469 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1470 CRM_Core_Error
::fatal();
1473 $memberships = &$objects['membership'];
1474 $participant = &$objects['participant'];
1475 $pledgePayment = &$objects['pledge_payment'];
1476 $contribution = &$objects['contribution'];
1478 if ($pledgePayment) {
1479 $pledgePaymentIDs = array();
1480 foreach ($pledgePayment as $key => $object) {
1481 $pledgePaymentIDs[] = $object->id
;
1483 $pledgeID = $pledgePayment[0]->pledge_id
;
1486 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1489 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1490 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1495 // we might want to process contribution object.
1496 $processContribution = FALSE;
1497 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1498 if (is_array($memberships)) {
1499 foreach ($memberships as $membership) {
1501 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1502 $membership->save();
1504 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1505 if ($processContributionObject) {
1506 $processContribution = TRUE;
1513 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1514 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1516 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1517 if ($processContributionObject) {
1518 $processContribution = TRUE;
1522 if ($pledgePayment) {
1523 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1525 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1526 if ($processContributionObject) {
1527 $processContribution = TRUE;
1531 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1532 if (is_array($memberships)) {
1533 foreach ($memberships as $membership) {
1535 $membership->status_id
= array_search('Expired', $membershipStatuses);
1536 $membership->save();
1538 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1539 if ($processContributionObject) {
1540 $processContribution = TRUE;
1546 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1547 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1549 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1550 if ($processContributionObject) {
1551 $processContribution = TRUE;
1555 if ($pledgePayment) {
1556 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1558 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1559 if ($processContributionObject) {
1560 $processContribution = TRUE;
1564 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1566 // only pending contribution related object processed.
1567 if ($previousContriStatusId &&
1568 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1570 // this is case when we already processed contribution object.
1571 return $updateResult;
1573 elseif (!$previousContriStatusId &&
1574 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1576 // this is case when we are going to process contribution object later.
1577 return $updateResult;
1580 if (is_array($memberships)) {
1581 foreach ($memberships as $membership) {
1586 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1587 $membership->membership_type_id
,
1588 $membership->is_test
, $membership->id
1591 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1592 // this picks up membership type changes during renewals
1594 SELECT membership_type_id
1595 FROM civicrm_membership_log
1596 WHERE membership_id=$membership->id
1599 $dao = new CRM_Core_DAO
;
1601 if ($dao->fetch()) {
1602 if (!empty($dao->membership_type_id
)) {
1603 $membership->membership_type_id
= $dao->membership_type_id
;
1604 $membership->save();
1607 // else fall back to using current membership type
1610 // Figure out number of terms
1612 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1613 foreach ($lineitems as $lineitem) {
1614 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1615 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1617 // in case membership_num_terms comes through as null or zero
1618 $numterms = $numterms >= 1 ?
$numterms : 1;
1623 // CRM-15735-to update the membership status as per the contribution receive date
1624 if (!empty($params['receive_date'])) {
1625 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1626 $membership->end_date
,
1627 $membership->join_date
,
1628 $params['receive_date'],
1630 $membership->membership_type_id
,
1633 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1634 $membership->save();
1637 if ($currentMembership) {
1638 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1639 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1640 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1643 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1646 //get the status for membership.
1647 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1649 $dates['join_date'],
1652 $membership->membership_type_id
,
1656 $formattedParams = array(
1657 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1658 array_search('Current', $membershipStatuses)
1660 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1661 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1662 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1665 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1667 $membership->copyValues($formattedParams);
1668 $membership->save();
1670 //updating the membership log
1671 $membershipLog = array();
1672 $membershipLog = $formattedParams;
1673 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1674 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1676 $membershipLog['start_date'] = $logStartDate;
1677 $membershipLog['membership_id'] = $membership->id
;
1678 $membershipLog['modified_id'] = $membership->contact_id
;
1679 $membershipLog['modified_date'] = date('Ymd');
1680 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1682 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1684 //update related Memberships.
1685 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1687 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1690 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1691 if ($processContributionObject) {
1692 $processContribution = TRUE;
1695 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1701 $updatedStatusId = array_search('Registered', $participantStatuses);
1702 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1704 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1705 if ($processContributionObject) {
1706 $processContribution = TRUE;
1710 if ($pledgePayment) {
1711 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1713 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1714 if ($processContributionObject) {
1715 $processContribution = TRUE;
1720 // process contribution object.
1721 if ($processContribution) {
1722 $contributionParams = array();
1729 'payment_instrument_id',
1732 'financial_type_id',
1733 'contribution_status_id',
1734 'non_deductible_amount',
1738 foreach ($fields as $field) {
1739 if (empty($params[$field])) {
1742 $contributionParams[$field] = $params[$field];
1745 $ids = array('contribution' => $contributionId);
1746 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1749 return $updateResult;
1753 * Returns all contribution related object ids.
1755 public static function getComponentDetails($contributionId) {
1756 $componentDetails = $pledgePayment = array();
1757 if (!$contributionId) {
1758 return $componentDetails;
1762 SELECT c.id as contribution_id,
1763 c.contact_id as contact_id,
1764 mp.membership_id as membership_id,
1765 m.membership_type_id as membership_type_id,
1766 pp.participant_id as participant_id,
1767 p.event_id as event_id,
1768 pgp.id as pledge_payment_id
1769 FROM civicrm_contribution c
1770 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1771 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1772 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1773 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1774 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1775 WHERE c.id = $contributionId";
1777 $dao = CRM_Core_DAO
::executeQuery($query);
1778 $componentDetails = array();
1780 while ($dao->fetch()) {
1781 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1782 $componentDetails['contact_id'] = $dao->contact_id
;
1783 if ($dao->event_id
) {
1784 $componentDetails['event'] = $dao->event_id
;
1786 if ($dao->participant_id
) {
1787 $componentDetails['participant'] = $dao->participant_id
;
1789 if ($dao->membership_id
) {
1790 if (!isset($componentDetails['membership'])) {
1791 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1793 $componentDetails['membership'][] = $dao->membership_id
;
1794 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1796 if ($dao->pledge_payment_id
) {
1797 $pledgePayment[] = $dao->pledge_payment_id
;
1801 if ($pledgePayment) {
1802 $componentDetails['pledge_payment'] = $pledgePayment;
1805 return $componentDetails;
1809 * @param int $contactId
1810 * @param bool $includeSoftCredit
1812 * @return null|string
1814 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1819 $contactContributionsSQL = "
1820 SELECT contribution.id AS id
1821 FROM civicrm_contribution contribution
1822 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1824 $contactSoftCreditContributionsSQL = "
1825 SELECT contribution.id
1826 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1827 ON ( contribution.id = softContribution.contribution_id )
1828 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1829 $query = "SELECT count( x.id ) count FROM ( ";
1830 $query .= $contactContributionsSQL;
1832 if ($includeSoftCredit) {
1833 $query .= " UNION ";
1834 $query .= $contactSoftCreditContributionsSQL;
1839 return CRM_Core_DAO
::singleValueQuery($query);
1843 * Get individual id for onbehalf contribution
1845 * @param int $contributionId
1847 * @param int $contributorId
1851 * containing organization id and individual id
1853 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1857 if (!$contributionId) {
1861 // fetch contributor id if null
1862 if (!$contributorId) {
1863 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1864 $contributionId, 'contact_id'
1868 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1869 $activityTypeId = array_search('Contribution', $activityTypeIds);
1871 if ($activityTypeId && $contributorId) {
1873 SELECT civicrm_activity_contact.contact_id
1874 FROM civicrm_activity_contact
1875 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1876 WHERE civicrm_activity.activity_type_id = %1
1877 AND civicrm_activity.source_record_id = %2
1878 AND civicrm_activity_contact.record_type_id = %3
1881 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1882 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1885 1 => array($activityTypeId, 'Integer'),
1886 2 => array($contributionId, 'Integer'),
1887 3 => array($sourceID, 'Integer'),
1890 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1892 // for on behalf contribution source is individual and contributor is organization
1893 if ($sourceContactId && $sourceContactId != $contributorId) {
1894 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1895 // get rel type id for employee of relation
1896 foreach ($relationshipTypeIds as $id => $typeVals) {
1897 if ($typeVals['name_a_b'] == 'Employee of') {
1898 $relationshipTypeId = $id;
1903 $rel = new CRM_Contact_DAO_Relationship();
1904 $rel->relationship_type_id
= $relationshipTypeId;
1905 $rel->contact_id_a
= $sourceContactId;
1906 $rel->contact_id_b
= $contributorId;
1907 if ($rel->find(TRUE)) {
1908 $ids['individual_id'] = $rel->contact_id_a
;
1909 $ids['organization_id'] = $rel->contact_id_b
;
1921 public static function getContributionDates() {
1922 $config = CRM_Core_Config
::singleton();
1923 $currentMonth = date('m');
1924 $currentDay = date('d');
1925 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1926 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1927 (int ) $config->fiscalYearStart
['d'] > $currentDay
1930 $year = date('Y') - 1;
1935 $year = array('Y' => $year);
1936 $yearDate = $config->fiscalYearStart
;
1937 $yearDate = array_merge($year, $yearDate);
1938 $yearDate = CRM_Utils_Date
::format($yearDate);
1940 $monthDate = date('Ym') . '01';
1946 'yearDate' => $yearDate,
1947 'monthDate' => $monthDate,
1952 * Load objects relations to contribution object
1953 * Objects are stored in the $_relatedObjects property
1954 * In the first instance we are just moving functionality from BASEIpn -
1955 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1957 * Note that the unit test for the BaseIPN class tests this function
1959 * @param array $input
1960 * Input as delivered from Payment Processor.
1962 * Ids as Loaded by Payment Processor.
1963 * @param bool $required
1964 * Is Payment processor / contribution page required.
1965 * @param bool $loadAll
1966 * Load all related objects - even where id not passed in? (allows API to call this).
1971 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1973 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
1974 if (empty($ids['contact']) && isset($this->contact_id
)) {
1975 $ids['contact'] = $this->contact_id
;
1978 if (empty($this->_component
)) {
1979 if (!empty($ids['event'])) {
1980 $this->_component
= 'event';
1983 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1986 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1987 $contributionType = new CRM_Financial_BAO_FinancialType();
1988 $contributionType->id
= $this->financial_type_id
;
1989 if (!$contributionType->find(TRUE)) {
1990 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1992 if (!empty($ids['contact'])) {
1993 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1994 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1995 $this->_relatedObjects
['contact']->find(TRUE);
1997 $this->_relatedObjects
['contributionType'] = $contributionType;
1999 if ($this->_component
== 'contribute') {
2000 // retrieve the other optional objects first so
2001 // stuff down the line can use this info and do things
2003 //in any case get the memberships associated with the contribution
2004 //because we now support multiple memberships w/ price set
2005 // see if there are any other memberships to be considered for same contribution.
2007 SELECT membership_id
2008 FROM civicrm_membership_payment
2009 WHERE contribution_id = %1 ";
2010 $params = array(1 => array($this->id
, 'Integer'));
2012 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2013 while ($dao->fetch()) {
2014 if ($dao->membership_id
) {
2015 if (!is_array($ids['membership'])) {
2016 $ids['membership'] = array();
2018 $ids['membership'][] = $dao->membership_id
;
2022 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2023 foreach ($ids['membership'] as $id) {
2025 $membership = new CRM_Member_BAO_Membership();
2026 $membership->id
= $id;
2027 if (!$membership->find(TRUE)) {
2028 throw new Exception("Could not find membership record: $id");
2030 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
2031 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
2032 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
2033 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
2034 $membership->free();
2039 if (!empty($ids['pledge_payment'])) {
2041 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2042 if (empty($paymentID)) {
2045 $payment = new CRM_Pledge_BAO_PledgePayment();
2046 $payment->id
= $paymentID;
2047 if (!$payment->find(TRUE)) {
2048 throw new Exception("Could not find pledge payment record: " . $paymentID);
2050 $this->_relatedObjects
['pledge_payment'][] = $payment;
2054 if (!empty($ids['contributionRecur'])) {
2055 $recur = new CRM_Contribute_BAO_ContributionRecur();
2056 $recur->id
= $ids['contributionRecur'];
2057 if (!$recur->find(TRUE)) {
2058 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2060 $this->_relatedObjects
['contributionRecur'] = &$recur;
2061 //get payment processor id from recur object.
2062 $paymentProcessorID = $recur->payment_processor_id
;
2064 //for normal contribution get the payment processor id.
2065 if (!$paymentProcessorID) {
2066 if ($this->contribution_page_id
) {
2067 // get the payment processor id from contribution page
2068 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2069 $this->contribution_page_id
,
2073 //fail to load payment processor id.
2074 elseif (empty($ids['pledge_payment'])) {
2075 $loadObjectSuccess = TRUE;
2077 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2079 return $loadObjectSuccess;
2084 // we are in event mode
2085 // make sure event exists and is valid
2086 $event = new CRM_Event_BAO_Event();
2087 $event->id
= $ids['event'];
2088 if ($ids['event'] &&
2091 throw new Exception("Could not find event: " . $ids['event']);
2094 $this->_relatedObjects
['event'] = &$event;
2096 $participant = new CRM_Event_BAO_Participant();
2097 $participant->id
= $ids['participant'];
2098 if ($ids['participant'] &&
2099 !$participant->find(TRUE)
2101 throw new Exception("Could not find participant: " . $ids['participant']);
2103 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2105 $this->_relatedObjects
['participant'] = &$participant;
2107 if (!$paymentProcessorID) {
2108 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2112 if ($paymentProcessorID) {
2113 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2114 $this->is_test ?
'test' : 'live'
2116 $ids['paymentProcessor'] = $paymentProcessorID;
2117 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2119 elseif ($required) {
2120 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2127 * Create array of message information - ie. return html version, txt version, to field
2129 * @param array $input
2130 * Incoming information.
2131 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2132 * just check presence of recur object but maintaining legacy approach
2135 * IDs of related objects.
2136 * @param array $values
2137 * Any values that may have already been compiled by calling process.
2138 * This is augmented by values 'gathered' by gatherMessageValues
2139 * @param bool $recur
2140 * @param bool $returnMessageText
2141 * Distinguishes between whether to send message or return.
2142 * message text. We are working towards this function ALWAYS returning message text & calling
2143 * function doing emails / pdfs with it
2149 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2150 if (empty($this->_relatedObjects
)) {
2151 $this->loadRelatedObjects($input, $ids);
2153 if (empty($this->_component
)) {
2154 $this->_component
= CRM_Utils_Array
::value('component', $input);
2157 //not really sure what params might be passed in but lets merge em into values
2158 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2159 $template = CRM_Core_Smarty
::singleton();
2160 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2161 //what does recur 'mean here - to do with payment processor return functionality but
2162 // what is the importance
2163 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2164 $paymentObject = &CRM_Core_Payment
::singleton(
2165 $this->is_test ?
'test' : 'live',
2166 $this->_relatedObjects
['paymentProcessor']
2169 $entityID = $entity = NULL;
2170 if (isset($ids['contribution'])) {
2171 $entity = 'contribution';
2172 $entityID = $ids['contribution'];
2174 if (!empty($ids['membership'])) {
2175 //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
2176 // 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
2177 // line having loaded an array
2178 $ids['membership'] = (array) $ids['membership'];
2179 $entity = 'membership';
2180 $entityID = $ids['membership'][0];
2183 $url = $paymentObject->subscriptionURL($entityID, $entity);
2184 $template->assign('cancelSubscriptionUrl', $url);
2186 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2187 $template->assign('updateSubscriptionBillingUrl', $url);
2189 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2190 $template->assign('updateSubscriptionUrl', $url);
2192 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2193 //direct mode showing billing block, so use directIPN for temporary
2194 $template->assign('contributeMode', 'directIPN');
2197 // todo remove strtolower - check consistency
2198 if (strtolower($this->_component
) == 'event') {
2199 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2200 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2204 $values['contribution_id'] = $this->id
;
2205 if (!empty($ids['related_contact'])) {
2206 $values['related_contact'] = $ids['related_contact'];
2207 if (isset($ids['onbehalf_dupe_alert'])) {
2208 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2210 $entityBlock = array(
2211 'contact_id' => $ids['contact'],
2212 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2213 'Home', 'id', 'name'
2216 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2217 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2220 if ($this->is_test
) {
2223 if (!empty($this->_relatedObjects
['membership'])) {
2224 foreach ($this->_relatedObjects
['membership'] as $membership) {
2225 if ($membership->id
) {
2226 $values['isMembership'] = TRUE;
2228 // need to set the membership values here
2229 $template->assign('membership_assign', 1);
2230 $template->assign('membership_name',
2231 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2233 $template->assign('mem_start_date', $membership->start_date
);
2234 $template->assign('mem_join_date', $membership->join_date
);
2235 $template->assign('mem_end_date', $membership->end_date
);
2236 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2237 $template->assign('mem_status', $membership_status);
2238 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2239 $template->assign('is_pay_later', 1);
2242 // if separate payment there are two contributions recorded and the
2243 // admin will need to send a receipt for each of them separately.
2244 // we dont link the two in the db (but can potentially infer it if needed)
2245 $template->assign('is_separate_payment', 0);
2247 if ($recur && $paymentObject) {
2248 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2249 $template->assign('cancelSubscriptionUrl', $url);
2250 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2251 $template->assign('updateSubscriptionBillingUrl', $url);
2252 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2253 $template->assign('updateSubscriptionUrl', $url);
2256 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2259 // otherwise if its about sending emails, continue sending without return, as we
2260 // don't want to exit the loop.
2265 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2271 * Gather values for contribution mail - this function has been created
2272 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2273 * Values related to the contribution in question are gathered
2275 * @param array $input
2276 * Input into function (probably from payment processor).
2277 * @param array $values
2279 * The set of ids related to the input.
2283 public function _gatherMessageValues($input, &$values, $ids = array()) {
2284 // set display address of contributor
2285 if ($this->address_id
) {
2286 $addressParams = array('id' => $this->address_id
);
2287 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2288 $addressDetails = array_values($addressDetails);
2289 $values['address'] = $addressDetails[0]['display'];
2291 if ($this->_component
== 'contribute') {
2292 if (isset($this->contribution_page_id
)) {
2293 CRM_Contribute_BAO_ContributionPage
::setValues(
2294 $this->contribution_page_id
,
2297 if ($this->contribution_page_id
) {
2298 // CRM-8254 - override default currency if applicable
2299 $config = CRM_Core_Config
::singleton();
2300 $config->defaultCurrency
= CRM_Utils_Array
::value(
2303 $config->defaultCurrency
2307 // no contribution page -probably back office
2309 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2310 $values['is_email_receipt'] = 1;
2311 $values['title'] = 'Contribution';
2313 // set lineItem for contribution
2315 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2316 if (!empty($lineItem)) {
2317 $itemId = key($lineItem);
2318 foreach ($lineItem as &$eachItem) {
2319 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2320 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2321 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2322 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2325 $values['lineItem'][0] = $lineItem;
2326 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2330 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2334 // if this is onbehalf of contribution then set related contact
2335 if (!empty($relatedContact['individual_id'])) {
2336 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2341 $eventParams = array(
2342 'id' => $this->_relatedObjects
['event']->id
,
2344 $values['event'] = array();
2346 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2348 //get location details
2349 $locationParams = array(
2350 'entity_id' => $this->_relatedObjects
['event']->id
,
2351 'entity_table' => 'civicrm_event',
2353 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2355 $ufJoinParams = array(
2356 'entity_table' => 'civicrm_event',
2357 'entity_id' => $ids['event'],
2358 'module' => 'CiviEvent',
2361 list($custom_pre_id,
2363 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2365 $values['custom_pre_id'] = $custom_pre_id;
2366 $values['custom_post_id'] = $custom_post_ids;
2368 // set lineItem for event contribution
2370 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2371 if (!empty($participantIds)) {
2372 foreach ($participantIds as $pIDs) {
2373 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2374 if (!CRM_Utils_System
::isNull($lineItem)) {
2375 $values['lineItem'][] = $lineItem;
2386 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2387 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2388 * Note we send directly from this function in some cases because it is only partly refactored
2389 * Don't call this function directly as the signature will change
2393 * @param CRM_Core_SMARTY $template
2394 * @param bool $recur
2395 * @param bool $returnMessageText
2399 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2400 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2401 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2402 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2403 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2404 $template->assign('useForMember', TRUE);
2406 //assign honor information to receipt message
2407 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2409 if (isset($softRecord['soft_credit'])) {
2410 //if id of contribution page is present
2411 if (!empty($values['id'])) {
2412 $values['honor'] = array(
2413 'honor_profile_values' => array(),
2414 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2415 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2417 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2419 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2420 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2423 //offline contribution
2424 $softCreditTypes = $softCredits = array();
2425 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2426 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2427 $softCredits[$key] = array(
2428 'Name' => $softCredit['contact_name'],
2429 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2432 $template->assign('softCreditTypes', $softCreditTypes);
2433 $template->assign('softCredits', $softCredits);
2437 $dao = new CRM_Contribute_DAO_ContributionProduct();
2438 $dao->contribution_id
= $this->id
;
2439 if ($dao->find(TRUE)) {
2440 $premiumId = $dao->product_id
;
2441 $template->assign('option', $dao->product_option
);
2443 $productDAO = new CRM_Contribute_DAO_Product();
2444 $productDAO->id
= $premiumId;
2445 $productDAO->find(TRUE);
2446 $template->assign('selectPremium', TRUE);
2447 $template->assign('product_name', $productDAO->name
);
2448 $template->assign('price', $productDAO->price
);
2449 $template->assign('sku', $productDAO->sku
);
2451 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2452 $amount = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2453 if (empty($amount) && isset($this->total_amount
)) {
2454 $amount = $this->total_amount
;
2456 $template->assign('amount', $amount);
2457 // add the new contribution values
2458 if (strtolower($this->_component
) == 'contribute') {
2460 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2461 $softDAO->contribution_id
= $this->id
;
2462 if ($softDAO->find(TRUE)) {
2463 $template->assign('pcpBlock', TRUE);
2464 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2465 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2466 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2468 //assign the pcp page title for email subject
2469 $pcpDAO = new CRM_PCP_DAO_PCP();
2470 $pcpDAO->id
= $softDAO->pcp_id
;
2471 if ($pcpDAO->find(TRUE)) {
2472 $template->assign('title', $pcpDAO->title
);
2477 if ($this->financial_type_id
) {
2478 $values['financial_type_id'] = $this->financial_type_id
;
2482 $template->assign('trxn_id', $this->trxn_id
);
2483 $template->assign('receive_date',
2484 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2486 $template->assign('contributeMode', 'notify');
2487 $template->assign('action', $this->is_test ?
1024 : 1);
2488 $template->assign('receipt_text',
2489 CRM_Utils_Array
::value('receipt_text',
2493 $template->assign('is_monetary', 1);
2494 $template->assign('is_recur', (bool) $recur);
2495 $template->assign('currency', $this->currency
);
2496 $template->assign('address', CRM_Utils_Address
::format($input));
2497 if ($this->_component
== 'event') {
2498 $template->assign('title', $values['event']['title']);
2499 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2500 $viewRoles = array();
2501 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2502 $viewRoles[] = $participantRoles[$v];
2504 $values['event']['participant_role'] = implode(', ', $viewRoles);
2505 $template->assign('event', $values['event']);
2506 $template->assign('location', $values['location']);
2507 $template->assign('customPre', $values['custom_pre_id']);
2508 $template->assign('customPost', $values['custom_post_id']);
2511 if ($this->_relatedObjects
['participant']->is_test
) {
2515 $values['params'] = array();
2516 //to get email of primary participant.
2517 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2518 $primaryAmount[] = array(
2519 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2520 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2522 //build an array of cId/pId of participants
2523 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2524 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2525 //send receipt to additional participant if exists
2526 if (count($additionalIDs)) {
2527 $template->assign('isPrimary', 0);
2528 $template->assign('customProfile', NULL);
2529 //set additionalParticipant true
2530 $values['params']['additionalParticipant'] = TRUE;
2531 foreach ($additionalIDs as $pId => $cId) {
2533 //to change the status pending to completed
2534 $additional = new CRM_Event_DAO_Participant();
2535 $additional->id
= $pId;
2536 $additional->contact_id
= $cId;
2537 $additional->find(TRUE);
2538 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2539 $additional->status_id
= 1;
2540 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2541 //if additional participant dont have email
2543 if (!$additionalParticipantInfo) {
2544 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2546 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2547 $primaryAmount[] = array(
2548 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2549 'amount' => $additional->fee_amount
,
2551 $additional->save();
2552 $additional->free();
2553 $template->assign('amount', $amount);
2554 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2558 //build an array of custom profile and assigning it to template
2559 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2561 if (count($customProfile)) {
2562 $template->assign('customProfile', $customProfile);
2565 // for primary contact
2566 $values['params']['additionalParticipant'] = FALSE;
2567 $template->assign('isPrimary', 1);
2568 $template->assign('amount', $primaryAmount);
2569 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2570 if ($this->payment_instrument_id
) {
2571 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2572 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2574 // carry paylater, since we did not created billing,
2575 // so need to pull email from primary location, CRM-4395
2576 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2582 * Check whether payment processor supports
2583 * cancellation of contribution subscription
2585 * @param int $contributionId
2588 * @param bool $isNotCancelled
2593 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2594 $cacheKeyString = "$contributionId";
2595 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2597 static $supportsCancel = array();
2599 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2600 $supportsCancel[$cacheKeyString] = FALSE;
2601 $isCancelled = FALSE;
2603 if ($isNotCancelled) {
2604 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2607 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2608 if (!empty($paymentObject)) {
2609 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2612 return $supportsCancel[$cacheKeyString];
2616 * Check whether subscription is already cancelled
2618 * @param int $contributionId
2622 * contribution status
2625 public static function isSubscriptionCancelled($contributionId) {
2627 SELECT cr.contribution_status_id
2628 FROM civicrm_contribution_recur cr
2629 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2630 WHERE con.id = %1 LIMIT 1";
2631 $params = array(1 => array($contributionId, 'Integer'));
2632 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2633 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2634 if ($status == 'Cancelled') {
2641 * Create all financial accounts entry
2643 * @param array $params
2644 * Contribution object, line item array and params for trxn.
2647 * @param array $financialTrxnValues
2649 * @return null|object
2652 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2653 $skipRecords = $update = $return = $isRelatedId = FALSE;
2655 $additionalParticipantId = array();
2656 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2658 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2659 $entityId = $params['participant_id'];
2660 $entityTable = 'civicrm_participant';
2661 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2663 elseif (!empty($params['membership_id'])) {
2664 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2665 // are created off one contribution should be handled elsewhere
2666 $entityId = $params['membership_id'];
2667 $entityTable = 'civicrm_membership';
2670 $entityId = $params['contribution']->id
;
2671 $entityTable = 'civicrm_contribution';
2674 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2675 $isRelatedId = TRUE;
2678 $entityID[] = $entityId;
2679 if (!empty($additionalParticipantId)) {
2680 $entityID +
= $additionalParticipantId;
2682 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2683 if (empty($params['prevContribution'])) {
2690 $statusId = $params['contribution']->contribution_status_id
;
2691 // CRM-13964 partial payment
2692 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2693 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2695 $partialAmtPay = $params['partial_amount_pay'];
2696 $partialAmtTotal = $params['partial_payment_total'];
2698 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2699 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2700 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2701 $params['total_amount'] = $partialAmtPay;
2703 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2704 if (empty($balanceTrxnInfo['trxn_id'])) {
2705 // create new balance transaction record
2706 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2707 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2709 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2710 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2711 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2712 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2713 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2714 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2715 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2716 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2717 $balanceTrxnParams['status_id'] = $statusId;
2718 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2719 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2720 if (!empty($params['payment_processor'])) {
2721 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2723 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2727 // build line item array if its not set in $params
2728 if (empty($params['line_item']) ||
$additionalParticipantId) {
2729 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2732 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2733 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)
2735 $skipRecords = TRUE;
2736 $pendingStatus = array(
2737 array_search('Pending', $contributionStatuses),
2738 array_search('In Progress', $contributionStatuses),
2740 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2741 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2742 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2744 elseif (!empty($params['payment_processor'])) {
2745 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2747 elseif (!empty($params['payment_instrument_id'])) {
2748 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2751 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2752 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2753 $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);
2756 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2757 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2758 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2761 //build financial transaction params
2762 $trxnParams = array(
2763 'contribution_id' => $params['contribution']->id
,
2764 'to_financial_account_id' => $params['to_financial_account_id'],
2765 'trxn_date' => date('YmdHis'),
2766 'total_amount' => $totalAmount,
2767 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2768 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2769 'currency' => $params['contribution']->currency
,
2770 'trxn_id' => $params['contribution']->trxn_id
,
2771 'status_id' => $statusId,
2772 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2773 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2776 if (!empty($params['payment_processor'])) {
2777 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2780 if (isset($fromFinancialAccountId)) {
2781 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2784 // consider external values passed for recording transaction entry
2785 if (!empty($financialTrxnValues)) {
2786 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2789 $params['trxnParams'] = $trxnParams;
2791 if (!empty($params['prevContribution'])) {
2792 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2793 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2794 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2795 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2796 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2799 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2800 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2801 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
2803 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2804 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2807 //if financial type is changed
2808 if (!empty($params['financial_type_id']) &&
2809 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
2811 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2812 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2813 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2814 if ($oldFinancialAccount != $newFinancialAccount) {
2815 $params['total_amount'] = 0;
2816 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2817 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2818 $params['prevContribution']->financial_type_id
, $relationTypeId);
2821 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2822 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2823 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2826 self
::updateFinancialAccounts($params, 'changeFinancialType');
2827 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2828 $params['financial_account_id'] = $newFinancialAccount;
2829 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2830 self
::updateFinancialAccounts($params);
2831 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2835 //Update contribution status
2836 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2837 if (!empty($params['contribution_status_id']) &&
2838 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2840 //Update Financial Records
2841 self
::updateFinancialAccounts($params, 'changedStatus');
2844 // change Payment Instrument for a Completed contribution
2845 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2846 // instrument is null and now new payment instrument is added along with the payment
2847 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2848 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2849 if (array_key_exists('payment_instrument_id', $params)) {
2850 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2851 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2852 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
2854 //check if status is changed from Pending to Completed
2855 // do not update payment instrument changes for Pending to Completed
2856 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2857 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
2859 // for all other statuses create new financial records
2860 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2861 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2862 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2865 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2866 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2867 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
2869 // for any other payment instrument changes create new financial records
2870 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2871 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2872 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2874 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2875 $params['contribution']->check_number
!= $params['prevContribution']->check_number
2877 // another special case when check number is changed, create new financial records
2878 // create financial trxn with negative amount
2879 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2880 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2881 // create financial trxn with positive amount
2882 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2883 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2884 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2888 //if Change contribution amount
2889 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2890 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2891 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2892 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2893 if (isset($totalAmount) &&
2894 $totalAmount != $params['prevContribution']->total_amount
2896 //Update Financial Records
2897 $params['trxnParams']['from_financial_account_id'] = NULL;
2898 self
::updateFinancialAccounts($params, 'changedAmount');
2903 // records finanical trxn and entity financial trxn
2904 // also make it available as return value
2905 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2906 $params['entity_id'] = $financialTxn->id
;
2909 // record line items and finacial items
2910 if (empty($params['skipLineItem'])) {
2911 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2914 // create batch entry if batch_id is passed
2915 if (!empty($params['batch_id'])) {
2916 $entityParams = array(
2917 'batch_id' => $params['batch_id'],
2918 'entity_table' => 'civicrm_financial_trxn',
2919 'entity_id' => $financialTxn->id
,
2921 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2924 // when a fee is charged
2925 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2926 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2929 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2930 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
2932 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2933 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2934 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2936 unset($params['line_item']);
2942 * Update all financial accounts entry
2944 * @param array $params
2945 * Contribution object, line item array and params for trxn.
2947 * @param string $context
2950 * @param null $skipTrxn
2954 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2955 $itemAmount = $trxnID = NULL;
2956 //get all the statuses
2957 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2958 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2959 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2960 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2961 && $context == 'changePaymentInstrument'
2965 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2966 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2968 if ($context == 'changedStatus') {
2969 //get all the statuses
2970 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2972 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2973 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2974 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
2976 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2978 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2979 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
2981 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2982 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2983 $params['trxnParams']['to_financial_account_id'] = NULL;
2984 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2986 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2987 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2988 $financialTypeID, $relationTypeId);
2990 $itemAmount = $params['trxnParams']['total_amount'];
2992 elseif ($context == 'changePaymentInstrument') {
2993 if ($params['trxnParams']['total_amount'] < 0) {
2994 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2995 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2996 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2997 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3001 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3002 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3005 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3006 $params['entity_id'] = $trxn->id
;
3008 if ($context == 'changedStatus') {
3009 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3010 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3011 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3013 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3014 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3016 $entityParams = array(
3017 'entity_table' => 'civicrm_financial_item',
3018 'financial_trxn_id' => $trxn->id
,
3020 if (empty($params['line_item'])) {
3022 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3023 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3024 // & this can be removed
3027 foreach ($params['line_item'] as $fieldId => $fields) {
3028 foreach ($fields as $fieldValueId => $fieldValues) {
3030 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3031 2 => array($fieldValues['id'], 'Integer'),
3033 CRM_Core_DAO
::executeQuery($query, $fparams);
3035 1 => array($fieldValues['id'], 'Integer'),
3037 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3038 while ($financialItem->fetch()) {
3039 $entityParams['entity_id'] = $financialItem->id
;
3040 $entityParams['amount'] = $financialItem->amount
;
3041 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3048 if ($context != 'changePaymentInstrument') {
3049 $itemParams['entity_table'] = 'civicrm_line_item';
3050 $trxnIds['id'] = $params['entity_id'];
3051 foreach ($params['line_item'] as $fieldId => $fields) {
3052 foreach ($fields as $fieldValueId => $fieldValues) {
3053 $prevParams['entity_id'] = $fieldValues['id'];
3054 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3056 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3057 if ($params['contribution']->receive_date
) {
3058 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3061 $financialAccount = $prevfinancialItem->financial_account_id
;
3062 if (!empty($params['financial_account_id'])) {
3063 $financialAccount = $params['financial_account_id'];
3066 $currency = $params['prevContribution']->currency
;
3067 if ($params['contribution']->currency
) {
3068 $currency = $params['contribution']->currency
;
3071 if (!empty($params['is_quick_config'])) {
3072 $amount = $itemAmount;
3074 $amount = $params['total_amount'];
3078 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3079 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3083 $amount = $diff * $fieldValues['line_total'];
3086 $itemParams = array(
3087 'transaction_date' => $receiveDate,
3088 'contact_id' => $params['prevContribution']->contact_id
,
3089 'currency' => $currency,
3090 'amount' => $amount,
3091 'description' => $prevfinancialItem->description
,
3092 'status_id' => $prevfinancialItem->status_id
,
3093 'financial_account_id' => $financialAccount,
3094 'entity_table' => 'civicrm_line_item',
3095 'entity_id' => $fieldValues['id'],
3097 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3099 if ($fieldValues['tax_amount']) {
3100 $invoiceSettings = CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::CONTRIBUTE_PREFERENCES_NAME
, 'contribution_invoice_settings');
3101 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3102 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3103 $itemParams['description'] = $taxTerm;
3104 if ($fieldValues['financial_type_id']) {
3105 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3107 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3115 * Check status validation on update of a contribution
3117 * @param array $values
3118 * Previous form values before submit.
3120 * @param array $fields
3121 * The input form values.
3123 * @param array $errors
3129 public static function checkStatusValidation($values, &$fields, &$errors) {
3130 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3131 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3132 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3136 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3137 $checkStatus = array(
3138 'Cancelled' => array('Completed', 'Refunded'),
3139 'Completed' => array('Cancelled', 'Refunded'),
3140 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3141 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3142 'Refunded' => array('Cancelled', 'Completed'),
3145 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3146 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3147 1 => $contributionStatuses[$values['contribution_status_id']],
3148 2 => $contributionStatuses[$fields['contribution_status_id']],
3154 * Delete contribution of contact
3158 * @param int $contactId
3163 public static function deleteContactContribution($contactId) {
3164 $contribution = new CRM_Contribute_DAO_Contribution();
3165 $contribution->contact_id
= $contactId;
3166 $contribution->find();
3167 while ($contribution->fetch()) {
3168 self
::deleteContribution($contribution->id
);
3173 * Get options for a given contribution field.
3174 * @see CRM_Core_DAO::buildOptions
3176 * @param string $fieldName
3177 * @param string $context
3178 * @see CRM_Core_DAO::buildOptionsContext.
3179 * @param array $props
3180 * whatever is known about this dao object.
3182 * @return Array|bool
3184 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3185 $className = __CLASS__
;
3187 switch ($fieldName) {
3188 // This field is not part of this object but the api supports it
3189 case 'payment_processor':
3190 $className = 'CRM_Contribute_BAO_ContributionPage';
3191 // Filter results by contribution page
3192 if (!empty($props['contribution_page_id'])) {
3193 $page = civicrm_api('contribution_page', 'getsingle', array(
3195 'id' => ($props['contribution_page_id']),
3197 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3198 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3202 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3203 case 'honor_type_id':
3204 $className = 'CRM_Contribute_BAO_ContributionSoft';
3205 $fieldName = 'soft_credit_type_id';
3206 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3209 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3213 * Validate financial type
3217 * @param int $financialTypeId
3218 * Financial Type id.
3220 * @param string $relationName
3222 * @return array|bool
3225 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3226 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3227 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3229 if (!$financialAccount) {
3230 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3237 * Function to record additional payment for partial and refund contributions
3239 * @param int $contributionId
3240 * is the invoice contribution id (got created after processing participant payment).
3241 * @param array $trxnData
3242 * to take user provided input of transaction details.
3243 * @param string $paymentType
3244 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3247 * @param int $contributionId
3249 * @param string $paymentType
3250 * @param int $participantId
3252 * @return null|object
3254 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3255 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3256 $getInfoOf['id'] = $contributionId;
3257 $defaults = array();
3258 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3260 if ($paymentType == 'owed') {
3261 // build params for recording financial trxn entry
3262 $params['contribution'] = $contributionDAO;
3263 $params = array_merge($defaults, $params);
3264 $params['skipLineItem'] = TRUE;
3265 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3266 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3267 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3270 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3271 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3272 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3274 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3275 if (!empty($trxnId)) {
3276 $trxnId = $trxnId['trxn_id'];
3278 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3279 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3282 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3283 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3284 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3288 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3289 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3290 FROM civicrm_financial_trxn ft
3291 LEFT JOIN civicrm_entity_financial_trxn eft
3292 ON (ft.id = eft.financial_trxn_id)
3293 WHERE eft.entity_table = 'civicrm_contribution'
3294 AND eft.entity_id = {$contributionId}
3295 AND ft.to_financial_account_id != {$toFinancialAccount}
3296 AND ft.status_id = {$statusId}
3298 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3301 if ($contributionDAO->total_amount
== $sumOfPayments) {
3302 // update contribution status and
3303 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3304 $contributionDAO->contribution_status_id
= $statusId;
3305 $contributionDAO->cancel_date
= 'null';
3306 $contributionDAO->cancel_reason
= NULL;
3307 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3308 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3309 $contributionDAO->save();
3311 //Change status of financial record too
3312 $financialTrxn->status_id
= $statusId;
3313 $financialTrxn->save();
3315 // note : not using the self::add method,
3316 // the reason because it performs 'status change' related code execution for financial records
3317 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3318 // are coded below i.e. just updating financial_item status to 'Paid'
3320 if ($participantId) {
3321 // update participant status
3322 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3323 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3324 foreach ($ids as $val) {
3325 $participantUpdate['id'] = $val;
3326 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3327 CRM_Event_BAO_Participant
::add($participantUpdate);
3331 // update financial item statuses
3332 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3333 $paidStatus = array_search('Paid', $financialItemStatus);
3335 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3336 $sqlFinancialItemUpdate = "
3337 UPDATE civicrm_financial_item fi
3338 LEFT JOIN civicrm_entity_financial_trxn eft
3339 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3340 SET status_id = {$paidStatus}
3341 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3343 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3346 elseif ($paymentType == 'refund') {
3347 // build params for recording financial trxn entry
3348 $params['contribution'] = $contributionDAO;
3349 $params = array_merge($defaults, $params);
3350 $params['skipLineItem'] = TRUE;
3351 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3352 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3354 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3355 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3356 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3358 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3360 // note : not using the self::add method,
3361 // the reason because it performs 'status change' related code execution for financial records
3362 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3363 // are coded below i.e. just updating financial_item status to 'Paid'
3364 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3366 // add financial item entry
3367 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3368 $getLine['entity_id'] = $contributionDAO->id
;
3369 $getLine['entity_table'] = 'civicrm_contribution';
3370 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3371 if (!empty($lineItemId->id
)) {
3372 $addFinancialEntry = array(
3373 'transaction_date' => $financialTrxn->trxn_date
,
3374 'contact_id' => $contributionDAO->contact_id
,
3375 'amount' => $financialTrxn->total_amount
,
3376 'status_id' => array_search('Paid', $financialItemStatus),
3377 'entity_id' => $lineItemId->id
,
3378 'entity_table' => 'civicrm_line_item',
3380 $trxnIds['id'] = $financialTrxn->id
;
3381 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3383 if ($participantId) {
3384 // update participant status
3385 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3386 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3387 foreach ($ids as $val) {
3388 $participantUpdate['id'] = $val;
3389 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3390 CRM_Event_BAO_Participant
::add($participantUpdate);
3395 // activity creation
3396 if (!empty($financialTrxn)) {
3397 if ($participantId) {
3398 $inputParams['id'] = $participantId;
3401 $component = 'event';
3402 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3403 $entityObj = $entityObj[$participantId];
3405 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3407 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3409 return $financialTrxn;
3415 * @param $activityType
3417 * @param int $contributionId
3419 * @throws CRM_Core_Exception
3421 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3422 if ($component == 'event') {
3423 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3424 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3425 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3426 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3427 $targetCid = $entityObj->contact_id
;
3428 // source record id would be the contribution id
3429 $srcRecId = $contributionId;
3433 $activityParams = array(
3434 'source_contact_id' => $targetCid,
3435 'source_record_id' => $srcRecId,
3436 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3440 'subject' => $subject,
3441 'activity_date_time' => $date,
3442 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3446 'skipRecentView' => TRUE,
3449 // create activity with target contacts
3450 $session = CRM_Core_Session
::singleton();
3451 $id = $session->get('userID');
3453 $activityParams['source_contact_id'] = $id;
3454 $activityParams['target_contact_id'][] = $targetCid;
3456 CRM_Activity_BAO_Activity
::create($activityParams);
3460 * Get list of payments displayed by Contribute_Page_PaymentInfo
3464 * @param bool $getTrxnInfo
3465 * @param bool $usingLineTotal
3469 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3470 if ($component == 'event') {
3471 $entity = 'participant';
3472 $entityTable = 'civicrm_participant';
3473 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3475 if (!$contributionId) {
3476 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3477 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3478 $id = $primaryParticipantId;
3480 if (!$contributionId) {
3485 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3486 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3492 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3493 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3496 if (empty($total) ||
$usingLineTotal) {
3497 // for additional participants
3498 if ($entityTable == 'civicrm_participant') {
3499 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3501 foreach ($ids as $val) {
3502 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3506 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3510 $baseTrxnId = $total['trxn_id'];
3511 $total = $total['total_amount'];
3514 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3515 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3517 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3518 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3519 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3521 if ($paymentBalance == 0 && $contributionIsPayLater) {
3522 $paymentBalance = $total;
3525 $info['total'] = $total;
3526 $info['paid'] = $total - $paymentBalance;
3527 $info['balance'] = $paymentBalance;
3529 $info['component'] = $component;
3530 $info['payLater'] = $contributionIsPayLater;
3532 if ($getTrxnInfo && $baseTrxnId) {
3533 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3535 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3536 FROM civicrm_contribution con
3537 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3538 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3539 WHERE con.id = {$contributionId}
3542 // conditioned WHERE clause
3544 // if balance trxn exists don't include details of it in transaction info
3545 $sql .= " AND ft.id != {$baseTrxnId} ";
3547 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3549 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3550 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3551 while ($resultDAO->fetch()) {
3552 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3553 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3555 'total_amount' => $resultDAO->total_amount
,
3556 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3557 'payment_instrument' => $paidByLabel,
3558 'receive_date' => $resultDAO->trxn_date
,
3559 'trxn_id' => $resultDAO->trxn_id
,
3560 'status' => $statuses[$resultDAO->status_id
],
3562 if ($paidByName == 'Check') {
3563 $val['check_number'] = $resultDAO->check_number
;
3567 $info['transaction'] = $rows;
3573 * Get financial account id has 'Sales Tax Account is'
3574 * account relationship with financial type
3576 * @param int $financialTypeId
3578 * @return FinancialAccountId
3580 public static function getFinancialAccountId($financialTypeId) {
3581 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3582 $searchParams = array(
3583 'entity_table' => 'civicrm_financial_type',
3584 'entity_id' => $financialTypeId,
3585 'account_relationship' => $accountRel,
3588 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
3590 return CRM_Utils_Array
::value('financial_account_id', $result);
3593 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3594 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
3596 // Update contribution
3597 if (!empty($params['id'])) {
3598 $id = $params['id'];
3599 $values = $ids = array();
3600 $contrbutionParams = array('id' => $id);
3601 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
3603 // To assign pervious finantial type on update of contribution
3604 if (!isset($params['financial_type_id'])) {
3605 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
3607 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3608 // Assisn tax Amount on update of contrbution
3609 if (!empty($prevContributionValue->tax_amount
)) {
3610 $params['tax_amount'] = 'null';
3611 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3612 foreach ($params['line_item'] as $setID => $priceField) {
3613 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3614 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3621 // New Contrbution and update of contribution with tax rate financial type
3622 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3623 empty($params['skipLineItem']) && !$isLineItem
3625 $taxRateParams = $taxRates[$params['financial_type_id']];
3626 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
3627 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3629 // Get Line Item on update of contribution
3630 if (isset($params['id'])) {
3631 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
3634 CRM_Price_BAO_LineItem
::getLineItemArray($params);
3636 foreach ($params['line_item'] as $setID => $priceField) {
3637 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3638 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3641 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3643 elseif (isset($params['api.line_item.create'])) {
3644 // Update total amount of contribution using lineItem
3645 $taxAmountArray = array();
3646 foreach ($params['api.line_item.create'] as $key => $value) {
3647 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3648 $taxRate = $taxRates[$value['financial_type_id']];
3649 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
3650 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3653 $params['tax_amount'] = array_sum($taxAmountArray);
3654 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
3657 // update line item of contrbution
3658 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3659 $taxRate = $taxRates[$params['financial_type_id']];
3660 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
3661 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);