3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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;
76 * @return \CRM_Contribute_DAO_Contribution
81 function __construct() {
82 parent
::__construct();
86 * takes an associative array and creates a contribution object
88 * the function extract all the params it needs to initialize the create a
89 * contribution object. the params array could contain additional unused name/value
92 * @param array $params (reference ) an assoc array of name/value pairs
93 * @param array $ids the array that holds all the db ids
95 * @return object CRM_Contribute_BAO_Contribution object
99 static function add(&$params, $ids = array()) {
100 if (empty($params)) {
103 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
104 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
106 $duplicates = array();
107 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
108 $error = CRM_Core_Error
::singleton();
109 $d = implode(', ', $duplicates);
110 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
113 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
118 // first clean up all the money fields
119 $moneyFields = array(
123 'non_deductible_amount',
126 //if priceset is used, no need to cleanup money
127 if (!empty($params['skipCleanMoney'])) {
128 unset($moneyFields[0]);
131 foreach ($moneyFields as $field) {
132 if (isset($params[$field])) {
133 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
137 // CRM-13420, set payment instrument to default if payment_instrument_id is empty
138 if (!$contributionID && empty($params['payment_instrument_id'])) {
139 $params['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument',
140 FALSE, FALSE, FALSE, 'AND is_default = 1'));
143 if (!empty($params['payment_instrument_id'])) {
144 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
145 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
146 $params['check_number'] = 'null';
150 // contribution status is missing, choose Completed as default status
151 // do this for create mode only
152 if (empty($ids['contribution']) && empty($params['contribution_status_id'])) {
153 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
155 $setPrevContribution = TRUE;
156 // CRM-13964 partial payment
157 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
158 $partialAmtTotal = $params['partial_payment_total'];
159 $partialAmtPay = $params['partial_amount_pay'];
160 $params['total_amount'] = $partialAmtTotal;
161 if ($partialAmtPay < $partialAmtTotal) {
162 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
163 $params['is_pay_later'] = 0;
164 $setPrevContribution = FALSE;
168 if ($contributionID) {
169 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
172 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
174 $contribution = new CRM_Contribute_BAO_Contribution();
175 $contribution->copyValues($params);
177 $contribution->id
= $contributionID;
179 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
180 $config = CRM_Core_Config
::singleton();
181 $contribution->currency
= $config->defaultCurrency
;
184 if ($contributionID && $setPrevContribution) {
185 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
188 $result = $contribution->save();
190 // Add financial_trxn details as part of fix for CRM-4724
191 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
192 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
194 //add Account details
195 $params['contribution'] = $contribution;
196 self
::recordFinancialAccounts($params);
198 // reset the group contact cache for this group
199 CRM_Contact_BAO_GroupContactCache
::remove();
201 if ($contributionID) {
202 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
205 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
212 * Given the list of params in the params array, fetch the object
213 * and store the values in the values array
215 * @param array $params input parameters to find object
216 * @param array $values output values of the object
217 * @param array $ids the array that holds all the db ids
219 * @return CRM_Contribute_BAO_Contribution|null the found object or null
223 static function &getValues($params, &$values, &$ids) {
224 if (empty($params)) {
227 $contribution = new CRM_Contribute_BAO_Contribution();
229 $contribution->copyValues($params);
231 if ($contribution->find(TRUE)) {
232 $ids['contribution'] = $contribution->id
;
234 CRM_Core_DAO
::storeValues($contribution, $values);
236 return $contribution;
242 * takes an associative array and creates a contribution object
244 * @param array $params (reference ) an assoc array of name/value pairs
245 * @param array $ids the array that holds all the db ids
247 * @return object CRM_Contribute_BAO_Contribution object
251 static function create(&$params, $ids = array()) {
252 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
253 foreach ($dateFields as $df) {
254 if (isset($params[$df])) {
255 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
259 $transaction = new CRM_Core_Transaction();
261 $contribution = self
::add($params, $ids);
263 if (is_a($contribution, 'CRM_Core_Error')) {
264 $transaction->rollback();
265 return $contribution;
268 $params['contribution_id'] = $contribution->id
;
270 if (!empty($params['custom']) &&
271 is_array($params['custom'])
273 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
276 $session = CRM_Core_Session
::singleton();
278 if (!empty($params['note'])) {
280 'entity_table' => 'civicrm_contribution',
281 'note' => $params['note'],
282 'entity_id' => $contribution->id
,
283 'contact_id' => $session->get('userID'),
284 'modified_date' => date('Ymd'),
286 if (!$noteParams['contact_id']) {
287 $noteParams['contact_id'] = $params['contact_id'];
289 CRM_Core_BAO_Note
::add($noteParams);
292 // make entry in batch entity batch table
293 if (!empty($params['batch_id'])) {
294 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
295 $titleFields = array(
301 $retrieveRequired = 0;
302 foreach ($titleFields as $titleField) {
303 if(!isset($contribution->$titleField)){
304 $retrieveRequired = 1;
308 if ($retrieveRequired == 1) {
309 $contribution->find(TRUE);
313 // check if activity record exist for this contribution, if
315 $activity = new CRM_Activity_DAO_Activity();
316 $activity->source_record_id
= $contribution->id
;
317 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
321 if (!$activity->find(TRUE)) {
322 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
325 // CRM-13237 : if activity record found, update it with campaign id of contribution
326 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
329 // Handle soft credit and / or link to personal campaign page
330 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
332 //Delete PCP against this contribution and create new on submitted PCP information
333 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
335 $deleteParams = array('id' => $pcpId);
336 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
338 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
339 $softParams = array();
340 $softParams['contribution_id'] = $contribution->id
;
341 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
342 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
343 $pcp['pcp_made_through_id'], 'contact_id'
345 $softParams['currency'] = $contribution->currency
;
346 $softParams['amount'] = $contribution->total_amount
;
347 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
348 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
349 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
350 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
351 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
353 if (isset($params['soft_credit'])) {
354 $softParams = $params['soft_credit'];
356 if (!empty($softIDs)) {
357 foreach ( $softIDs as $softID) {
358 if (!in_array($softID, $params['soft_credit_ids'])) {
359 $deleteParams = array('id' => $softID);
360 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
365 foreach ($softParams as $softParam) {
366 $softParam['contribution_id'] = $contribution->id
;
367 $softParam['currency'] = $contribution->currency
;
368 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
369 if (empty($softParam['amount'])) {
370 $softParam['amount'] = $contribution->total_amount
;
372 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
376 $transaction->commit();
378 // do not add to recent items for import, CRM-4399
379 if (empty($params['skipRecentView'])) {
380 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
381 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
383 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
384 $titleFields = array(
390 $retrieveRequired = 0;
391 foreach ($titleFields as $titleField) {
392 if(!isset($contribution->$titleField)){
393 $retrieveRequired = 1;
397 if($retrieveRequired == 1){
398 $contribution->find(TRUE);
400 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
401 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
403 $recentOther = array();
404 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
405 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
406 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
410 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
411 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
412 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
416 // add the recently created Contribution
417 CRM_Utils_Recent
::add($title,
421 $contribution->contact_id
,
427 return $contribution;
431 * Get the values for pseudoconstants for name->value and reverse.
433 * @param array $defaults (reference) the default values, some of which need to be resolved.
434 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
440 static function resolveDefaults(&$defaults, $reverse = FALSE) {
441 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
442 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
443 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
444 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
448 * This function is used to convert associative array names to values
451 * This function is used by both the web form layer and the api. Note that
452 * the api needs the name => value conversion, also the view layer typically
453 * requires value => name conversion
455 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
456 $id = $property . '_id';
458 $src = $reverse ?
$property : $id;
459 $dst = $reverse ?
$id : $property;
461 if (!array_key_exists($src, $defaults)) {
465 $look = $reverse ?
array_flip($lookup) : $lookup;
467 if (is_array($look)) {
468 if (!array_key_exists($defaults[$src], $look)) {
472 $defaults[$dst] = $look[$defaults[$src]];
477 * Takes a bunch of params that are needed to match certain criteria and
478 * retrieves the relevant objects. We'll tweak this function to be more
479 * full featured over a period of time. This is the inverse function of
480 * create. It also stores all the retrieved values in the default array
482 * @param array $params (reference ) an assoc array of name/value pairs
483 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
484 * in a hierarchical manner
485 * @param array $ids (reference) the array that holds all the db ids
487 * @return object CRM_Contribute_BAO_Contribution object
491 static function retrieve(&$params, &$defaults, &$ids) {
492 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
493 return $contribution;
497 * combine all the importable fields from the lower levels object
499 * The ordering is important, since currently we do not have a weight
500 * scheme. Adding weight is super important and should be done in the
501 * next week or so, before this can be called complete.
503 * @param string $contactType
504 * @param bool $status
506 * @return array array of importable Fields
510 static function &importableFields($contactType = 'Individual', $status = TRUE) {
511 if (!self
::$_importableFields) {
512 if (!self
::$_importableFields) {
513 self
::$_importableFields = array();
517 $fields = array('' => array('title' => ts('- do not import -')));
520 $fields = array('' => array('title' => ts('- Contribution Fields -')));
523 $note = CRM_Core_DAO_Note
::import();
524 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
525 unset($tmpFields['option_value']);
526 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
527 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
529 // Using new Dedupe rule.
531 'contact_type' => $contactType,
532 'used' => 'Unsupervised',
534 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
535 $tmpContactField = array();
536 if (is_array($fieldsArray)) {
537 foreach ($fieldsArray as $value) {
538 //skip if there is no dupe rule
539 if ($value == 'none') {
542 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
547 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
548 $tmpContactField[trim($value)] = $contactFields[trim($value)];
550 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
553 $title = $tmpContactField[trim($value)]['title'];
555 $tmpContactField[trim($value)]['title'] = $title;
559 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
560 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
561 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
562 $fields = array_merge($fields, $tmpContactField);
563 $fields = array_merge($fields, $tmpFields);
564 $fields = array_merge($fields, $note);
565 $fields = array_merge($fields, $optionFields);
566 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
567 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
568 self
::$_importableFields = $fields;
570 return self
::$_importableFields;
576 static function &exportableFields() {
577 if (!self
::$_exportableFields) {
578 if (!self
::$_exportableFields) {
579 self
::$_exportableFields = array();
582 $impFields = CRM_Contribute_DAO_Contribution
::export();
583 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
584 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
585 $typeField = CRM_Financial_DAO_FinancialType
::export();
586 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
587 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
588 $contributionStatus = array(
589 'contribution_status' => array(
590 'title' => ts('Contribution Status'),
591 'name' => 'contribution_status',
592 'data_type' => CRM_Utils_Type
::T_STRING
595 $contributionNote = array(
596 'contribution_note' =>
598 'title' => ts('Contribution Note'),
599 'name' => 'contribution_note',
600 'data_type' => CRM_Utils_Type
::T_TEXT
604 $contributionRecurId = array(
605 'contribution_recur_id' =>
607 'title' => ts('Recurring Contributions ID'),
608 'name' => 'contribution_recur_id',
609 'where' => 'civicrm_contribution.contribution_recur_id',
610 'data_type' => CRM_Utils_Type
::T_INT
613 $extraFields = array(
614 'contribution_batch' => array(
615 'title' => ts('Batch Name')
619 $softCreditFields = array(
620 'contribution_soft_credit_name' => array(
621 'name' => 'contribution_soft_credit_name',
622 'title' => 'Soft Credit For',
623 'where' => 'civicrm_contact_d.display_name',
624 'data_type' => CRM_Utils_Type
::T_STRING
626 'contribution_soft_credit_amount' => array(
627 'name' => 'contribution_soft_credit_amount',
628 'title' => 'Soft Credit Amount',
629 'where' => 'civicrm_contribution_soft.amount',
630 'data_type' => CRM_Utils_Type
::T_MONEY
632 'contribution_soft_credit_type' => array(
633 'name' => 'contribution_soft_credit_type',
634 'title' => 'Soft Credit Type',
635 'where' => 'contribution_softcredit_type.label',
636 'data_type' => CRM_Utils_Type
::T_STRING
638 'contribution_soft_credit_contribution_id' => array(
639 'name' => 'contribution_soft_credit_contribution_id',
640 'title' => 'Soft Credit For Contribution ID',
641 'where' => 'civicrm_contribution_soft.contribution_id',
642 'data_type' => CRM_Utils_Type
::T_INT
646 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
647 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
648 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
651 self
::$_exportableFields = $fields;
654 return self
::$_exportableFields;
658 * @param null $status
659 * @param null $startDate
660 * @param null $endDate
664 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
668 $where[] = 'contribution_status_id = 1';
672 $where[] = 'contribution_status_id = 3';
677 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
680 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
683 $whereCond = implode(' AND ', $where);
686 SELECT sum( total_amount ) as total_amount,
687 count( civicrm_contribution.id ) as total_count,
689 FROM civicrm_contribution
690 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
692 AND ( is_test = 0 OR is_test IS NULL )
693 AND contact.is_deleted = 0
697 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
700 while ($dao->fetch()) {
701 $count +
= $dao->total_count
;
702 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
705 return array('amount' => implode(', ', $amount),
713 * Delete the indirect records associated with this contribution first
717 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
720 static function deleteContribution($id) {
721 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
723 $transaction = new CRM_Core_Transaction();
726 //delete activity record
728 'source_record_id' => $id,
729 // activity type id for contribution
730 'activity_type_id' => 6,
733 CRM_Activity_BAO_Activity
::deleteActivity($params);
735 //delete billing address if exists for this contribution.
736 self
::deleteAddress($id);
738 //update pledge and pledge payment, CRM-3961
739 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
741 // remove entry from civicrm_price_set_entity, CRM-5095
742 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
743 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
745 // cleanup line items.
746 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
748 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
749 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
751 if ($participantId) {
752 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
755 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
759 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
760 $noteId = key($note);
762 CRM_Core_BAO_Note
::del($noteId, FALSE);
765 $dao = new CRM_Contribute_DAO_Contribution();
768 $results = $dao->delete();
770 $transaction->commit();
772 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
774 // delete the recently created Contribution
775 $contributionRecent = array(
777 'type' => 'Contribution',
779 CRM_Utils_Recent
::del($contributionRecent);
785 * Check if there is a contribution with the same trxn_id or invoice_id
788 * @param array $duplicates (reference ) store ids of duplicate contribs
792 * @internal param array $params (reference ) an assoc array of name/value pairs
793 * @return boolean true if duplicate, false otherwise
797 static function checkDuplicate($input, &$duplicates, $id = NULL) {
799 $id = CRM_Utils_Array
::value('id', $input);
801 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
802 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
808 $clause[] = "trxn_id = %1";
809 $input[1] = array($trxn_id, 'String');
813 $clause[] = "invoice_id = %2";
814 $input[2] = array($invoice_id, 'String');
817 if (empty($clause)) {
821 $clause = implode(' OR ', $clause);
823 $clause = "( $clause ) AND id != %3";
824 $input[3] = array($id, 'Integer');
827 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
828 $dao = CRM_Core_DAO
::executeQuery($query, $input);
830 while ($dao->fetch()) {
831 $duplicates[] = $dao->id
;
838 * takes an associative array and creates a contribution_product object
840 * the function extract all the params it needs to initialize the create a
841 * contribution_product object. the params array could contain additional unused name/value
844 * @param array $params (reference ) an assoc array of name/value pairs
846 * @return object CRM_Contribute_BAO_ContributionProduct object
850 static function addPremium(&$params) {
851 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
852 $contributionProduct->copyValues($params);
853 return $contributionProduct->save();
857 * Function to get list of contribution fields for profile
858 * For now we only allow custom contribution fields to be in
861 * @param boolean $addExtraFields true if special fields needs to be added
863 * @return return the list of contribution fields
867 static function getContributionFields($addExtraFields = TRUE) {
868 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
869 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
871 if ($addExtraFields) {
872 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
875 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
877 foreach ($contributionFields as $key => $var) {
878 if ($key == 'contribution_contact_id') {
881 elseif ($key == 'contribution_campaign_id') {
882 $var['title'] = ts('Campaign');
884 $fields[$key] = $var;
887 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
892 * Function to add extra fields specific to contribtion
896 static function getSpecialContributionFields() {
897 $extraFields = array(
898 'contribution_soft_credit_name' => array(
899 'name' => 'contribution_soft_credit_name',
900 'title' => 'Soft Credit Name',
901 'headerPattern' => '/^soft_credit_name$/i',
902 'where' => 'civicrm_contact_d.display_name',
904 'contribution_soft_credit_email' => array(
905 'name' => 'contribution_soft_credit_email',
906 'title' => 'Soft Credit Email',
907 'headerPattern' => '/^soft_credit_email$/i',
908 'where' => 'soft_email.email',
910 'contribution_soft_credit_phone' => array(
911 'name' => 'contribution_soft_credit_phone',
912 'title' => 'Soft Credit Phone',
913 'headerPattern' => '/^soft_credit_phone$/i',
914 'where' => 'soft_phone.phone',
916 'contribution_soft_credit_contact_id' => array(
917 'name' => 'contribution_soft_credit_contact_id',
918 'title' => 'Soft Credit Contact ID',
919 'headerPattern' => '/^soft_credit_contact_id$/i',
920 'where' => 'civicrm_contribution_soft.contact_id',
932 static function getCurrentandGoalAmount($pageID) {
934 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
935 FROM civicrm_contribution_page p,
936 civicrm_contribution c
937 WHERE p.id = c.contribution_page_id
939 AND c.cancel_date is null
943 $config = CRM_Core_Config
::singleton();
944 $params = array(1 => array($pageID, 'Integer'));
945 $dao = CRM_Core_DAO
::executeQuery($query, $params);
948 return array($dao->goal
, $dao->total
);
951 return array(NULL, NULL);
956 * Function to get list of contribution In Honor of contact Ids
958 * @param int $honorId In Honor of Contact ID
960 * @return return the list of contribution fields
965 static function getHonorContacts($honorId) {
967 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
968 $honorDAO->contact_id
= $honorId;
971 $type = CRM_Contribute_PseudoConstant
::financialType();
973 while ($honorDAO->fetch()) {
974 $contributionDAO = new CRM_Contribute_DAO_Contribution();
975 $contributionDAO->id
= $honorDAO->contribution_id
;
977 if ($contributionDAO->find(TRUE)) {
978 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
979 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
980 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
981 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
982 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
983 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
984 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
985 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
986 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
994 * function to get the sort name of a contact for a particular contribution
996 * @param int $id id of the contribution
998 * @return null|string sort name of the contact if found
1002 static function sortName($id) {
1003 $id = CRM_Utils_Type
::escape($id, 'Integer');
1006 SELECT civicrm_contact.sort_name
1007 FROM civicrm_contribution, civicrm_contact
1008 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1009 AND civicrm_contribution.id = {$id}
1011 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1019 static function annual($contactID) {
1020 if (is_array($contactID)) {
1021 $contactIDs = implode(',', $contactID);
1024 $contactIDs = $contactID;
1027 $config = CRM_Core_Config
::singleton();
1028 $startDate = $endDate = NULL;
1030 $currentMonth = date('m');
1031 $currentDay = date('d');
1032 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1033 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1034 (int ) $config->fiscalYearStart
['d'] > $currentDay
1037 $year = date('Y') - 1;
1042 $nextYear = $year +
1;
1044 if ($config->fiscalYearStart
) {
1045 if ($config->fiscalYearStart
['M'] < 10) {
1046 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1048 if ($config->fiscalYearStart
['d'] < 10) {
1049 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1051 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1056 $startDate = "$year$monthDay";
1057 $endDate = "$nextYear$monthDay";
1060 SELECT count(*) as count,
1061 sum(total_amount) as amount,
1062 avg(total_amount) as average,
1064 FROM civicrm_contribution b
1065 WHERE b.contact_id IN ( $contactIDs )
1066 AND b.contribution_status_id = 1
1068 AND b.receive_date >= $startDate
1069 AND b.receive_date < $endDate
1072 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1074 $amount = $average = array();
1075 while ($dao->fetch()) {
1076 if ($dao->count
> 0 && $dao->amount
> 0) {
1077 $count +
= $dao->count
;
1078 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1079 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1085 implode(', ', $amount),
1086 implode(', ', $average),
1089 return array(0, 0, 0);
1093 * Check if there is a contribution with the params passed in.
1094 * Used for trxn_id,invoice_id and contribution_id
1096 * @param array $params an assoc array of name/value pairs
1098 * @return array contribution id if success else NULL
1102 static function checkDuplicateIds($params) {
1103 $dao = new CRM_Contribute_DAO_Contribution();
1107 foreach ($params as $k => $v) {
1109 $clause[] = "$k = '$v'";
1112 $clause = implode(' AND ', $clause);
1113 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1114 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1116 while ($dao->fetch()) {
1124 * Function to get the contribution details for component export
1126 * @param int $exportMode export mode
1127 * @param string $componentIds component ids
1129 * @return array associated array
1134 static function getContributionDetails($exportMode, $componentIds) {
1135 $paymentDetails = array();
1136 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1138 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1139 $componentSelect = " civicrm_participant_payment.participant_id id";
1140 $additionalClause = "
1141 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1142 AND civicrm_participant_payment.participant_id {$componentClause} )
1145 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1146 $componentSelect = " civicrm_membership_payment.membership_id id";
1147 $additionalClause = "
1148 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1149 AND civicrm_membership_payment.membership_id {$componentClause} )
1152 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1153 $componentSelect = " civicrm_pledge_payment.id id";
1154 $additionalClause = "
1155 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1156 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1160 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1161 trxn_id, {$componentSelect}
1162 FROM civicrm_contribution
1163 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1164 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1165 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1166 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1167 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1168 AND option_group_contribution_status.id = contribution_status.option_group_id )
1172 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1174 while ($dao->fetch()) {
1175 $paymentDetails[$dao->id
] = array(
1176 'total_amount' => $dao->total_amount
,
1177 'contribution_status' => $dao->status
,
1178 'receive_date' => $dao->receive_date
,
1179 'pay_instru' => $dao->payment_instrument
,
1180 'trxn_id' => $dao->trxn_id
,
1184 return $paymentDetails;
1188 * Function to create address associated with contribution record.
1190 * @param array $params an associated array
1191 * @param $billingLocationTypeID
1193 * @internal param int $billingID $billingLocationTypeID
1195 * @return address id
1198 static function createAddress(&$params, $billingLocationTypeID) {
1199 $billingFields = array(
1202 'state_province_id',
1207 //build address array
1208 $addressParams = array();
1209 $addressParams['location_type_id'] = $billingLocationTypeID;
1210 $addressParams['is_billing'] = 1;
1212 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1213 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1214 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1215 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1217 foreach ($billingFields as $value) {
1218 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1221 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1223 return $address->id
;
1227 * Delete billing address record related contribution
1229 * @param null $contributionId
1230 * @param null $contactId
1232 * @internal param int $contact_id contact id
1233 * @internal param int $contribution_id contributionId
1237 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1239 $contactJoin = NULL;
1241 if ($contributionId) {
1242 $clauses[] = "cc.id = {$contributionId}";
1246 $clauses[] = "cco.id = {$contactId}";
1247 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1250 if (empty($clauses)) {
1251 CRM_Core_Error
::fatal();
1254 $condition = implode(' OR ', $clauses);
1258 FROM civicrm_address ca
1259 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1263 $dao = CRM_Core_DAO
::executeQuery($query);
1265 while ($dao->fetch()) {
1266 $params = array('id' => $dao->id
);
1267 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1272 * This function check online pending contribution associated w/
1273 * Online Event Registration or Online Membership signup.
1275 * @param int $componentId participant/membership id.
1276 * @param string $componentName Event/Membership.
1278 * @return $contributionId pending contribution id.
1281 static function checkOnlinePendingContribution($componentId, $componentName) {
1282 $contributionId = NULL;
1283 if (!$componentId ||
1284 !in_array($componentName, array('Event', 'Membership'))
1286 return $contributionId;
1289 if ($componentName == 'Event') {
1290 $idName = 'participant_id';
1291 $componentTable = 'civicrm_participant';
1292 $paymentTable = 'civicrm_participant_payment';
1293 $source = ts('Online Event Registration');
1296 if ($componentName == 'Membership') {
1297 $idName = 'membership_id';
1298 $componentTable = 'civicrm_membership';
1299 $paymentTable = 'civicrm_membership_payment';
1300 $source = ts('Online Contribution');
1303 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1306 SELECT component.id as {$idName},
1307 componentPayment.contribution_id as contribution_id,
1308 contribution.source source,
1309 contribution.contribution_status_id as contribution_status_id,
1310 contribution.is_pay_later as is_pay_later
1311 FROM $componentTable component
1312 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1313 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1314 WHERE component.id = {$componentId}";
1316 $dao = CRM_Core_DAO
::executeQuery($query);
1318 while ($dao->fetch()) {
1319 if ($dao->contribution_id
&&
1320 $dao->is_pay_later
&&
1321 $dao->contribution_status_id
== $pendingStatusId &&
1322 strpos($dao->source
, $source) !== FALSE
1324 $contributionId = $dao->contribution_id
;
1329 return $contributionId;
1333 * This function update contribution as well as related objects.
1335 static function transitionComponents($params, $processContributionObject = FALSE) {
1336 // get minimum required values.
1337 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1338 $componentId = CRM_Utils_Array
::value('component_id', $params);
1339 $componentName = CRM_Utils_Array
::value('componentName', $params);
1340 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1341 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1343 // if we already processed contribution object pass previous status id.
1344 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1346 $updateResult = array();
1348 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1350 // we process only ( Completed, Cancelled, or Failed ) contributions.
1351 if (!$contributionId ||
1352 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1353 array_search('Cancelled', $contributionStatuses),
1354 array_search('Failed', $contributionStatuses),
1357 return $updateResult;
1360 if (!$componentName ||
!$componentId) {
1361 // get the related component details.
1362 $componentDetails = self
::getComponentDetails($contributionId);
1365 $componentDetails['contact_id'] = $contactId;
1366 $componentDetails['component'] = $componentName;
1368 if ($componentName == 'event') {
1369 $componentDetails['participant'] = $componentId;
1372 $componentDetails['membership'] = $componentId;
1376 if (!empty($componentDetails['contact_id'])) {
1377 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1383 // do check for required ids.
1384 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1385 return $updateResult;
1388 //now we are ready w/ required ids, start processing.
1390 $baseIPN = new CRM_Core_Payment_BaseIPN();
1392 $input = $ids = $objects = array();
1394 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1395 $ids['contribution'] = $contributionId;
1396 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1397 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1398 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1399 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1400 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1401 $ids['contributionRecur'] = NULL;
1402 $ids['contributionPage'] = NULL;
1404 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1405 CRM_Core_Error
::fatal();
1408 $memberships = &$objects['membership'];
1409 $participant = &$objects['participant'];
1410 $pledgePayment = &$objects['pledge_payment'];
1411 $contribution = &$objects['contribution'];
1413 if ($pledgePayment) {
1414 $pledgePaymentIDs = array();
1415 foreach ($pledgePayment as $key => $object) {
1416 $pledgePaymentIDs[] = $object->id
;
1418 $pledgeID = $pledgePayment[0]->pledge_id
;
1421 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1424 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1425 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1430 // we might want to process contribution object.
1431 $processContribution = FALSE;
1432 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1433 if (is_array($memberships)) {
1434 foreach ($memberships as $membership) {
1436 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1437 $membership->save();
1439 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1440 if ($processContributionObject) {
1441 $processContribution = TRUE;
1448 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1449 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1451 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1452 if ($processContributionObject) {
1453 $processContribution = TRUE;
1457 if ($pledgePayment) {
1458 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1460 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1461 if ($processContributionObject) {
1462 $processContribution = TRUE;
1466 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1467 if (is_array($memberships)) {
1468 foreach ($memberships as $membership) {
1470 $membership->status_id
= array_search('Expired', $membershipStatuses);
1471 $membership->save();
1473 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1474 if ($processContributionObject) {
1475 $processContribution = TRUE;
1481 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1482 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1484 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1485 if ($processContributionObject) {
1486 $processContribution = TRUE;
1490 if ($pledgePayment) {
1491 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1493 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1494 if ($processContributionObject) {
1495 $processContribution = TRUE;
1499 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1501 // only pending contribution related object processed.
1502 if ($previousContriStatusId &&
1503 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1505 // this is case when we already processed contribution object.
1506 return $updateResult;
1508 elseif (!$previousContriStatusId &&
1509 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1511 // this is case when we are going to process contribution object later.
1512 return $updateResult;
1515 if (is_array($memberships)) {
1516 foreach ($memberships as $membership) {
1521 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1522 $membership->membership_type_id
,
1523 $membership->is_test
, $membership->id
1526 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1527 // this picks up membership type changes during renewals
1529 SELECT membership_type_id
1530 FROM civicrm_membership_log
1531 WHERE membership_id=$membership->id
1534 $dao = new CRM_Core_DAO
;
1536 if ($dao->fetch()) {
1537 if (!empty($dao->membership_type_id
)) {
1538 $membership->membership_type_id
= $dao->membership_type_id
;
1539 $membership->save();
1542 // else fall back to using current membership type
1545 // Figure out number of terms
1547 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1548 foreach ($lineitems as $lineitem) {
1549 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1550 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1552 // in case membership_num_terms comes through as null or zero
1553 $numterms = $numterms >= 1 ?
$numterms : 1;
1558 if ($currentMembership) {
1559 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1560 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1561 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1564 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1567 //get the status for membership.
1568 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1570 $dates['join_date'],
1573 $membership->membership_type_id
,
1577 $formattedParams = array(
1578 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1579 array_search('Current', $membershipStatuses)
1581 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1582 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1583 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1586 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1588 $membership->copyValues($formattedParams);
1589 $membership->save();
1591 //updating the membership log
1592 $membershipLog = array();
1593 $membershipLog = $formattedParams;
1594 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1595 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1597 $membershipLog['start_date'] = $logStartDate;
1598 $membershipLog['membership_id'] = $membership->id
;
1599 $membershipLog['modified_id'] = $membership->contact_id
;
1600 $membershipLog['modified_date'] = date('Ymd');
1601 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1603 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1605 //update related Memberships.
1606 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1608 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1611 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1612 if ($processContributionObject) {
1613 $processContribution = TRUE;
1616 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1622 $updatedStatusId = array_search('Registered', $participantStatuses);
1623 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1625 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1626 if ($processContributionObject) {
1627 $processContribution = TRUE;
1631 if ($pledgePayment) {
1632 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1634 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1635 if ($processContributionObject) {
1636 $processContribution = TRUE;
1641 // process contribution object.
1642 if ($processContribution) {
1643 $contributionParams = array();
1645 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1646 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1647 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1649 foreach ($fields as $field) {
1650 if (empty($params[$field])) {
1653 $contributionParams[$field] = $params[$field];
1656 $ids = array('contribution' => $contributionId);
1657 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1660 return $updateResult;
1664 * This function returns all contribution related object ids.
1666 public static function getComponentDetails($contributionId) {
1667 $componentDetails = $pledgePayment = array();
1668 if (!$contributionId) {
1669 return $componentDetails;
1673 SELECT c.id as contribution_id,
1674 c.contact_id as contact_id,
1675 mp.membership_id as membership_id,
1676 m.membership_type_id as membership_type_id,
1677 pp.participant_id as participant_id,
1678 p.event_id as event_id,
1679 pgp.id as pledge_payment_id
1680 FROM civicrm_contribution c
1681 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1682 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1683 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1684 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1685 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1686 WHERE c.id = $contributionId";
1688 $dao = CRM_Core_DAO
::executeQuery($query);
1689 $componentDetails = array();
1691 while ($dao->fetch()) {
1692 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1693 $componentDetails['contact_id'] = $dao->contact_id
;
1694 if ($dao->event_id
) {
1695 $componentDetails['event'] = $dao->event_id
;
1697 if ($dao->participant_id
) {
1698 $componentDetails['participant'] = $dao->participant_id
;
1700 if ($dao->membership_id
) {
1701 if (!isset($componentDetails['membership'])) {
1702 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1704 $componentDetails['membership'][] = $dao->membership_id
;
1705 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1707 if ($dao->pledge_payment_id
) {
1708 $pledgePayment[] = $dao->pledge_payment_id
;
1712 if ($pledgePayment) {
1713 $componentDetails['pledge_payment'] = $pledgePayment;
1716 return $componentDetails;
1721 * @param bool $includeSoftCredit
1723 * @return null|string
1725 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1730 $contactContributionsSQL = "
1731 SELECT contribution.id AS id
1732 FROM civicrm_contribution contribution
1733 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1735 $contactSoftCreditContributionsSQL = "
1736 SELECT contribution.id
1737 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1738 ON ( contribution.id = softContribution.contribution_id )
1739 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1740 $query = "SELECT count( x.id ) count FROM ( ";
1741 $query .= $contactContributionsSQL;
1743 if ($includeSoftCredit) {
1744 $query .= " UNION ";
1745 $query .= $contactSoftCreditContributionsSQL;
1750 return CRM_Core_DAO
::singleValueQuery($query);
1754 * Function to get individual id for onbehalf contribution
1756 * @param int $contributionId contribution id
1757 * @param int $contributorId contributor id
1759 * @return array $ids containing organization id and individual id
1762 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1766 if (!$contributionId) {
1770 // fetch contributor id if null
1771 if (!$contributorId) {
1772 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1773 $contributionId, 'contact_id'
1777 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1778 $activityTypeId = array_search('Contribution', $activityTypeIds);
1780 if ($activityTypeId && $contributorId) {
1782 SELECT civicrm_activity_contact.contact_id
1783 FROM civicrm_activity_contact
1784 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1785 WHERE civicrm_activity.activity_type_id = %1
1786 AND civicrm_activity.source_record_id = %2
1787 AND civicrm_activity_contact.record_type_id = %3
1790 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1791 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1794 1 => array($activityTypeId, 'Integer'),
1795 2 => array($contributionId, 'Integer'),
1796 3 => array($sourceID, 'Integer'),
1799 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1801 // for on behalf contribution source is individual and contributor is organization
1802 if ($sourceContactId && $sourceContactId != $contributorId) {
1803 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1804 // get rel type id for employee of relation
1805 foreach ($relationshipTypeIds as $id => $typeVals) {
1806 if ($typeVals['name_a_b'] == 'Employee of') {
1807 $relationshipTypeId = $id;
1812 $rel = new CRM_Contact_DAO_Relationship();
1813 $rel->relationship_type_id
= $relationshipTypeId;
1814 $rel->contact_id_a
= $sourceContactId;
1815 $rel->contact_id_b
= $contributorId;
1816 if ($rel->find(TRUE)) {
1817 $ids['individual_id'] = $rel->contact_id_a
;
1818 $ids['organization_id'] = $rel->contact_id_b
;
1830 static function getContributionDates() {
1831 $config = CRM_Core_Config
::singleton();
1832 $currentMonth = date('m');
1833 $currentDay = date('d');
1834 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1835 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1836 (int ) $config->fiscalYearStart
['d'] > $currentDay
1839 $year = date('Y') - 1;
1844 $year = array('Y' => $year);
1845 $yearDate = $config->fiscalYearStart
;
1846 $yearDate = array_merge($year, $yearDate);
1847 $yearDate = CRM_Utils_Date
::format($yearDate);
1849 $monthDate = date('Ym') . '01';
1855 'yearDate' => $yearDate,
1856 'monthDate' => $monthDate,
1861 * Load objects relations to contribution object
1862 * Objects are stored in the $_relatedObjects property
1863 * In the first instance we are just moving functionality from BASEIpn -
1864 * see http://issues.civicrm.org/jira/browse/CRM-9996
1866 * @param array $input Input as delivered from Payment Processor
1867 * @param array $ids Ids as Loaded by Payment Processor
1868 * @param boolean $required Is Payment processor / contribution page required
1869 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1870 * Note that the unit test for the BaseIPN class tests this function
1875 * @param bool $required
1876 * @param bool $loadAll
1881 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1883 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1884 if(empty($ids['contact']) && isset($this->contact_id
)){
1885 $ids['contact'] = $this->contact_id
;
1888 if (empty($this->_component
)) {
1889 if (! empty($ids['event'])) {
1890 $this->_component
= 'event';
1893 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1896 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1897 $contributionType = new CRM_Financial_BAO_FinancialType();
1898 $contributionType->id
= $this->financial_type_id
;
1899 if (!$contributionType->find(TRUE)) {
1900 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1902 if (!empty($ids['contact'])) {
1903 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1904 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1905 $this->_relatedObjects
['contact']->find(TRUE);
1907 $this->_relatedObjects
['contributionType'] = $contributionType;
1909 if ($this->_component
== 'contribute') {
1910 // retrieve the other optional objects first so
1911 // stuff down the line can use this info and do things
1913 //in any case get the memberships associated with the contribution
1914 //because we now support multiple memberships w/ price set
1915 // see if there are any other memberships to be considered for same contribution.
1917 SELECT membership_id
1918 FROM civicrm_membership_payment
1919 WHERE contribution_id = %1 ";
1920 $params = array(1 => array($this->id
, 'Integer'));
1922 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1923 while ($dao->fetch()) {
1924 if ($dao->membership_id
) {
1925 if (!is_array($ids['membership'])) {
1926 $ids['membership'] = array();
1928 $ids['membership'][] = $dao->membership_id
;
1932 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1933 foreach ($ids['membership'] as $id) {
1935 $membership = new CRM_Member_BAO_Membership();
1936 $membership->id
= $id;
1937 if (!$membership->find(TRUE)) {
1938 throw new Exception("Could not find membership record: $id");
1940 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1941 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1942 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1943 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1944 $membership->free();
1949 if (!empty($ids['pledge_payment'])) {
1951 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1952 if (empty($paymentID)) {
1955 $payment = new CRM_Pledge_BAO_PledgePayment();
1956 $payment->id
= $paymentID;
1957 if (!$payment->find(TRUE)) {
1958 throw new Exception("Could not find pledge payment record: " . $paymentID);
1960 $this->_relatedObjects
['pledge_payment'][] = $payment;
1964 if (!empty($ids['contributionRecur'])) {
1965 $recur = new CRM_Contribute_BAO_ContributionRecur();
1966 $recur->id
= $ids['contributionRecur'];
1967 if (!$recur->find(TRUE)) {
1968 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1970 $this->_relatedObjects
['contributionRecur'] = &$recur;
1971 //get payment processor id from recur object.
1972 $paymentProcessorID = $recur->payment_processor_id
;
1974 //for normal contribution get the payment processor id.
1975 if (!$paymentProcessorID) {
1976 if ($this->contribution_page_id
) {
1977 // get the payment processor id from contribution page
1978 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1979 $this->contribution_page_id
,
1983 //fail to load payment processor id.
1984 elseif (empty($ids['pledge_payment'])) {
1985 $loadObjectSuccess = TRUE;
1987 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
1989 return $loadObjectSuccess;
1994 // we are in event mode
1995 // make sure event exists and is valid
1996 $event = new CRM_Event_BAO_Event();
1997 $event->id
= $ids['event'];
1998 if ($ids['event'] &&
2001 throw new Exception("Could not find event: " . $ids['event']);
2004 $this->_relatedObjects
['event'] = &$event;
2006 $participant = new CRM_Event_BAO_Participant();
2007 $participant->id
= $ids['participant'];
2008 if ($ids['participant'] &&
2009 !$participant->find(TRUE)
2011 throw new Exception("Could not find participant: " . $ids['participant']);
2013 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2015 $this->_relatedObjects
['participant'] = &$participant;
2017 if (!$paymentProcessorID) {
2018 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2022 $loadObjectSuccess = TRUE;
2023 if ($paymentProcessorID) {
2024 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2025 $this->is_test ?
'test' : 'live'
2027 $ids['paymentProcessor'] = $paymentProcessorID;
2028 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2030 elseif ($required) {
2031 $loadObjectSuccess = FALSE;
2032 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2035 return $loadObjectSuccess;
2039 * Create array of message information - ie. return html version, txt version, to field
2041 * @param array $input incoming information
2042 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2043 * just check presence of recur object but maintaining legacy approach
2045 * @param array $ids IDs of related objects
2046 * @param array $values any values that may have already been compiled by calling process
2047 * This is augmented by values 'gathered' by gatherMessageValues
2048 * @param bool $returnMessageText distinguishes between whether to send message or return
2049 * message text. We are working towards this function ALWAYS returning message text & calling
2050 * function doing emails / pdfs with it
2051 * @return array $messageArray - messages
2057 * @param bool $recur
2058 * @param bool $returnMessageText
2062 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2063 if (empty($this->_relatedObjects
)) {
2064 $this->loadRelatedObjects($input, $ids);
2066 if (empty($this->_component
)) {
2067 $this->_component
= CRM_Utils_Array
::value('component', $input);
2070 //not really sure what params might be passed in but lets merge em into values
2071 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2072 $template = CRM_Core_Smarty
::singleton();
2073 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2074 //what does recur 'mean here - to do with payment processor return functionality but
2075 // what is the importance
2076 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2077 $paymentObject = &CRM_Core_Payment
::singleton(
2078 $this->is_test ?
'test' : 'live',
2079 $this->_relatedObjects
['paymentProcessor']
2082 $entityID = $entity = NULL;
2083 if (isset($ids['contribution'])) {
2084 $entity = 'contribution';
2085 $entityID = $ids['contribution'];
2087 if (isset($ids['membership']) && $ids['membership']) {
2088 $entity = 'membership';
2089 $entityID = $ids['membership'];
2092 $url = $paymentObject->subscriptionURL($entityID, $entity);
2093 $template->assign('cancelSubscriptionUrl', $url);
2095 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2096 $template->assign('updateSubscriptionBillingUrl', $url);
2098 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2099 $template->assign('updateSubscriptionUrl', $url);
2101 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2102 //direct mode showing billing block, so use directIPN for temporary
2103 $template->assign('contributeMode', 'directIPN');
2106 // todo remove strtolower - check consistency
2107 if (strtolower($this->_component
) == 'event') {
2108 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2109 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2113 $values['contribution_id'] = $this->id
;
2114 if (!empty($ids['related_contact'])) {
2115 $values['related_contact'] = $ids['related_contact'];
2116 if (isset($ids['onbehalf_dupe_alert'])) {
2117 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2119 $entityBlock = array(
2120 'contact_id' => $ids['contact'],
2121 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2122 'Home', 'id', 'name'
2125 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2126 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2129 if ($this->is_test
) {
2132 if (!empty($this->_relatedObjects
['membership'])) {
2133 foreach ($this->_relatedObjects
['membership'] as $membership) {
2134 if ($membership->id
) {
2135 $values['membership_id'] = $membership->id
;
2137 // need to set the membership values here
2138 $template->assign('membership_assign', 1);
2139 $template->assign('membership_name',
2140 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2142 $template->assign('mem_start_date', $membership->start_date
);
2143 $template->assign('mem_join_date', $membership->join_date
);
2144 $template->assign('mem_end_date', $membership->end_date
);
2145 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2146 $template->assign('mem_status', $membership_status);
2147 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2148 $template->assign('is_pay_later', 1);
2151 // if separate payment there are two contributions recorded and the
2152 // admin will need to send a receipt for each of them separately.
2153 // we dont link the two in the db (but can potentially infer it if needed)
2154 $template->assign('is_separate_payment', 0);
2156 if ($recur && $paymentObject) {
2157 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2158 $template->assign('cancelSubscriptionUrl', $url);
2159 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2160 $template->assign('updateSubscriptionBillingUrl', $url);
2161 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2162 $template->assign('updateSubscriptionUrl', $url);
2165 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2168 // otherwise if its about sending emails, continue sending without return, as we
2169 // don't want to exit the loop.
2174 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2180 * Gather values for contribution mail - this function has been created
2181 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2182 * Values related to the contribution in question are gathered
2184 * @param array $input input into function (probably from payment processor)
2185 * @param array $ids the set of ids related to the inpurt
2187 * @return array $values
2189 * NB don't add direct calls to the function as we intend to change the signature
2198 function _gatherMessageValues($input, &$values, $ids = array()) {
2199 // set display address of contributor
2200 if ($this->address_id
) {
2201 $addressParams = array('id' => $this->address_id
);
2202 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2203 $addressDetails = array_values($addressDetails);
2204 $values['address'] = $addressDetails[0]['display'];
2206 if ($this->_component
== 'contribute') {
2207 if (isset($this->contribution_page_id
)) {
2208 CRM_Contribute_BAO_ContributionPage
::setValues(
2209 $this->contribution_page_id
,
2212 if ($this->contribution_page_id
) {
2213 // CRM-8254 - override default currency if applicable
2214 $config = CRM_Core_Config
::singleton();
2215 $config->defaultCurrency
= CRM_Utils_Array
::value(
2218 $config->defaultCurrency
2222 // no contribution page -probably back office
2224 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2225 $values['is_email_receipt'] = 1;
2226 $values['title'] = 'Contribution';
2228 // set lineItem for contribution
2230 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2231 if (!empty($lineItem)) {
2232 $itemId = key($lineItem);
2233 foreach ($lineItem as &$eachItem) {
2234 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2235 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2236 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2237 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2240 $values['lineItem'][0] = $lineItem;
2241 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2245 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2249 // if this is onbehalf of contribution then set related contact
2250 if (!empty($relatedContact['individual_id'])) {
2251 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2256 $eventParams = array(
2257 'id' => $this->_relatedObjects
['event']->id
,
2259 $values['event'] = array();
2261 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2263 //get location details
2264 $locationParams = array(
2265 'entity_id' => $this->_relatedObjects
['event']->id
,
2266 'entity_table' => 'civicrm_event',
2268 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2270 $ufJoinParams = array(
2271 'entity_table' => 'civicrm_event',
2272 'entity_id' => $ids['event'],
2273 'module' => 'CiviEvent',
2276 list($custom_pre_id,
2278 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2280 $values['custom_pre_id'] = $custom_pre_id;
2281 $values['custom_post_id'] = $custom_post_ids;
2283 // set lineItem for event contribution
2285 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2286 if (!empty($participantIds)) {
2287 foreach ($participantIds as $pIDs) {
2288 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2289 if (!CRM_Utils_System
::isNull($lineItem)) {
2290 $values['lineItem'][] = $lineItem;
2301 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2302 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2303 * Note we send directly from this function in some cases because it is only partly refactored
2304 * Don't call this function directly as the signature will change
2308 * @param $template CRM_Core_SMARTY
2309 * @param bool $recur
2310 * @param bool $returnMessageText
2314 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2315 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2316 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2317 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2318 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2319 $template->assign('useForMember', true);
2321 //assign honor information to receipt message
2322 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2324 if (isset($softRecord['soft_credit'])) {
2325 //if id of contribution page is present
2326 if (!empty($values['id'])) {
2327 $values['honor'] = array(
2328 'honor_profile_values' => array(),
2329 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2330 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2332 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2334 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2335 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2338 //offline contribution
2339 $softCreditTypes = $softCredits = array();
2340 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2341 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2342 $softCredits[$key] = array(
2343 'Name' => $softCredit['contact_name'],
2344 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2347 $template->assign('softCreditTypes', $softCreditTypes);
2348 $template->assign('softCredits', $softCredits);
2352 $dao = new CRM_Contribute_DAO_ContributionProduct();
2353 $dao->contribution_id
= $this->id
;
2354 if ($dao->find(TRUE)) {
2355 $premiumId = $dao->product_id
;
2356 $template->assign('option', $dao->product_option
);
2358 $productDAO = new CRM_Contribute_DAO_Product();
2359 $productDAO->id
= $premiumId;
2360 $productDAO->find(TRUE);
2361 $template->assign('selectPremium', TRUE);
2362 $template->assign('product_name', $productDAO->name
);
2363 $template->assign('price', $productDAO->price
);
2364 $template->assign('sku', $productDAO->sku
);
2366 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2367 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2368 if(empty($amount) && isset($this->total_amount
)){
2369 $amount = $this->total_amount
;
2371 $template->assign('amount', $amount);
2372 // add the new contribution values
2373 if (strtolower($this->_component
) == 'contribute') {
2375 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2376 $softDAO->contribution_id
= $this->id
;
2377 if ($softDAO->find(TRUE)) {
2378 $template->assign('pcpBlock', TRUE);
2379 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2380 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2381 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2383 //assign the pcp page title for email subject
2384 $pcpDAO = new CRM_PCP_DAO_PCP();
2385 $pcpDAO->id
= $softDAO->pcp_id
;
2386 if ($pcpDAO->find(TRUE)) {
2387 $template->assign('title', $pcpDAO->title
);
2392 if ($this->financial_type_id
) {
2393 $values['financial_type_id'] = $this->financial_type_id
;
2397 $template->assign('trxn_id', $this->trxn_id
);
2398 $template->assign('receive_date',
2399 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2401 $template->assign('contributeMode', 'notify');
2402 $template->assign('action', $this->is_test ?
1024 : 1);
2403 $template->assign('receipt_text',
2404 CRM_Utils_Array
::value('receipt_text',
2408 $template->assign('is_monetary', 1);
2409 $template->assign('is_recur', (bool) $recur);
2410 $template->assign('currency', $this->currency
);
2411 $template->assign('address', CRM_Utils_Address
::format($input));
2412 if ($this->_component
== 'event') {
2413 $template->assign('title', $values['event']['title']);
2414 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2415 $viewRoles = array();
2416 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2417 $viewRoles[] = $participantRoles[$v];
2419 $values['event']['participant_role'] = implode(', ', $viewRoles);
2420 $template->assign('event', $values['event']);
2421 $template->assign('location', $values['location']);
2422 $template->assign('customPre', $values['custom_pre_id']);
2423 $template->assign('customPost', $values['custom_post_id']);
2426 if ($this->_relatedObjects
['participant']->is_test
) {
2430 $values['params'] = array();
2431 //to get email of primary participant.
2432 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2433 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2434 //build an array of cId/pId of participants
2435 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2436 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2437 //send receipt to additional participant if exists
2438 if (count($additionalIDs)) {
2439 $template->assign('isPrimary', 0);
2440 $template->assign('customProfile', NULL);
2441 //set additionalParticipant true
2442 $values['params']['additionalParticipant'] = TRUE;
2443 foreach ($additionalIDs as $pId => $cId) {
2445 //to change the status pending to completed
2446 $additional = new CRM_Event_DAO_Participant();
2447 $additional->id
= $pId;
2448 $additional->contact_id
= $cId;
2449 $additional->find(TRUE);
2450 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2451 $additional->status_id
= 1;
2452 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2453 //if additional participant dont have email
2455 if (!$additionalParticipantInfo) {
2456 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2458 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2459 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2460 $additional->save();
2461 $additional->free();
2462 $template->assign('amount', $amount);
2463 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2467 //build an array of custom profile and assigning it to template
2468 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2470 if (count($customProfile)) {
2471 $template->assign('customProfile', $customProfile);
2474 // for primary contact
2475 $values['params']['additionalParticipant'] = FALSE;
2476 $template->assign('isPrimary', 1);
2477 $template->assign('amount', $primaryAmount);
2478 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2479 if ($this->payment_instrument_id
) {
2480 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2481 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2483 // carry paylater, since we did not created billing,
2484 // so need to pull email from primary location, CRM-4395
2485 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2491 * Function to check whether payment processor supports
2492 * cancellation of contribution subscription
2494 * @param int $contributionId contribution id
2496 * @param bool $isNotCancelled
2502 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2503 $cacheKeyString = "$contributionId";
2504 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2506 static $supportsCancel = array();
2508 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2509 $supportsCancel[$cacheKeyString] = FALSE;
2510 $isCancelled = FALSE;
2512 if ($isNotCancelled) {
2513 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2516 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2517 if (!empty($paymentObject)) {
2518 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2521 return $supportsCancel[$cacheKeyString];
2525 * Function to check whether subscription is already cancelled
2527 * @param int $contributionId contribution id
2529 * @return string $status contribution status
2533 static function isSubscriptionCancelled($contributionId) {
2535 SELECT cr.contribution_status_id
2536 FROM civicrm_contribution_recur cr
2537 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2538 WHERE con.id = %1 LIMIT 1";
2539 $params = array(1 => array($contributionId, 'Integer'));
2540 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2541 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2542 if ($status == 'Cancelled') {
2549 * Function to create all financial accounts entry
2551 * @param array $params contribution object, line item array and params for trxn
2554 * @param array $financialTrxnValues
2556 * @return null|object
2560 static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2561 $skipRecords = $update = $return = FALSE;
2563 $additionalParticipantId = array();
2564 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2566 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2567 $entityId = $params['participant_id'];
2568 $entityTable = 'civicrm_participant';
2569 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2571 elseif (!empty($params['membership_id'])) {
2572 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2573 // are created off one contribution should be handled elsewhere
2574 $entityId = $params['membership_id'];
2575 $entityTable = 'civicrm_membership';
2578 $entityId = $params['contribution']->id
;
2579 $entityTable = 'civicrm_contribution';
2582 $entityID[] = $entityId;
2583 if (!empty($additionalParticipantId)) {
2584 $entityID +
= $additionalParticipantId;
2586 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2587 if (empty($params['prevContribution'])) {
2594 $statusId = $params['contribution']->contribution_status_id
;
2595 // CRM-13964 partial payment
2596 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2597 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2598 $partialAmtPay = $params['partial_amount_pay'];
2599 $partialAmtTotal = $params['partial_payment_total'];
2601 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2602 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2603 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2604 $params['total_amount'] = $partialAmtPay;
2606 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2607 if (empty($balanceTrxnInfo['trxn_id'])) {
2608 // create new balance transaction record
2609 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2610 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2612 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2613 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2614 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2615 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2616 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2617 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2618 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2619 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2620 $balanceTrxnParams['status_id'] = $statusId;
2621 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2622 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2623 if (!empty($params['payment_processor'])) {
2624 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2626 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2630 // build line item array if its not set in $params
2631 if (empty($params['line_item']) ||
$additionalParticipantId) {
2632 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2635 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2636 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2637 $skipRecords = TRUE;
2638 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2639 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2640 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2641 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2643 elseif (!empty($params['payment_processor'])) {
2644 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2646 elseif (!empty($params['payment_instrument_id'])) {
2647 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2650 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2651 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2652 $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);
2655 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2656 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2657 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2660 //build financial transaction params
2661 $trxnParams = array(
2662 'contribution_id' => $params['contribution']->id
,
2663 'to_financial_account_id' => $params['to_financial_account_id'],
2664 'trxn_date' => date('YmdHis'),
2665 'total_amount' => $totalAmount,
2666 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2667 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2668 'currency' => $params['contribution']->currency
,
2669 'trxn_id' => $params['contribution']->trxn_id
,
2670 'status_id' => $statusId,
2671 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2672 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2675 if (!empty($params['payment_processor'])) {
2676 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2679 if (isset($fromFinancialAccountId)) {
2680 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2683 // consider external values passed for recording transaction entry
2684 if (!empty($financialTrxnValues)) {
2685 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2688 $params['trxnParams'] = $trxnParams;
2690 if (!empty($params['prevContribution'])) {
2691 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2692 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2693 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2694 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2695 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2696 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2697 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2699 //if financial type is changed
2700 if (!empty($params['financial_type_id']) &&
2701 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2702 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2703 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2704 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2705 if ($oldFinancialAccount != $newFinancialAccount) {
2706 $params['total_amount'] = 0;
2707 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2708 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2709 $params['prevContribution']->financial_type_id
, $relationTypeId);
2712 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2713 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2714 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2717 self
::updateFinancialAccounts($params, 'changeFinancialType');
2718 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2719 $params['financial_account_id'] = $newFinancialAccount;
2720 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2721 self
::updateFinancialAccounts($params);
2722 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2726 //Update contribution status
2727 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2728 if (!empty($params['contribution_status_id']) &&
2729 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2730 //Update Financial Records
2731 self
::updateFinancialAccounts($params, 'changedStatus');
2734 // change Payment Instrument for a Completed contribution
2735 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2736 // instrument is null and now new payment instrument is added along with the payment
2737 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2738 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2739 if (array_key_exists('payment_instrument_id', $params)) {
2740 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2741 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2742 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2743 //check if status is changed from Pending to Completed
2744 // do not update payment instrument changes for Pending to Completed
2745 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2746 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2747 // for all other statuses create new financial records
2748 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2749 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2750 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2753 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2754 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2755 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2756 // for any other payment instrument changes create new financial records
2757 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2758 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2759 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2761 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2762 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2763 // another special case when check number is changed, create new financial records
2764 // create financial trxn with negative amount
2765 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2766 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2767 // create financial trxn with positive amount
2768 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2769 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2770 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2774 //if Change contribution amount
2775 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2776 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2777 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2778 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2779 if (isset($totalAmount) &&
2780 $totalAmount != $params['prevContribution']->total_amount
) {
2781 //Update Financial Records
2782 $params['trxnParams']['from_financial_account_id'] = NULL;
2783 self
::updateFinancialAccounts($params, 'changedAmount');
2788 // records finanical trxn and entity financial trxn
2789 // also make it available as return value
2790 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2791 $params['entity_id'] = $financialTxn->id
;
2794 // record line items and finacial items
2795 if (empty($params['skipLineItem'])) {
2796 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2799 // create batch entry if batch_id is passed
2800 if (!empty($params['batch_id'])) {
2801 $entityParams = array(
2802 'batch_id' => $params['batch_id'],
2803 'entity_table' => 'civicrm_financial_trxn',
2804 'entity_id' => $financialTxn->id
,
2806 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2809 // when a fee is charged
2810 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2811 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2814 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2815 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2816 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2817 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2818 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2820 unset($params['line_item']);
2826 * Function to update all financial accounts entry
2828 * @param array $params contribution object, line item array and params for trxn
2830 * @param string $context update scenarios
2832 * @param null $skipTrxn
2837 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2838 $itemAmount = $trxnID = NULL;
2839 //get all the statuses
2840 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2841 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2842 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2843 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2844 && $context == 'changePaymentInstrument') {
2847 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2848 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2850 if ($context == 'changedStatus') {
2851 //get all the statuses
2852 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2854 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2855 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2856 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2857 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2859 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2860 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2861 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2862 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2863 $params['trxnParams']['to_financial_account_id'] = NULL;
2864 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2866 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2867 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2868 $financialTypeID, $relationTypeId);
2870 $itemAmount = $params['trxnParams']['total_amount'];
2872 elseif ($context == 'changePaymentInstrument') {
2873 if ($params['trxnParams']['total_amount'] < 0) {
2874 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2875 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2876 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2877 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2881 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2882 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2885 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2886 $params['entity_id'] = $trxn->id
;
2888 if ($context == 'changedStatus') {
2889 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2890 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2891 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2892 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2893 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2895 $entityParams = array(
2896 'entity_table' => 'civicrm_financial_item',
2897 'financial_trxn_id' => $trxn->id
,
2899 foreach ($params['line_item'] as $fieldId => $fields) {
2900 foreach ($fields as $fieldValueId => $fieldValues) {
2902 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2903 2 => array($fieldValues['id'], 'Integer'),
2905 CRM_Core_DAO
::executeQuery($query, $fparams);
2907 1 => array($fieldValues['id'], 'Integer'),
2909 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2910 while ($financialItem->fetch()) {
2911 $entityParams['entity_id'] = $financialItem->id
;
2912 $entityParams['amount'] = $financialItem->amount
;
2913 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2920 if ($context != 'changePaymentInstrument') {
2921 $itemParams['entity_table'] = 'civicrm_line_item';
2922 $trxnIds['id'] = $params['entity_id'];
2923 foreach ($params['line_item'] as $fieldId => $fields) {
2924 foreach ($fields as $fieldValueId => $fieldValues) {
2925 $prevParams['entity_id'] = $fieldValues['id'];
2926 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2928 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2929 if ($params['contribution']->receive_date
) {
2930 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2933 $financialAccount = $prevfinancialItem->financial_account_id
;
2934 if (!empty($params['financial_account_id'])) {
2935 $financialAccount = $params['financial_account_id'];
2938 $currency = $params['prevContribution']->currency
;
2939 if ($params['contribution']->currency
) {
2940 $currency = $params['contribution']->currency
;
2942 if (!empty($params['is_quick_config'])) {
2943 $amount = $itemAmount;
2945 $amount = $params['total_amount'];
2950 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
2951 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)) {
2954 $amount = $diff * $fieldValues['line_total'];
2957 $itemParams = array(
2958 'transaction_date' => $receiveDate,
2959 'contact_id' => $params['prevContribution']->contact_id
,
2960 'currency' => $currency,
2961 'amount' => $amount,
2962 'description' => $prevfinancialItem->description
,
2963 'status_id' => $prevfinancialItem->status_id
,
2964 'financial_account_id' => $financialAccount,
2965 'entity_table' => 'civicrm_line_item',
2966 'entity_id' => $fieldValues['id']
2968 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
2975 * Function to check status validation on update of a contribution
2977 * @param array $values previous form values before submit
2979 * @param array $fields the input form values
2981 * @param array $errors list of errors
2987 static function checkStatusValidation($values, &$fields, &$errors) {
2988 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
2989 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2990 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2994 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2995 $checkStatus = array(
2996 'Cancelled' => array('Completed', 'Refunded'),
2997 'Completed' => array('Cancelled', 'Refunded'),
2998 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2999 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3000 'Refunded' => array('Cancelled', 'Completed')
3003 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3004 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(1 => $contributionStatuses[$values['contribution_status_id']], 2 => $contributionStatuses[$fields['contribution_status_id']]));
3009 * Function to delete contribution of contact
3013 * @param integer $contactId contact id
3018 static function deleteContactContribution($contactId) {
3019 $contribution = new CRM_Contribute_DAO_Contribution();
3020 $contribution->contact_id
= $contactId;
3021 $contribution->find();
3022 while ($contribution->fetch()) {
3023 self
::deleteContribution($contribution->id
);
3028 * Get options for a given contribution field.
3029 * @see CRM_Core_DAO::buildOptions
3031 * @param String $fieldName
3032 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3033 * @param Array $props : whatever is known about this dao object
3035 * @return Array|bool
3037 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3038 $className = __CLASS__
;
3040 switch ($fieldName) {
3041 // This field is not part of this object but the api supports it
3042 case 'payment_processor':
3043 $className = 'CRM_Contribute_BAO_ContributionPage';
3044 // Filter results by contribution page
3045 if (!empty($props['contribution_page_id'])) {
3046 $page = civicrm_api('contribution_page', 'getsingle', array(
3048 'id' => ($props['contribution_page_id'])
3050 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3051 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3054 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3058 * Function to validate financial type
3062 * @param integer $financialTypeId Financial Type id
3064 * @param string $relationName
3066 * @return array|bool
3070 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3071 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3072 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3074 if (!$financialAccount) {
3075 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3082 * Function to record additional payment for partial and refund contributions
3084 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3085 * @param array $trxnData : to take user provided input of transaction details.
3086 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3089 * @param $contributionId
3091 * @param string $paymentType
3092 * @param null $participantId
3094 * @return null|object
3096 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3097 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3098 $getInfoOf['id'] = $contributionId;
3099 $defaults = array();
3100 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3102 if ($paymentType == 'owed') {
3103 // build params for recording financial trxn entry
3104 $params['contribution'] = $contributionDAO;
3105 $params = array_merge($defaults, $params);
3106 $params['skipLineItem'] = TRUE;
3107 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3108 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3109 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3112 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3113 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3114 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3116 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3117 $trxnId = $trxnId['trxn_id'];
3120 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3121 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3122 FROM civicrm_financial_trxn ft
3123 LEFT JOIN civicrm_entity_financial_trxn eft
3124 ON (ft.id = eft.financial_trxn_id)
3125 WHERE eft.entity_table = 'civicrm_contribution'
3126 AND eft.entity_id = {$contributionId}
3127 AND ft.to_financial_account_id != {$toFinancialAccount}
3128 AND ft.status_id = {$statusId}
3130 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3133 if ($contributionDAO->total_amount
== $sumOfPayments) {
3134 // update contribution status
3135 $contributionUpdate['id'] = $contributionId;
3136 $contributionUpdate['contribution_status_id'] = $statusId;
3137 $contributionUpdate['skipLineItem'] = TRUE;
3138 // note : not using the self::add method,
3139 // the reason because it performs 'status change' related code execution for financial records
3140 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3141 // are coded below i.e. just updating financial_item status to 'Paid'
3142 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3144 if ($participantId) {
3145 // update participant status
3146 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3147 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3148 foreach ($ids as $val) {
3149 $participantUpdate['id'] = $val;
3150 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3151 CRM_Event_BAO_Participant
::add($participantUpdate);
3155 // update financial item statuses
3156 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3157 $paidStatus = array_search('Paid', $financialItemStatus);
3159 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3160 $sqlFinancialItemUpdate = "
3161 UPDATE civicrm_financial_item fi
3162 LEFT JOIN civicrm_entity_financial_trxn eft
3163 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3164 SET status_id = {$paidStatus}
3165 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3167 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3170 elseif ($paymentType == 'refund') {
3171 // build params for recording financial trxn entry
3172 $params['contribution'] = $contributionDAO;
3173 $params = array_merge($defaults, $params);
3174 $params['skipLineItem'] = TRUE;
3175 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3176 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3178 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3179 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3180 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3182 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3184 // note : not using the self::add method,
3185 // the reason because it performs 'status change' related code execution for financial records
3186 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3187 // are coded below i.e. just updating financial_item status to 'Paid'
3188 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3190 // add financial item entry
3191 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3192 $getLine['entity_id'] = $contributionDAO->id
;
3193 $getLine['entity_table'] = 'civicrm_contribution';
3194 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3195 if (!empty($lineItemId->id
)) {
3196 $addFinancialEntry = array(
3197 'transaction_date' => $financialTrxn->trxn_date
,
3198 'contact_id' => $contributionDAO->contact_id
,
3199 'amount' => $financialTrxn->total_amount
,
3200 'status_id' => array_search('Paid', $financialItemStatus),
3201 'entity_id' => $lineItemId->id
,
3202 'entity_table' => 'civicrm_line_item'
3204 $trxnIds['id'] = $financialTrxn->id
;
3205 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3207 if ($participantId) {
3208 // update participant status
3209 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3210 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3211 foreach ($ids as $val) {
3212 $participantUpdate['id'] = $val;
3213 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3214 CRM_Event_BAO_Participant
::add($participantUpdate);
3219 // activity creation
3220 if (!empty($financialTrxn)) {
3221 if ($participantId) {
3222 $inputParams['id'] = $participantId;
3225 $component = 'event';
3226 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3227 $entityObj = $entityObj[$participantId];
3229 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3231 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3233 return $financialTrxn;
3239 * @param $activityType
3241 * @param $contributionId
3243 * @throws CRM_Core_Exception
3245 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3246 if ($component == 'event') {
3247 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3248 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3249 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3250 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3251 $targetCid = $entityObj->contact_id
;
3252 // source record id would be the contribution id
3253 $srcRecId = $contributionId;
3257 $activityParams = array(
3258 'source_contact_id' => $targetCid,
3259 'source_record_id' => $srcRecId,
3260 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3264 'subject' => $subject,
3265 'activity_date_time' => $date,
3266 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3270 'skipRecentView' => TRUE,
3273 // create activity with target contacts
3274 $session = CRM_Core_Session
::singleton();
3275 $id = $session->get('userID');
3277 $activityParams['source_contact_id'] = $id;
3278 $activityParams['target_contact_id'][] = $targetCid;
3280 CRM_Activity_BAO_Activity
::create($activityParams);
3286 * @param bool $getTrxnInfo
3287 * @param bool $usingLineTotal
3291 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3292 if ($component == 'event') {
3293 $entity = 'participant';
3294 $entityTable = 'civicrm_participant';
3295 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3297 if (!$contributionId) {
3298 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3299 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3300 $id = $primaryParticipantId;
3304 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3305 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3311 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3312 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3315 if (empty($total) ||
$usingLineTotal) {
3316 // for additional participants
3317 if ($entityTable == 'civicrm_participant') {
3318 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3320 foreach ($ids as $val) {
3321 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3325 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3329 $baseTrxnId = $total['trxn_id'];
3330 $total = $total['total_amount'];
3333 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3334 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3335 if ($paymentBalance == 0 && $contributionIsPayLater) {
3336 $paymentBalance = $total;
3339 $info['total'] = $total;
3340 $info['paid'] = $total - $paymentBalance;
3341 $info['balance'] = $paymentBalance;
3343 $info['component'] = $component;
3344 $info['payLater'] = $contributionIsPayLater;
3346 if ($getTrxnInfo && $baseTrxnId) {
3348 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3349 FROM civicrm_contribution con
3350 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3351 LEFT JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
3352 WHERE con.id = {$contributionId}
3355 // conditioned WHERE clause
3357 // if balance trxn exists don't include details of it in transaction info
3358 $sql .= " AND ft.id != {$baseTrxnId} ";
3360 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3362 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3363 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3364 while($resultDAO->fetch()) {
3365 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3366 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3368 'total_amount' => $resultDAO->total_amount
,
3369 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3370 'payment_instrument' => $paidByLabel,
3371 'receive_date' => $resultDAO->trxn_date
,
3372 'trxn_id' => $resultDAO->trxn_id
,
3373 'status' => $statuses[$resultDAO->status_id
],
3375 if ($paidByName == 'Check') {
3376 $val['check_number'] = $resultDAO->check_number
;
3380 $info['transaction'] = $rows;