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 (!$contributionID && 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;
238 $null = NULL; // return by reference
243 * Get the number of terms for this contribution for a given membership type
244 * based on querying the line item table and relevant price field values
245 * Note that any one contribution should only be able to have one line item relating to a particular membership
248 * @param int $membershipTypeID
250 * @param int $contributionID
254 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
255 $numTerms = CRM_Core_DAO
::singleValueQuery("
256 SELECT membership_num_terms FROM civicrm_line_item li
257 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
258 WHERE contribution_id = %1 AND membership_type_id = %2",
259 array(1 => array($contributionID, 'Integer') , 2 => array($membershipTypeID, 'Integer'))
261 // default of 1 is precautionary
262 return empty($numTerms) ?
1 : $numTerms;
266 * takes an associative array and creates a contribution object
268 * @param array $params (reference ) an assoc array of name/value pairs
269 * @param array $ids the array that holds all the db ids
271 * @return object CRM_Contribute_BAO_Contribution object
275 static function create(&$params, $ids = array()) {
276 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
277 foreach ($dateFields as $df) {
278 if (isset($params[$df])) {
279 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
283 $transaction = new CRM_Core_Transaction();
285 $contribution = self
::add($params, $ids);
287 if (is_a($contribution, 'CRM_Core_Error')) {
288 $transaction->rollback();
289 return $contribution;
292 $params['contribution_id'] = $contribution->id
;
294 if (!empty($params['custom']) &&
295 is_array($params['custom'])
297 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
300 $session = CRM_Core_Session
::singleton();
302 if (!empty($params['note'])) {
304 'entity_table' => 'civicrm_contribution',
305 'note' => $params['note'],
306 'entity_id' => $contribution->id
,
307 'contact_id' => $session->get('userID'),
308 'modified_date' => date('Ymd'),
310 if (!$noteParams['contact_id']) {
311 $noteParams['contact_id'] = $params['contact_id'];
313 CRM_Core_BAO_Note
::add($noteParams);
316 // make entry in batch entity batch table
317 if (!empty($params['batch_id'])) {
318 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
319 $titleFields = array(
325 $retrieveRequired = 0;
326 foreach ($titleFields as $titleField) {
327 if(!isset($contribution->$titleField)){
328 $retrieveRequired = 1;
332 if ($retrieveRequired == 1) {
333 $contribution->find(TRUE);
337 // check if activity record exist for this contribution, if
339 $activity = new CRM_Activity_DAO_Activity();
340 $activity->source_record_id
= $contribution->id
;
341 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
345 if (!$activity->find(TRUE)) {
346 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
349 // CRM-13237 : if activity record found, update it with campaign id of contribution
350 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
353 // Handle soft credit and / or link to personal campaign page
354 $softIDs = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
);
356 //Delete PCP against this contribution and create new on submitted PCP information
357 $pcpId = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditIds($contribution->id
, TRUE);
359 $deleteParams = array('id' => $pcpId);
360 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
362 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
363 $softParams = array();
364 $softParams['contribution_id'] = $contribution->id
;
365 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
366 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
367 $pcp['pcp_made_through_id'], 'contact_id'
369 $softParams['currency'] = $contribution->currency
;
370 $softParams['amount'] = $contribution->total_amount
;
371 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
372 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
373 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
374 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
375 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
377 if (isset($params['soft_credit'])) {
378 $softParams = $params['soft_credit'];
380 if (!empty($softIDs)) {
381 foreach ( $softIDs as $softID) {
382 if (!in_array($softID, $params['soft_credit_ids'])) {
383 $deleteParams = array('id' => $softID);
384 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
389 foreach ($softParams as $softParam) {
390 $softParam['contribution_id'] = $contribution->id
;
391 $softParam['currency'] = $contribution->currency
;
392 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
393 if (empty($softParam['amount'])) {
394 $softParam['amount'] = $contribution->total_amount
;
396 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
400 $transaction->commit();
402 // do not add to recent items for import, CRM-4399
403 if (empty($params['skipRecentView'])) {
404 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
405 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
407 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
408 $titleFields = array(
414 $retrieveRequired = 0;
415 foreach ($titleFields as $titleField) {
416 if(!isset($contribution->$titleField)){
417 $retrieveRequired = 1;
421 if($retrieveRequired == 1){
422 $contribution->find(TRUE);
424 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
425 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
427 $recentOther = array();
428 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
429 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
430 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
434 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
435 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
436 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
440 // add the recently created Contribution
441 CRM_Utils_Recent
::add($title,
445 $contribution->contact_id
,
451 return $contribution;
455 * Get the values for pseudoconstants for name->value and reverse.
457 * @param array $defaults (reference) the default values, some of which need to be resolved.
458 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
464 static function resolveDefaults(&$defaults, $reverse = FALSE) {
465 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
466 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
467 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
468 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
472 * This function is used to convert associative array names to values
475 * This function is used by both the web form layer and the api. Note that
476 * the api needs the name => value conversion, also the view layer typically
477 * requires value => name conversion
479 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
480 $id = $property . '_id';
482 $src = $reverse ?
$property : $id;
483 $dst = $reverse ?
$id : $property;
485 if (!array_key_exists($src, $defaults)) {
489 $look = $reverse ?
array_flip($lookup) : $lookup;
491 if (is_array($look)) {
492 if (!array_key_exists($defaults[$src], $look)) {
496 $defaults[$dst] = $look[$defaults[$src]];
501 * Takes a bunch of params that are needed to match certain criteria and
502 * retrieves the relevant objects. We'll tweak this function to be more
503 * full featured over a period of time. This is the inverse function of
504 * create. It also stores all the retrieved values in the default array
506 * @param array $params (reference ) an assoc array of name/value pairs
507 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
508 * in a hierarchical manner
509 * @param array $ids (reference) the array that holds all the db ids
511 * @return object CRM_Contribute_BAO_Contribution object
515 static function retrieve(&$params, &$defaults, &$ids) {
516 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
517 return $contribution;
521 * combine all the importable fields from the lower levels object
523 * The ordering is important, since currently we do not have a weight
524 * scheme. Adding weight is super important and should be done in the
525 * next week or so, before this can be called complete.
527 * @param string $contactType
528 * @param bool $status
530 * @return array array of importable Fields
534 static function &importableFields($contactType = 'Individual', $status = TRUE) {
535 if (!self
::$_importableFields) {
536 if (!self
::$_importableFields) {
537 self
::$_importableFields = array();
541 $fields = array('' => array('title' => ts('- do not import -')));
544 $fields = array('' => array('title' => ts('- Contribution Fields -')));
547 $note = CRM_Core_DAO_Note
::import();
548 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
549 unset($tmpFields['option_value']);
550 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
551 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
553 // Using new Dedupe rule.
555 'contact_type' => $contactType,
556 'used' => 'Unsupervised',
558 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
559 $tmpContactField = array();
560 if (is_array($fieldsArray)) {
561 foreach ($fieldsArray as $value) {
562 //skip if there is no dupe rule
563 if ($value == 'none') {
566 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
571 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
572 $tmpContactField[trim($value)] = $contactFields[trim($value)];
574 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
577 $title = $tmpContactField[trim($value)]['title'];
579 $tmpContactField[trim($value)]['title'] = $title;
583 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
584 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
585 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
586 $fields = array_merge($fields, $tmpContactField);
587 $fields = array_merge($fields, $tmpFields);
588 $fields = array_merge($fields, $note);
589 $fields = array_merge($fields, $optionFields);
590 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
591 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
592 self
::$_importableFields = $fields;
594 return self
::$_importableFields;
600 static function &exportableFields() {
601 if (!self
::$_exportableFields) {
602 if (!self
::$_exportableFields) {
603 self
::$_exportableFields = array();
606 $impFields = CRM_Contribute_DAO_Contribution
::export();
607 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
608 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
609 $typeField = CRM_Financial_DAO_FinancialType
::export();
610 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
611 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
612 $contributionStatus = array(
613 'contribution_status' => array(
614 'title' => ts('Contribution Status'),
615 'name' => 'contribution_status',
616 'data_type' => CRM_Utils_Type
::T_STRING
619 $contributionNote = array(
620 'contribution_note' =>
622 'title' => ts('Contribution Note'),
623 'name' => 'contribution_note',
624 'data_type' => CRM_Utils_Type
::T_TEXT
628 $contributionRecurId = array(
629 'contribution_recur_id' =>
631 'title' => ts('Recurring Contributions ID'),
632 'name' => 'contribution_recur_id',
633 'where' => 'civicrm_contribution.contribution_recur_id',
634 'data_type' => CRM_Utils_Type
::T_INT
637 $extraFields = array(
638 'contribution_batch' => array(
639 'title' => ts('Batch Name')
643 $softCreditFields = array(
644 'contribution_soft_credit_name' => array(
645 'name' => 'contribution_soft_credit_name',
646 'title' => 'Soft Credit For',
647 'where' => 'civicrm_contact_d.display_name',
648 'data_type' => CRM_Utils_Type
::T_STRING
650 'contribution_soft_credit_amount' => array(
651 'name' => 'contribution_soft_credit_amount',
652 'title' => 'Soft Credit Amount',
653 'where' => 'civicrm_contribution_soft.amount',
654 'data_type' => CRM_Utils_Type
::T_MONEY
656 'contribution_soft_credit_type' => array(
657 'name' => 'contribution_soft_credit_type',
658 'title' => 'Soft Credit Type',
659 'where' => 'contribution_softcredit_type.label',
660 'data_type' => CRM_Utils_Type
::T_STRING
662 'contribution_soft_credit_contribution_id' => array(
663 'name' => 'contribution_soft_credit_contribution_id',
664 'title' => 'Soft Credit For Contribution ID',
665 'where' => 'civicrm_contribution_soft.contribution_id',
666 'data_type' => CRM_Utils_Type
::T_INT
670 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
671 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
672 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
675 self
::$_exportableFields = $fields;
678 return self
::$_exportableFields;
682 * @param null $status
683 * @param null $startDate
684 * @param null $endDate
688 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
692 $where[] = 'contribution_status_id = 1';
696 $where[] = 'contribution_status_id = 3';
701 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
704 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
707 $whereCond = implode(' AND ', $where);
710 SELECT sum( total_amount ) as total_amount,
711 count( civicrm_contribution.id ) as total_count,
713 FROM civicrm_contribution
714 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
716 AND ( is_test = 0 OR is_test IS NULL )
717 AND contact.is_deleted = 0
721 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
724 while ($dao->fetch()) {
725 $count +
= $dao->total_count
;
726 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
729 return array('amount' => implode(', ', $amount),
737 * Delete the indirect records associated with this contribution first
741 * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
744 static function deleteContribution($id) {
745 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
747 $transaction = new CRM_Core_Transaction();
750 //delete activity record
752 'source_record_id' => $id,
753 // activity type id for contribution
754 'activity_type_id' => 6,
757 CRM_Activity_BAO_Activity
::deleteActivity($params);
759 //delete billing address if exists for this contribution.
760 self
::deleteAddress($id);
762 //update pledge and pledge payment, CRM-3961
763 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
765 // remove entry from civicrm_price_set_entity, CRM-5095
766 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
767 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
769 // cleanup line items.
770 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
772 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
773 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
775 if ($participantId) {
776 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
779 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
783 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
784 $noteId = key($note);
786 CRM_Core_BAO_Note
::del($noteId, FALSE);
789 $dao = new CRM_Contribute_DAO_Contribution();
792 $results = $dao->delete();
794 $transaction->commit();
796 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
798 // delete the recently created Contribution
799 $contributionRecent = array(
801 'type' => 'Contribution',
803 CRM_Utils_Recent
::del($contributionRecent);
809 * Check if there is a contribution with the same trxn_id or invoice_id
812 * @param array $duplicates (reference ) store ids of duplicate contribs
816 * @internal param array $params (reference ) an assoc array of name/value pairs
817 * @return boolean true if duplicate, false otherwise
821 static function checkDuplicate($input, &$duplicates, $id = NULL) {
823 $id = CRM_Utils_Array
::value('id', $input);
825 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
826 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
832 $clause[] = "trxn_id = %1";
833 $input[1] = array($trxn_id, 'String');
837 $clause[] = "invoice_id = %2";
838 $input[2] = array($invoice_id, 'String');
841 if (empty($clause)) {
845 $clause = implode(' OR ', $clause);
847 $clause = "( $clause ) AND id != %3";
848 $input[3] = array($id, 'Integer');
851 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
852 $dao = CRM_Core_DAO
::executeQuery($query, $input);
854 while ($dao->fetch()) {
855 $duplicates[] = $dao->id
;
862 * takes an associative array and creates a contribution_product object
864 * the function extract all the params it needs to initialize the create a
865 * contribution_product object. the params array could contain additional unused name/value
868 * @param array $params (reference ) an assoc array of name/value pairs
870 * @return object CRM_Contribute_BAO_ContributionProduct object
874 static function addPremium(&$params) {
875 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
876 $contributionProduct->copyValues($params);
877 return $contributionProduct->save();
881 * Function to get list of contribution fields for profile
882 * For now we only allow custom contribution fields to be in
885 * @param boolean $addExtraFields true if special fields needs to be added
887 * @return return the list of contribution fields
891 static function getContributionFields($addExtraFields = TRUE) {
892 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
893 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
895 if ($addExtraFields) {
896 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
899 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
901 foreach ($contributionFields as $key => $var) {
902 if ($key == 'contribution_contact_id') {
905 elseif ($key == 'contribution_campaign_id') {
906 $var['title'] = ts('Campaign');
908 $fields[$key] = $var;
911 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
916 * Function to add extra fields specific to contribtion
920 static function getSpecialContributionFields() {
921 $extraFields = array(
922 'contribution_soft_credit_name' => array(
923 'name' => 'contribution_soft_credit_name',
924 'title' => 'Soft Credit Name',
925 'headerPattern' => '/^soft_credit_name$/i',
926 'where' => 'civicrm_contact_d.display_name',
928 'contribution_soft_credit_email' => array(
929 'name' => 'contribution_soft_credit_email',
930 'title' => 'Soft Credit Email',
931 'headerPattern' => '/^soft_credit_email$/i',
932 'where' => 'soft_email.email',
934 'contribution_soft_credit_phone' => array(
935 'name' => 'contribution_soft_credit_phone',
936 'title' => 'Soft Credit Phone',
937 'headerPattern' => '/^soft_credit_phone$/i',
938 'where' => 'soft_phone.phone',
940 'contribution_soft_credit_contact_id' => array(
941 'name' => 'contribution_soft_credit_contact_id',
942 'title' => 'Soft Credit Contact ID',
943 'headerPattern' => '/^soft_credit_contact_id$/i',
944 'where' => 'civicrm_contribution_soft.contact_id',
956 static function getCurrentandGoalAmount($pageID) {
958 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
959 FROM civicrm_contribution_page p,
960 civicrm_contribution c
961 WHERE p.id = c.contribution_page_id
963 AND c.cancel_date is null
967 $config = CRM_Core_Config
::singleton();
968 $params = array(1 => array($pageID, 'Integer'));
969 $dao = CRM_Core_DAO
::executeQuery($query, $params);
972 return array($dao->goal
, $dao->total
);
975 return array(NULL, NULL);
980 * Function to get list of contribution In Honor of contact Ids
982 * @param int $honorId In Honor of Contact ID
984 * @return return the list of contribution fields
989 static function getHonorContacts($honorId) {
991 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
992 $honorDAO->contact_id
= $honorId;
995 $type = CRM_Contribute_PseudoConstant
::financialType();
997 while ($honorDAO->fetch()) {
998 $contributionDAO = new CRM_Contribute_DAO_Contribution();
999 $contributionDAO->id
= $honorDAO->contribution_id
;
1001 if ($contributionDAO->find(TRUE)) {
1002 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
1003 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1004 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1005 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1006 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1007 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1008 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1009 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1010 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1018 * function to get the sort name of a contact for a particular contribution
1020 * @param int $id id of the contribution
1022 * @return null|string sort name of the contact if found
1026 static function sortName($id) {
1027 $id = CRM_Utils_Type
::escape($id, 'Integer');
1030 SELECT civicrm_contact.sort_name
1031 FROM civicrm_contribution, civicrm_contact
1032 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1033 AND civicrm_contribution.id = {$id}
1035 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1043 static function annual($contactID) {
1044 if (is_array($contactID)) {
1045 $contactIDs = implode(',', $contactID);
1048 $contactIDs = $contactID;
1051 $config = CRM_Core_Config
::singleton();
1052 $startDate = $endDate = NULL;
1054 $currentMonth = date('m');
1055 $currentDay = date('d');
1056 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1057 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1058 (int ) $config->fiscalYearStart
['d'] > $currentDay
1061 $year = date('Y') - 1;
1066 $nextYear = $year +
1;
1068 if ($config->fiscalYearStart
) {
1069 if ($config->fiscalYearStart
['M'] < 10) {
1070 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1072 if ($config->fiscalYearStart
['d'] < 10) {
1073 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1075 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1080 $startDate = "$year$monthDay";
1081 $endDate = "$nextYear$monthDay";
1084 SELECT count(*) as count,
1085 sum(total_amount) as amount,
1086 avg(total_amount) as average,
1088 FROM civicrm_contribution b
1089 WHERE b.contact_id IN ( $contactIDs )
1090 AND b.contribution_status_id = 1
1092 AND b.receive_date >= $startDate
1093 AND b.receive_date < $endDate
1096 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1098 $amount = $average = array();
1099 while ($dao->fetch()) {
1100 if ($dao->count
> 0 && $dao->amount
> 0) {
1101 $count +
= $dao->count
;
1102 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1103 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1109 implode(', ', $amount),
1110 implode(', ', $average),
1113 return array(0, 0, 0);
1117 * Check if there is a contribution with the params passed in.
1118 * Used for trxn_id,invoice_id and contribution_id
1120 * @param array $params an assoc array of name/value pairs
1122 * @return array contribution id if success else NULL
1126 static function checkDuplicateIds($params) {
1127 $dao = new CRM_Contribute_DAO_Contribution();
1131 foreach ($params as $k => $v) {
1133 $clause[] = "$k = '$v'";
1136 $clause = implode(' AND ', $clause);
1137 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1138 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1140 while ($dao->fetch()) {
1148 * Function to get the contribution details for component export
1150 * @param int $exportMode export mode
1151 * @param string $componentIds component ids
1153 * @return array associated array
1158 static function getContributionDetails($exportMode, $componentIds) {
1159 $paymentDetails = array();
1160 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1162 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1163 $componentSelect = " civicrm_participant_payment.participant_id id";
1164 $additionalClause = "
1165 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1166 AND civicrm_participant_payment.participant_id {$componentClause} )
1169 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1170 $componentSelect = " civicrm_membership_payment.membership_id id";
1171 $additionalClause = "
1172 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1173 AND civicrm_membership_payment.membership_id {$componentClause} )
1176 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1177 $componentSelect = " civicrm_pledge_payment.id id";
1178 $additionalClause = "
1179 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1180 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1184 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1185 trxn_id, {$componentSelect}
1186 FROM civicrm_contribution
1187 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1188 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1189 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1190 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1191 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1192 AND option_group_contribution_status.id = contribution_status.option_group_id )
1196 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1198 while ($dao->fetch()) {
1199 $paymentDetails[$dao->id
] = array(
1200 'total_amount' => $dao->total_amount
,
1201 'contribution_status' => $dao->status
,
1202 'receive_date' => $dao->receive_date
,
1203 'pay_instru' => $dao->payment_instrument
,
1204 'trxn_id' => $dao->trxn_id
,
1208 return $paymentDetails;
1212 * Function to create address associated with contribution record.
1214 * @param array $params an associated array
1215 * @param $billingLocationTypeID
1217 * @internal param int $billingID $billingLocationTypeID
1219 * @return address id
1222 static function createAddress(&$params, $billingLocationTypeID) {
1223 $billingFields = array(
1226 'state_province_id',
1231 //build address array
1232 $addressParams = array();
1233 $addressParams['location_type_id'] = $billingLocationTypeID;
1234 $addressParams['is_billing'] = 1;
1236 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1237 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1238 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1239 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1241 foreach ($billingFields as $value) {
1242 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1245 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1247 return $address->id
;
1251 * Delete billing address record related contribution
1253 * @param null $contributionId
1254 * @param null $contactId
1256 * @internal param int $contact_id contact id
1257 * @internal param int $contribution_id contributionId
1261 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1263 $contactJoin = NULL;
1265 if ($contributionId) {
1266 $clauses[] = "cc.id = {$contributionId}";
1270 $clauses[] = "cco.id = {$contactId}";
1271 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1274 if (empty($clauses)) {
1275 CRM_Core_Error
::fatal();
1278 $condition = implode(' OR ', $clauses);
1282 FROM civicrm_address ca
1283 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1287 $dao = CRM_Core_DAO
::executeQuery($query);
1289 while ($dao->fetch()) {
1290 $params = array('id' => $dao->id
);
1291 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1296 * This function check online pending contribution associated w/
1297 * Online Event Registration or Online Membership signup.
1299 * @param int $componentId participant/membership id.
1300 * @param string $componentName Event/Membership.
1302 * @return $contributionId pending contribution id.
1305 static function checkOnlinePendingContribution($componentId, $componentName) {
1306 $contributionId = NULL;
1307 if (!$componentId ||
1308 !in_array($componentName, array('Event', 'Membership'))
1310 return $contributionId;
1313 if ($componentName == 'Event') {
1314 $idName = 'participant_id';
1315 $componentTable = 'civicrm_participant';
1316 $paymentTable = 'civicrm_participant_payment';
1317 $source = ts('Online Event Registration');
1320 if ($componentName == 'Membership') {
1321 $idName = 'membership_id';
1322 $componentTable = 'civicrm_membership';
1323 $paymentTable = 'civicrm_membership_payment';
1324 $source = ts('Online Contribution');
1327 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1330 SELECT component.id as {$idName},
1331 componentPayment.contribution_id as contribution_id,
1332 contribution.source source,
1333 contribution.contribution_status_id as contribution_status_id,
1334 contribution.is_pay_later as is_pay_later
1335 FROM $componentTable component
1336 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1337 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1338 WHERE component.id = {$componentId}";
1340 $dao = CRM_Core_DAO
::executeQuery($query);
1342 while ($dao->fetch()) {
1343 if ($dao->contribution_id
&&
1344 $dao->is_pay_later
&&
1345 $dao->contribution_status_id
== $pendingStatusId &&
1346 strpos($dao->source
, $source) !== FALSE
1348 $contributionId = $dao->contribution_id
;
1353 return $contributionId;
1357 * This function update contribution as well as related objects.
1359 static function transitionComponents($params, $processContributionObject = FALSE) {
1360 // get minimum required values.
1361 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1362 $componentId = CRM_Utils_Array
::value('component_id', $params);
1363 $componentName = CRM_Utils_Array
::value('componentName', $params);
1364 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1365 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1367 // if we already processed contribution object pass previous status id.
1368 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1370 $updateResult = array();
1372 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1374 // we process only ( Completed, Cancelled, or Failed ) contributions.
1375 if (!$contributionId ||
1376 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1377 array_search('Cancelled', $contributionStatuses),
1378 array_search('Failed', $contributionStatuses),
1381 return $updateResult;
1384 if (!$componentName ||
!$componentId) {
1385 // get the related component details.
1386 $componentDetails = self
::getComponentDetails($contributionId);
1389 $componentDetails['contact_id'] = $contactId;
1390 $componentDetails['component'] = $componentName;
1392 if ($componentName == 'event') {
1393 $componentDetails['participant'] = $componentId;
1396 $componentDetails['membership'] = $componentId;
1400 if (!empty($componentDetails['contact_id'])) {
1401 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1407 // do check for required ids.
1408 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1409 return $updateResult;
1412 //now we are ready w/ required ids, start processing.
1414 $baseIPN = new CRM_Core_Payment_BaseIPN();
1416 $input = $ids = $objects = array();
1418 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1419 $ids['contribution'] = $contributionId;
1420 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1421 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1422 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1423 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1424 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1425 $ids['contributionRecur'] = NULL;
1426 $ids['contributionPage'] = NULL;
1428 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1429 CRM_Core_Error
::fatal();
1432 $memberships = &$objects['membership'];
1433 $participant = &$objects['participant'];
1434 $pledgePayment = &$objects['pledge_payment'];
1435 $contribution = &$objects['contribution'];
1437 if ($pledgePayment) {
1438 $pledgePaymentIDs = array();
1439 foreach ($pledgePayment as $key => $object) {
1440 $pledgePaymentIDs[] = $object->id
;
1442 $pledgeID = $pledgePayment[0]->pledge_id
;
1445 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1448 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1449 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1454 // we might want to process contribution object.
1455 $processContribution = FALSE;
1456 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1457 if (is_array($memberships)) {
1458 foreach ($memberships as $membership) {
1460 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1461 $membership->save();
1463 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1464 if ($processContributionObject) {
1465 $processContribution = TRUE;
1472 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1473 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1475 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1476 if ($processContributionObject) {
1477 $processContribution = TRUE;
1481 if ($pledgePayment) {
1482 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1484 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1485 if ($processContributionObject) {
1486 $processContribution = TRUE;
1490 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1491 if (is_array($memberships)) {
1492 foreach ($memberships as $membership) {
1494 $membership->status_id
= array_search('Expired', $membershipStatuses);
1495 $membership->save();
1497 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1498 if ($processContributionObject) {
1499 $processContribution = TRUE;
1505 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1506 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1508 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1509 if ($processContributionObject) {
1510 $processContribution = TRUE;
1514 if ($pledgePayment) {
1515 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1517 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1518 if ($processContributionObject) {
1519 $processContribution = TRUE;
1523 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1525 // only pending contribution related object processed.
1526 if ($previousContriStatusId &&
1527 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1529 // this is case when we already processed contribution object.
1530 return $updateResult;
1532 elseif (!$previousContriStatusId &&
1533 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1535 // this is case when we are going to process contribution object later.
1536 return $updateResult;
1539 if (is_array($memberships)) {
1540 foreach ($memberships as $membership) {
1545 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1546 $membership->membership_type_id
,
1547 $membership->is_test
, $membership->id
1550 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1551 // this picks up membership type changes during renewals
1553 SELECT membership_type_id
1554 FROM civicrm_membership_log
1555 WHERE membership_id=$membership->id
1558 $dao = new CRM_Core_DAO
;
1560 if ($dao->fetch()) {
1561 if (!empty($dao->membership_type_id
)) {
1562 $membership->membership_type_id
= $dao->membership_type_id
;
1563 $membership->save();
1566 // else fall back to using current membership type
1569 // Figure out number of terms
1571 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1572 foreach ($lineitems as $lineitem) {
1573 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1574 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1576 // in case membership_num_terms comes through as null or zero
1577 $numterms = $numterms >= 1 ?
$numterms : 1;
1582 if ($currentMembership) {
1583 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1584 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1585 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1588 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1591 //get the status for membership.
1592 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1594 $dates['join_date'],
1597 $membership->membership_type_id
,
1601 $formattedParams = array(
1602 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1603 array_search('Current', $membershipStatuses)
1605 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1606 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1607 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1610 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1612 $membership->copyValues($formattedParams);
1613 $membership->save();
1615 //updating the membership log
1616 $membershipLog = array();
1617 $membershipLog = $formattedParams;
1618 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1619 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1621 $membershipLog['start_date'] = $logStartDate;
1622 $membershipLog['membership_id'] = $membership->id
;
1623 $membershipLog['modified_id'] = $membership->contact_id
;
1624 $membershipLog['modified_date'] = date('Ymd');
1625 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1627 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1629 //update related Memberships.
1630 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1632 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1635 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1636 if ($processContributionObject) {
1637 $processContribution = TRUE;
1640 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1646 $updatedStatusId = array_search('Registered', $participantStatuses);
1647 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1649 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1650 if ($processContributionObject) {
1651 $processContribution = TRUE;
1655 if ($pledgePayment) {
1656 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1658 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1659 if ($processContributionObject) {
1660 $processContribution = TRUE;
1665 // process contribution object.
1666 if ($processContribution) {
1667 $contributionParams = array();
1669 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1670 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1671 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1673 foreach ($fields as $field) {
1674 if (empty($params[$field])) {
1677 $contributionParams[$field] = $params[$field];
1680 $ids = array('contribution' => $contributionId);
1681 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1684 return $updateResult;
1688 * This function returns all contribution related object ids.
1690 public static function getComponentDetails($contributionId) {
1691 $componentDetails = $pledgePayment = array();
1692 if (!$contributionId) {
1693 return $componentDetails;
1697 SELECT c.id as contribution_id,
1698 c.contact_id as contact_id,
1699 mp.membership_id as membership_id,
1700 m.membership_type_id as membership_type_id,
1701 pp.participant_id as participant_id,
1702 p.event_id as event_id,
1703 pgp.id as pledge_payment_id
1704 FROM civicrm_contribution c
1705 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1706 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1707 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1708 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1709 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1710 WHERE c.id = $contributionId";
1712 $dao = CRM_Core_DAO
::executeQuery($query);
1713 $componentDetails = array();
1715 while ($dao->fetch()) {
1716 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1717 $componentDetails['contact_id'] = $dao->contact_id
;
1718 if ($dao->event_id
) {
1719 $componentDetails['event'] = $dao->event_id
;
1721 if ($dao->participant_id
) {
1722 $componentDetails['participant'] = $dao->participant_id
;
1724 if ($dao->membership_id
) {
1725 if (!isset($componentDetails['membership'])) {
1726 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1728 $componentDetails['membership'][] = $dao->membership_id
;
1729 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1731 if ($dao->pledge_payment_id
) {
1732 $pledgePayment[] = $dao->pledge_payment_id
;
1736 if ($pledgePayment) {
1737 $componentDetails['pledge_payment'] = $pledgePayment;
1740 return $componentDetails;
1745 * @param bool $includeSoftCredit
1747 * @return null|string
1749 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1754 $contactContributionsSQL = "
1755 SELECT contribution.id AS id
1756 FROM civicrm_contribution contribution
1757 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1759 $contactSoftCreditContributionsSQL = "
1760 SELECT contribution.id
1761 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1762 ON ( contribution.id = softContribution.contribution_id )
1763 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1764 $query = "SELECT count( x.id ) count FROM ( ";
1765 $query .= $contactContributionsSQL;
1767 if ($includeSoftCredit) {
1768 $query .= " UNION ";
1769 $query .= $contactSoftCreditContributionsSQL;
1774 return CRM_Core_DAO
::singleValueQuery($query);
1778 * Function to get individual id for onbehalf contribution
1780 * @param int $contributionId contribution id
1781 * @param int $contributorId contributor id
1783 * @return array $ids containing organization id and individual id
1786 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1790 if (!$contributionId) {
1794 // fetch contributor id if null
1795 if (!$contributorId) {
1796 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1797 $contributionId, 'contact_id'
1801 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1802 $activityTypeId = array_search('Contribution', $activityTypeIds);
1804 if ($activityTypeId && $contributorId) {
1806 SELECT civicrm_activity_contact.contact_id
1807 FROM civicrm_activity_contact
1808 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1809 WHERE civicrm_activity.activity_type_id = %1
1810 AND civicrm_activity.source_record_id = %2
1811 AND civicrm_activity_contact.record_type_id = %3
1814 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1815 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1818 1 => array($activityTypeId, 'Integer'),
1819 2 => array($contributionId, 'Integer'),
1820 3 => array($sourceID, 'Integer'),
1823 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1825 // for on behalf contribution source is individual and contributor is organization
1826 if ($sourceContactId && $sourceContactId != $contributorId) {
1827 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1828 // get rel type id for employee of relation
1829 foreach ($relationshipTypeIds as $id => $typeVals) {
1830 if ($typeVals['name_a_b'] == 'Employee of') {
1831 $relationshipTypeId = $id;
1836 $rel = new CRM_Contact_DAO_Relationship();
1837 $rel->relationship_type_id
= $relationshipTypeId;
1838 $rel->contact_id_a
= $sourceContactId;
1839 $rel->contact_id_b
= $contributorId;
1840 if ($rel->find(TRUE)) {
1841 $ids['individual_id'] = $rel->contact_id_a
;
1842 $ids['organization_id'] = $rel->contact_id_b
;
1854 static function getContributionDates() {
1855 $config = CRM_Core_Config
::singleton();
1856 $currentMonth = date('m');
1857 $currentDay = date('d');
1858 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1859 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1860 (int ) $config->fiscalYearStart
['d'] > $currentDay
1863 $year = date('Y') - 1;
1868 $year = array('Y' => $year);
1869 $yearDate = $config->fiscalYearStart
;
1870 $yearDate = array_merge($year, $yearDate);
1871 $yearDate = CRM_Utils_Date
::format($yearDate);
1873 $monthDate = date('Ym') . '01';
1879 'yearDate' => $yearDate,
1880 'monthDate' => $monthDate,
1885 * Load objects relations to contribution object
1886 * Objects are stored in the $_relatedObjects property
1887 * In the first instance we are just moving functionality from BASEIpn -
1888 * see http://issues.civicrm.org/jira/browse/CRM-9996
1890 * @param array $input Input as delivered from Payment Processor
1891 * @param array $ids Ids as Loaded by Payment Processor
1892 * @param boolean $required Is Payment processor / contribution page required
1893 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1894 * Note that the unit test for the BaseIPN class tests this function
1899 * @param bool $required
1900 * @param bool $loadAll
1905 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1907 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1908 if(empty($ids['contact']) && isset($this->contact_id
)){
1909 $ids['contact'] = $this->contact_id
;
1912 if (empty($this->_component
)) {
1913 if (! empty($ids['event'])) {
1914 $this->_component
= 'event';
1917 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1920 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1921 $contributionType = new CRM_Financial_BAO_FinancialType();
1922 $contributionType->id
= $this->financial_type_id
;
1923 if (!$contributionType->find(TRUE)) {
1924 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1926 if (!empty($ids['contact'])) {
1927 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1928 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1929 $this->_relatedObjects
['contact']->find(TRUE);
1931 $this->_relatedObjects
['contributionType'] = $contributionType;
1933 if ($this->_component
== 'contribute') {
1934 // retrieve the other optional objects first so
1935 // stuff down the line can use this info and do things
1937 //in any case get the memberships associated with the contribution
1938 //because we now support multiple memberships w/ price set
1939 // see if there are any other memberships to be considered for same contribution.
1941 SELECT membership_id
1942 FROM civicrm_membership_payment
1943 WHERE contribution_id = %1 ";
1944 $params = array(1 => array($this->id
, 'Integer'));
1946 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1947 while ($dao->fetch()) {
1948 if ($dao->membership_id
) {
1949 if (!is_array($ids['membership'])) {
1950 $ids['membership'] = array();
1952 $ids['membership'][] = $dao->membership_id
;
1956 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1957 foreach ($ids['membership'] as $id) {
1959 $membership = new CRM_Member_BAO_Membership();
1960 $membership->id
= $id;
1961 if (!$membership->find(TRUE)) {
1962 throw new Exception("Could not find membership record: $id");
1964 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1965 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1966 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1967 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1968 $membership->free();
1973 if (!empty($ids['pledge_payment'])) {
1975 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1976 if (empty($paymentID)) {
1979 $payment = new CRM_Pledge_BAO_PledgePayment();
1980 $payment->id
= $paymentID;
1981 if (!$payment->find(TRUE)) {
1982 throw new Exception("Could not find pledge payment record: " . $paymentID);
1984 $this->_relatedObjects
['pledge_payment'][] = $payment;
1988 if (!empty($ids['contributionRecur'])) {
1989 $recur = new CRM_Contribute_BAO_ContributionRecur();
1990 $recur->id
= $ids['contributionRecur'];
1991 if (!$recur->find(TRUE)) {
1992 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1994 $this->_relatedObjects
['contributionRecur'] = &$recur;
1995 //get payment processor id from recur object.
1996 $paymentProcessorID = $recur->payment_processor_id
;
1998 //for normal contribution get the payment processor id.
1999 if (!$paymentProcessorID) {
2000 if ($this->contribution_page_id
) {
2001 // get the payment processor id from contribution page
2002 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2003 $this->contribution_page_id
,
2007 //fail to load payment processor id.
2008 elseif (empty($ids['pledge_payment'])) {
2009 $loadObjectSuccess = TRUE;
2011 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
2013 return $loadObjectSuccess;
2018 // we are in event mode
2019 // make sure event exists and is valid
2020 $event = new CRM_Event_BAO_Event();
2021 $event->id
= $ids['event'];
2022 if ($ids['event'] &&
2025 throw new Exception("Could not find event: " . $ids['event']);
2028 $this->_relatedObjects
['event'] = &$event;
2030 $participant = new CRM_Event_BAO_Participant();
2031 $participant->id
= $ids['participant'];
2032 if ($ids['participant'] &&
2033 !$participant->find(TRUE)
2035 throw new Exception("Could not find participant: " . $ids['participant']);
2037 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2039 $this->_relatedObjects
['participant'] = &$participant;
2041 if (!$paymentProcessorID) {
2042 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2046 $loadObjectSuccess = TRUE;
2047 if ($paymentProcessorID) {
2048 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2049 $this->is_test ?
'test' : 'live'
2051 $ids['paymentProcessor'] = $paymentProcessorID;
2052 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
2054 elseif ($required) {
2055 $loadObjectSuccess = FALSE;
2056 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
2059 return $loadObjectSuccess;
2063 * Create array of message information - ie. return html version, txt version, to field
2065 * @param array $input incoming information
2066 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2067 * just check presence of recur object but maintaining legacy approach
2069 * @param array $ids IDs of related objects
2070 * @param array $values any values that may have already been compiled by calling process
2071 * This is augmented by values 'gathered' by gatherMessageValues
2072 * @param bool $returnMessageText distinguishes between whether to send message or return
2073 * message text. We are working towards this function ALWAYS returning message text & calling
2074 * function doing emails / pdfs with it
2075 * @return array $messageArray - messages
2081 * @param bool $recur
2082 * @param bool $returnMessageText
2086 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2087 if (empty($this->_relatedObjects
)) {
2088 $this->loadRelatedObjects($input, $ids);
2090 if (empty($this->_component
)) {
2091 $this->_component
= CRM_Utils_Array
::value('component', $input);
2094 //not really sure what params might be passed in but lets merge em into values
2095 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2096 $template = CRM_Core_Smarty
::singleton();
2097 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2098 //what does recur 'mean here - to do with payment processor return functionality but
2099 // what is the importance
2100 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2101 $paymentObject = &CRM_Core_Payment
::singleton(
2102 $this->is_test ?
'test' : 'live',
2103 $this->_relatedObjects
['paymentProcessor']
2106 $entityID = $entity = NULL;
2107 if (isset($ids['contribution'])) {
2108 $entity = 'contribution';
2109 $entityID = $ids['contribution'];
2111 if (isset($ids['membership']) && $ids['membership']) {
2112 $entity = 'membership';
2113 $entityID = $ids['membership'];
2116 $url = $paymentObject->subscriptionURL($entityID, $entity);
2117 $template->assign('cancelSubscriptionUrl', $url);
2119 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2120 $template->assign('updateSubscriptionBillingUrl', $url);
2122 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2123 $template->assign('updateSubscriptionUrl', $url);
2125 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2126 //direct mode showing billing block, so use directIPN for temporary
2127 $template->assign('contributeMode', 'directIPN');
2130 // todo remove strtolower - check consistency
2131 if (strtolower($this->_component
) == 'event') {
2132 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2133 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2137 $values['contribution_id'] = $this->id
;
2138 if (!empty($ids['related_contact'])) {
2139 $values['related_contact'] = $ids['related_contact'];
2140 if (isset($ids['onbehalf_dupe_alert'])) {
2141 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2143 $entityBlock = array(
2144 'contact_id' => $ids['contact'],
2145 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2146 'Home', 'id', 'name'
2149 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2150 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2153 if ($this->is_test
) {
2156 if (!empty($this->_relatedObjects
['membership'])) {
2157 foreach ($this->_relatedObjects
['membership'] as $membership) {
2158 if ($membership->id
) {
2159 $values['isMembership'] = TRUE;
2161 // need to set the membership values here
2162 $template->assign('membership_assign', 1);
2163 $template->assign('membership_name',
2164 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2166 $template->assign('mem_start_date', $membership->start_date
);
2167 $template->assign('mem_join_date', $membership->join_date
);
2168 $template->assign('mem_end_date', $membership->end_date
);
2169 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2170 $template->assign('mem_status', $membership_status);
2171 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2172 $template->assign('is_pay_later', 1);
2175 // if separate payment there are two contributions recorded and the
2176 // admin will need to send a receipt for each of them separately.
2177 // we dont link the two in the db (but can potentially infer it if needed)
2178 $template->assign('is_separate_payment', 0);
2180 if ($recur && $paymentObject) {
2181 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2182 $template->assign('cancelSubscriptionUrl', $url);
2183 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2184 $template->assign('updateSubscriptionBillingUrl', $url);
2185 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2186 $template->assign('updateSubscriptionUrl', $url);
2189 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2192 // otherwise if its about sending emails, continue sending without return, as we
2193 // don't want to exit the loop.
2198 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2204 * Gather values for contribution mail - this function has been created
2205 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2206 * Values related to the contribution in question are gathered
2208 * @param array $input input into function (probably from payment processor)
2209 * @param array $ids the set of ids related to the inpurt
2211 * @return array $values
2213 * NB don't add direct calls to the function as we intend to change the signature
2222 function _gatherMessageValues($input, &$values, $ids = array()) {
2223 // set display address of contributor
2224 if ($this->address_id
) {
2225 $addressParams = array('id' => $this->address_id
);
2226 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2227 $addressDetails = array_values($addressDetails);
2228 $values['address'] = $addressDetails[0]['display'];
2230 if ($this->_component
== 'contribute') {
2231 if (isset($this->contribution_page_id
)) {
2232 CRM_Contribute_BAO_ContributionPage
::setValues(
2233 $this->contribution_page_id
,
2236 if ($this->contribution_page_id
) {
2237 // CRM-8254 - override default currency if applicable
2238 $config = CRM_Core_Config
::singleton();
2239 $config->defaultCurrency
= CRM_Utils_Array
::value(
2242 $config->defaultCurrency
2246 // no contribution page -probably back office
2248 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2249 $values['is_email_receipt'] = 1;
2250 $values['title'] = 'Contribution';
2252 // set lineItem for contribution
2254 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2255 if (!empty($lineItem)) {
2256 $itemId = key($lineItem);
2257 foreach ($lineItem as &$eachItem) {
2258 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2259 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2260 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2261 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2264 $values['lineItem'][0] = $lineItem;
2265 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2269 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2273 // if this is onbehalf of contribution then set related contact
2274 if (!empty($relatedContact['individual_id'])) {
2275 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2280 $eventParams = array(
2281 'id' => $this->_relatedObjects
['event']->id
,
2283 $values['event'] = array();
2285 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2287 //get location details
2288 $locationParams = array(
2289 'entity_id' => $this->_relatedObjects
['event']->id
,
2290 'entity_table' => 'civicrm_event',
2292 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2294 $ufJoinParams = array(
2295 'entity_table' => 'civicrm_event',
2296 'entity_id' => $ids['event'],
2297 'module' => 'CiviEvent',
2300 list($custom_pre_id,
2302 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2304 $values['custom_pre_id'] = $custom_pre_id;
2305 $values['custom_post_id'] = $custom_post_ids;
2307 // set lineItem for event contribution
2309 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2310 if (!empty($participantIds)) {
2311 foreach ($participantIds as $pIDs) {
2312 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2313 if (!CRM_Utils_System
::isNull($lineItem)) {
2314 $values['lineItem'][] = $lineItem;
2325 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2326 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2327 * Note we send directly from this function in some cases because it is only partly refactored
2328 * Don't call this function directly as the signature will change
2332 * @param $template CRM_Core_SMARTY
2333 * @param bool $recur
2334 * @param bool $returnMessageText
2338 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2339 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2340 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2341 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2342 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2343 $template->assign('useForMember', true);
2345 //assign honor information to receipt message
2346 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2348 if (isset($softRecord['soft_credit'])) {
2349 //if id of contribution page is present
2350 if (!empty($values['id'])) {
2351 $values['honor'] = array(
2352 'honor_profile_values' => array(),
2353 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2354 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2356 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2358 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2359 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2362 //offline contribution
2363 $softCreditTypes = $softCredits = array();
2364 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2365 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2366 $softCredits[$key] = array(
2367 'Name' => $softCredit['contact_name'],
2368 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2371 $template->assign('softCreditTypes', $softCreditTypes);
2372 $template->assign('softCredits', $softCredits);
2376 $dao = new CRM_Contribute_DAO_ContributionProduct();
2377 $dao->contribution_id
= $this->id
;
2378 if ($dao->find(TRUE)) {
2379 $premiumId = $dao->product_id
;
2380 $template->assign('option', $dao->product_option
);
2382 $productDAO = new CRM_Contribute_DAO_Product();
2383 $productDAO->id
= $premiumId;
2384 $productDAO->find(TRUE);
2385 $template->assign('selectPremium', TRUE);
2386 $template->assign('product_name', $productDAO->name
);
2387 $template->assign('price', $productDAO->price
);
2388 $template->assign('sku', $productDAO->sku
);
2390 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2391 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2392 if(empty($amount) && isset($this->total_amount
)){
2393 $amount = $this->total_amount
;
2395 $template->assign('amount', $amount);
2396 // add the new contribution values
2397 if (strtolower($this->_component
) == 'contribute') {
2399 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2400 $softDAO->contribution_id
= $this->id
;
2401 if ($softDAO->find(TRUE)) {
2402 $template->assign('pcpBlock', TRUE);
2403 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2404 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2405 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2407 //assign the pcp page title for email subject
2408 $pcpDAO = new CRM_PCP_DAO_PCP();
2409 $pcpDAO->id
= $softDAO->pcp_id
;
2410 if ($pcpDAO->find(TRUE)) {
2411 $template->assign('title', $pcpDAO->title
);
2416 if ($this->financial_type_id
) {
2417 $values['financial_type_id'] = $this->financial_type_id
;
2421 $template->assign('trxn_id', $this->trxn_id
);
2422 $template->assign('receive_date',
2423 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2425 $template->assign('contributeMode', 'notify');
2426 $template->assign('action', $this->is_test ?
1024 : 1);
2427 $template->assign('receipt_text',
2428 CRM_Utils_Array
::value('receipt_text',
2432 $template->assign('is_monetary', 1);
2433 $template->assign('is_recur', (bool) $recur);
2434 $template->assign('currency', $this->currency
);
2435 $template->assign('address', CRM_Utils_Address
::format($input));
2436 if ($this->_component
== 'event') {
2437 $template->assign('title', $values['event']['title']);
2438 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2439 $viewRoles = array();
2440 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2441 $viewRoles[] = $participantRoles[$v];
2443 $values['event']['participant_role'] = implode(', ', $viewRoles);
2444 $template->assign('event', $values['event']);
2445 $template->assign('location', $values['location']);
2446 $template->assign('customPre', $values['custom_pre_id']);
2447 $template->assign('customPost', $values['custom_post_id']);
2450 if ($this->_relatedObjects
['participant']->is_test
) {
2454 $values['params'] = array();
2455 //to get email of primary participant.
2456 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2457 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2458 //build an array of cId/pId of participants
2459 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2460 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2461 //send receipt to additional participant if exists
2462 if (count($additionalIDs)) {
2463 $template->assign('isPrimary', 0);
2464 $template->assign('customProfile', NULL);
2465 //set additionalParticipant true
2466 $values['params']['additionalParticipant'] = TRUE;
2467 foreach ($additionalIDs as $pId => $cId) {
2469 //to change the status pending to completed
2470 $additional = new CRM_Event_DAO_Participant();
2471 $additional->id
= $pId;
2472 $additional->contact_id
= $cId;
2473 $additional->find(TRUE);
2474 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2475 $additional->status_id
= 1;
2476 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2477 //if additional participant dont have email
2479 if (!$additionalParticipantInfo) {
2480 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2482 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2483 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2484 $additional->save();
2485 $additional->free();
2486 $template->assign('amount', $amount);
2487 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2491 //build an array of custom profile and assigning it to template
2492 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2494 if (count($customProfile)) {
2495 $template->assign('customProfile', $customProfile);
2498 // for primary contact
2499 $values['params']['additionalParticipant'] = FALSE;
2500 $template->assign('isPrimary', 1);
2501 $template->assign('amount', $primaryAmount);
2502 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2503 if ($this->payment_instrument_id
) {
2504 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2505 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2507 // carry paylater, since we did not created billing,
2508 // so need to pull email from primary location, CRM-4395
2509 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2515 * Function to check whether payment processor supports
2516 * cancellation of contribution subscription
2518 * @param int $contributionId contribution id
2520 * @param bool $isNotCancelled
2526 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2527 $cacheKeyString = "$contributionId";
2528 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2530 static $supportsCancel = array();
2532 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2533 $supportsCancel[$cacheKeyString] = FALSE;
2534 $isCancelled = FALSE;
2536 if ($isNotCancelled) {
2537 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2540 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2541 if (!empty($paymentObject)) {
2542 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2545 return $supportsCancel[$cacheKeyString];
2549 * Function to check whether subscription is already cancelled
2551 * @param int $contributionId contribution id
2553 * @return string $status contribution status
2557 static function isSubscriptionCancelled($contributionId) {
2559 SELECT cr.contribution_status_id
2560 FROM civicrm_contribution_recur cr
2561 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2562 WHERE con.id = %1 LIMIT 1";
2563 $params = array(1 => array($contributionId, 'Integer'));
2564 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2565 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2566 if ($status == 'Cancelled') {
2573 * Function to create all financial accounts entry
2575 * @param array $params contribution object, line item array and params for trxn
2578 * @param array $financialTrxnValues
2580 * @return null|object
2584 static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2585 $skipRecords = $update = $return = $isRelatedId = FALSE;
2587 $additionalParticipantId = array();
2588 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2590 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2591 $entityId = $params['participant_id'];
2592 $entityTable = 'civicrm_participant';
2593 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2595 elseif (!empty($params['membership_id'])) {
2596 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2597 // are created off one contribution should be handled elsewhere
2598 $entityId = $params['membership_id'];
2599 $entityTable = 'civicrm_membership';
2602 $entityId = $params['contribution']->id
;
2603 $entityTable = 'civicrm_contribution';
2606 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
2607 $isRelatedId = TRUE;
2610 $entityID[] = $entityId;
2611 if (!empty($additionalParticipantId)) {
2612 $entityID +
= $additionalParticipantId;
2614 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2615 if (empty($params['prevContribution'])) {
2622 $statusId = $params['contribution']->contribution_status_id
;
2623 // CRM-13964 partial payment
2624 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2625 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2626 $partialAmtPay = $params['partial_amount_pay'];
2627 $partialAmtTotal = $params['partial_payment_total'];
2629 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2630 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2631 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2632 $params['total_amount'] = $partialAmtPay;
2634 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2635 if (empty($balanceTrxnInfo['trxn_id'])) {
2636 // create new balance transaction record
2637 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2638 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2640 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2641 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2642 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2643 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2644 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2645 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2646 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2647 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2648 $balanceTrxnParams['status_id'] = $statusId;
2649 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2650 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2651 if (!empty($params['payment_processor'])) {
2652 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2654 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2658 // build line item array if its not set in $params
2659 if (empty($params['line_item']) ||
$additionalParticipantId) {
2660 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2663 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2664 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2665 $skipRecords = TRUE;
2666 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2667 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2668 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2669 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2671 elseif (!empty($params['payment_processor'])) {
2672 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2674 elseif (!empty($params['payment_instrument_id'])) {
2675 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2678 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2679 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2680 $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);
2683 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2684 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2685 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2688 //build financial transaction params
2689 $trxnParams = array(
2690 'contribution_id' => $params['contribution']->id
,
2691 'to_financial_account_id' => $params['to_financial_account_id'],
2692 'trxn_date' => date('YmdHis'),
2693 'total_amount' => $totalAmount,
2694 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2695 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2696 'currency' => $params['contribution']->currency
,
2697 'trxn_id' => $params['contribution']->trxn_id
,
2698 'status_id' => $statusId,
2699 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2700 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2703 if (!empty($params['payment_processor'])) {
2704 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2707 if (isset($fromFinancialAccountId)) {
2708 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2711 // consider external values passed for recording transaction entry
2712 if (!empty($financialTrxnValues)) {
2713 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2716 $params['trxnParams'] = $trxnParams;
2718 if (!empty($params['prevContribution'])) {
2719 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2720 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2721 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2722 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2723 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2726 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
2727 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
2728 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))) {
2729 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2730 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2733 //if financial type is changed
2734 if (!empty($params['financial_type_id']) &&
2735 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2736 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2737 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2738 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2739 if ($oldFinancialAccount != $newFinancialAccount) {
2740 $params['total_amount'] = 0;
2741 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2742 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2743 $params['prevContribution']->financial_type_id
, $relationTypeId);
2746 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2747 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2748 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2751 self
::updateFinancialAccounts($params, 'changeFinancialType');
2752 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2753 $params['financial_account_id'] = $newFinancialAccount;
2754 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2755 self
::updateFinancialAccounts($params);
2756 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2760 //Update contribution status
2761 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2762 if (!empty($params['contribution_status_id']) &&
2763 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2764 //Update Financial Records
2765 self
::updateFinancialAccounts($params, 'changedStatus');
2768 // change Payment Instrument for a Completed contribution
2769 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2770 // instrument is null and now new payment instrument is added along with the payment
2771 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2772 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2773 if (array_key_exists('payment_instrument_id', $params)) {
2774 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2775 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2776 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2777 //check if status is changed from Pending to Completed
2778 // do not update payment instrument changes for Pending to Completed
2779 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2780 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2781 // for all other statuses create new financial records
2782 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2783 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2784 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2787 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2788 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2789 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2790 // for any other payment instrument changes create new financial records
2791 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2792 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2793 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2795 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2796 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2797 // another special case when check number is changed, create new financial records
2798 // create financial trxn with negative amount
2799 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2800 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2801 // create financial trxn with positive amount
2802 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2803 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2804 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2808 //if Change contribution amount
2809 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2810 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2811 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2812 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2813 if (isset($totalAmount) &&
2814 $totalAmount != $params['prevContribution']->total_amount
) {
2815 //Update Financial Records
2816 $params['trxnParams']['from_financial_account_id'] = NULL;
2817 self
::updateFinancialAccounts($params, 'changedAmount');
2822 // records finanical trxn and entity financial trxn
2823 // also make it available as return value
2824 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2825 $params['entity_id'] = $financialTxn->id
;
2828 // record line items and finacial items
2829 if (empty($params['skipLineItem'])) {
2830 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2833 // create batch entry if batch_id is passed
2834 if (!empty($params['batch_id'])) {
2835 $entityParams = array(
2836 'batch_id' => $params['batch_id'],
2837 'entity_table' => 'civicrm_financial_trxn',
2838 'entity_id' => $financialTxn->id
,
2840 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2843 // when a fee is charged
2844 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2845 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2848 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2849 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2850 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2851 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2852 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2854 unset($params['line_item']);
2860 * Function to update all financial accounts entry
2862 * @param array $params contribution object, line item array and params for trxn
2864 * @param string $context update scenarios
2866 * @param null $skipTrxn
2871 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2872 $itemAmount = $trxnID = NULL;
2873 //get all the statuses
2874 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2875 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2876 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2877 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2878 && $context == 'changePaymentInstrument') {
2881 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2882 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2884 if ($context == 'changedStatus') {
2885 //get all the statuses
2886 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2888 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2889 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2890 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2891 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2893 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2894 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2895 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2896 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2897 $params['trxnParams']['to_financial_account_id'] = NULL;
2898 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2900 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2901 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2902 $financialTypeID, $relationTypeId);
2904 $itemAmount = $params['trxnParams']['total_amount'];
2906 elseif ($context == 'changePaymentInstrument') {
2907 if ($params['trxnParams']['total_amount'] < 0) {
2908 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2909 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2910 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2911 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2915 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2916 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2919 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2920 $params['entity_id'] = $trxn->id
;
2922 if ($context == 'changedStatus') {
2923 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2924 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2925 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2926 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2927 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2929 $entityParams = array(
2930 'entity_table' => 'civicrm_financial_item',
2931 'financial_trxn_id' => $trxn->id
,
2933 if (empty($params['line_item'])) {
2935 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
2936 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
2937 // & this can be removed
2940 foreach ($params['line_item'] as $fieldId => $fields) {
2941 foreach ($fields as $fieldValueId => $fieldValues) {
2943 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2944 2 => array($fieldValues['id'], 'Integer'),
2946 CRM_Core_DAO
::executeQuery($query, $fparams);
2948 1 => array($fieldValues['id'], 'Integer'),
2950 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2951 while ($financialItem->fetch()) {
2952 $entityParams['entity_id'] = $financialItem->id
;
2953 $entityParams['amount'] = $financialItem->amount
;
2954 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2961 if ($context != 'changePaymentInstrument') {
2962 $itemParams['entity_table'] = 'civicrm_line_item';
2963 $trxnIds['id'] = $params['entity_id'];
2964 foreach ($params['line_item'] as $fieldId => $fields) {
2965 foreach ($fields as $fieldValueId => $fieldValues) {
2966 $prevParams['entity_id'] = $fieldValues['id'];
2967 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2969 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2970 if ($params['contribution']->receive_date
) {
2971 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2974 $financialAccount = $prevfinancialItem->financial_account_id
;
2975 if (!empty($params['financial_account_id'])) {
2976 $financialAccount = $params['financial_account_id'];
2979 $currency = $params['prevContribution']->currency
;
2980 if ($params['contribution']->currency
) {
2981 $currency = $params['contribution']->currency
;
2983 if (!empty($params['is_quick_config'])) {
2984 $amount = $itemAmount;
2986 $amount = $params['total_amount'];
2991 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
2992 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)) {
2995 $amount = $diff * $fieldValues['line_total'];
2998 $itemParams = array(
2999 'transaction_date' => $receiveDate,
3000 'contact_id' => $params['prevContribution']->contact_id
,
3001 'currency' => $currency,
3002 'amount' => $amount,
3003 'description' => $prevfinancialItem->description
,
3004 'status_id' => $prevfinancialItem->status_id
,
3005 'financial_account_id' => $financialAccount,
3006 'entity_table' => 'civicrm_line_item',
3007 'entity_id' => $fieldValues['id']
3009 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3016 * Function to check status validation on update of a contribution
3018 * @param array $values previous form values before submit
3020 * @param array $fields the input form values
3022 * @param array $errors list of errors
3028 static function checkStatusValidation($values, &$fields, &$errors) {
3029 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3030 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3031 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3035 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3036 $checkStatus = array(
3037 'Cancelled' => array('Completed', 'Refunded'),
3038 'Completed' => array('Cancelled', 'Refunded'),
3039 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3040 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3041 'Refunded' => array('Cancelled', 'Completed')
3044 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3045 $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']]));
3050 * Function to delete contribution of contact
3054 * @param integer $contactId contact id
3059 static function deleteContactContribution($contactId) {
3060 $contribution = new CRM_Contribute_DAO_Contribution();
3061 $contribution->contact_id
= $contactId;
3062 $contribution->find();
3063 while ($contribution->fetch()) {
3064 self
::deleteContribution($contribution->id
);
3069 * Get options for a given contribution field.
3070 * @see CRM_Core_DAO::buildOptions
3072 * @param String $fieldName
3073 * @param String $context : @see CRM_Core_DAO::buildOptionsContext
3074 * @param Array $props : whatever is known about this dao object
3076 * @return Array|bool
3078 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3079 $className = __CLASS__
;
3081 switch ($fieldName) {
3082 // This field is not part of this object but the api supports it
3083 case 'payment_processor':
3084 $className = 'CRM_Contribute_BAO_ContributionPage';
3085 // Filter results by contribution page
3086 if (!empty($props['contribution_page_id'])) {
3087 $page = civicrm_api('contribution_page', 'getsingle', array(
3089 'id' => ($props['contribution_page_id'])
3091 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3092 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3095 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3096 case 'honor_type_id':
3097 $className = 'CRM_Contribute_BAO_ContributionSoft';
3098 $fieldName = 'soft_credit_type_id';
3099 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3102 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3106 * Function to validate financial type
3110 * @param integer $financialTypeId Financial Type id
3112 * @param string $relationName
3114 * @return array|bool
3118 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3119 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3120 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3122 if (!$financialAccount) {
3123 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3130 * Function to record additional payment for partial and refund contributions
3132 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3133 * @param array $trxnData : to take user provided input of transaction details.
3134 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3137 * @param $contributionId
3139 * @param string $paymentType
3140 * @param null $participantId
3142 * @return null|object
3144 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3145 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3146 $getInfoOf['id'] = $contributionId;
3147 $defaults = array();
3148 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3150 if ($paymentType == 'owed') {
3151 // build params for recording financial trxn entry
3152 $params['contribution'] = $contributionDAO;
3153 $params = array_merge($defaults, $params);
3154 $params['skipLineItem'] = TRUE;
3155 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3156 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3157 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3160 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3161 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3162 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3164 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3165 if (!empty($trxnId)) {
3166 $trxnId = $trxnId['trxn_id'];
3168 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3169 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3172 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3173 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3174 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3178 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3179 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3180 FROM civicrm_financial_trxn ft
3181 LEFT JOIN civicrm_entity_financial_trxn eft
3182 ON (ft.id = eft.financial_trxn_id)
3183 WHERE eft.entity_table = 'civicrm_contribution'
3184 AND eft.entity_id = {$contributionId}
3185 AND ft.to_financial_account_id != {$toFinancialAccount}
3186 AND ft.status_id = {$statusId}
3188 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3191 if ($contributionDAO->total_amount
== $sumOfPayments) {
3192 // update contribution status and
3193 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3194 $contributionDAO->contribution_status_id
= $statusId;
3195 $contributionDAO->cancel_date
= 'null';
3196 $contributionDAO->cancel_reason
= NULL;
3197 $netAmount = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3198 $contributionDAO->net_amount
= $contributionDAO->net_amount +
$netAmount;
3199 $contributionDAO->save();
3201 //Change status of financial record too
3202 $financialTrxn->status_id
= $statusId;
3203 $financialTrxn->save();
3205 // note : not using the self::add method,
3206 // the reason because it performs 'status change' related code execution for financial records
3207 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3208 // are coded below i.e. just updating financial_item status to 'Paid'
3210 if ($participantId) {
3211 // update participant status
3212 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3213 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3214 foreach ($ids as $val) {
3215 $participantUpdate['id'] = $val;
3216 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3217 CRM_Event_BAO_Participant
::add($participantUpdate);
3221 // update financial item statuses
3222 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3223 $paidStatus = array_search('Paid', $financialItemStatus);
3225 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3226 $sqlFinancialItemUpdate = "
3227 UPDATE civicrm_financial_item fi
3228 LEFT JOIN civicrm_entity_financial_trxn eft
3229 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3230 SET status_id = {$paidStatus}
3231 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3233 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3236 elseif ($paymentType == 'refund') {
3237 // build params for recording financial trxn entry
3238 $params['contribution'] = $contributionDAO;
3239 $params = array_merge($defaults, $params);
3240 $params['skipLineItem'] = TRUE;
3241 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3242 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3244 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3245 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3246 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3248 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3250 // note : not using the self::add method,
3251 // the reason because it performs 'status change' related code execution for financial records
3252 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3253 // are coded below i.e. just updating financial_item status to 'Paid'
3254 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3256 // add financial item entry
3257 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3258 $getLine['entity_id'] = $contributionDAO->id
;
3259 $getLine['entity_table'] = 'civicrm_contribution';
3260 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3261 if (!empty($lineItemId->id
)) {
3262 $addFinancialEntry = array(
3263 'transaction_date' => $financialTrxn->trxn_date
,
3264 'contact_id' => $contributionDAO->contact_id
,
3265 'amount' => $financialTrxn->total_amount
,
3266 'status_id' => array_search('Paid', $financialItemStatus),
3267 'entity_id' => $lineItemId->id
,
3268 'entity_table' => 'civicrm_line_item'
3270 $trxnIds['id'] = $financialTrxn->id
;
3271 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3273 if ($participantId) {
3274 // update participant status
3275 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3276 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3277 foreach ($ids as $val) {
3278 $participantUpdate['id'] = $val;
3279 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3280 CRM_Event_BAO_Participant
::add($participantUpdate);
3285 // activity creation
3286 if (!empty($financialTrxn)) {
3287 if ($participantId) {
3288 $inputParams['id'] = $participantId;
3291 $component = 'event';
3292 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3293 $entityObj = $entityObj[$participantId];
3295 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3297 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3299 return $financialTrxn;
3305 * @param $activityType
3307 * @param $contributionId
3309 * @throws CRM_Core_Exception
3311 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3312 if ($component == 'event') {
3313 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3314 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3315 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3316 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3317 $targetCid = $entityObj->contact_id
;
3318 // source record id would be the contribution id
3319 $srcRecId = $contributionId;
3323 $activityParams = array(
3324 'source_contact_id' => $targetCid,
3325 'source_record_id' => $srcRecId,
3326 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3330 'subject' => $subject,
3331 'activity_date_time' => $date,
3332 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3336 'skipRecentView' => TRUE,
3339 // create activity with target contacts
3340 $session = CRM_Core_Session
::singleton();
3341 $id = $session->get('userID');
3343 $activityParams['source_contact_id'] = $id;
3344 $activityParams['target_contact_id'][] = $targetCid;
3346 CRM_Activity_BAO_Activity
::create($activityParams);
3350 * function to get list of payments displayed by Contribute_Page_PaymentInfo
3354 * @param bool $getTrxnInfo
3355 * @param bool $usingLineTotal
3359 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3360 if ($component == 'event') {
3361 $entity = 'participant';
3362 $entityTable = 'civicrm_participant';
3363 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3365 if (!$contributionId) {
3366 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3367 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3368 $id = $primaryParticipantId;
3370 if (!$contributionId) {
3375 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3376 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3382 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3383 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3386 if (empty($total) ||
$usingLineTotal) {
3387 // for additional participants
3388 if ($entityTable == 'civicrm_participant') {
3389 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3391 foreach ($ids as $val) {
3392 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3396 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3400 $baseTrxnId = $total['trxn_id'];
3401 $total = $total['total_amount'];
3404 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3405 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3407 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3408 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3409 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3411 if ($paymentBalance == 0 && $contributionIsPayLater) {
3412 $paymentBalance = $total;
3415 $info['total'] = $total;
3416 $info['paid'] = $total - $paymentBalance;
3417 $info['balance'] = $paymentBalance;
3419 $info['component'] = $component;
3420 $info['payLater'] = $contributionIsPayLater;
3422 if ($getTrxnInfo && $baseTrxnId) {
3423 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3425 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3426 FROM civicrm_contribution con
3427 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3428 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3429 WHERE con.id = {$contributionId}
3432 // conditioned WHERE clause
3434 // if balance trxn exists don't include details of it in transaction info
3435 $sql .= " AND ft.id != {$baseTrxnId} ";
3437 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3439 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3440 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3441 while($resultDAO->fetch()) {
3442 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3443 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3445 'total_amount' => $resultDAO->total_amount
,
3446 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3447 'payment_instrument' => $paidByLabel,
3448 'receive_date' => $resultDAO->trxn_date
,
3449 'trxn_id' => $resultDAO->trxn_id
,
3450 'status' => $statuses[$resultDAO->status_id
],
3452 if ($paidByName == 'Check') {
3453 $val['check_number'] = $resultDAO->check_number
;
3457 $info['transaction'] = $rows;