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;
72 function __construct() {
73 parent
::__construct();
77 * takes an associative array and creates a contribution object
79 * the function extract all the params it needs to initialize the create a
80 * contribution object. the params array could contain additional unused name/value
83 * @param array $params (reference ) an assoc array of name/value pairs
84 * @param array $ids the array that holds all the db ids
86 * @return object CRM_Contribute_BAO_Contribution object
90 static function add(&$params, $ids = array()) {
94 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
95 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
97 $duplicates = array();
98 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
99 $error = CRM_Core_Error
::singleton();
100 $d = implode(', ', $duplicates);
101 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
104 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
109 // first clean up all the money fields
110 $moneyFields = array(
114 'non_deductible_amount',
117 //if priceset is used, no need to cleanup money
118 if (!empty($params['skipCleanMoney'])) {
119 unset($moneyFields[0]);
122 foreach ($moneyFields as $field) {
123 if (isset($params[$field])) {
124 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
128 // CRM-13420, set payment instrument to default if payment_instrument_id is empty
129 if (!$contributionID && empty($params['payment_instrument_id'])) {
130 $params['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument',
131 FALSE, FALSE, FALSE, 'AND is_default = 1'));
134 if (!empty($params['payment_instrument_id'])) {
135 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
136 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
137 $params['check_number'] = 'null';
141 // contribution status is missing, choose Completed as default status
142 // do this for create mode only
143 if (empty($ids['contribution']) && empty($params['contribution_status_id'])) {
144 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
146 $setPrevContribution = TRUE;
147 // CRM-13964 partial payment
148 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
149 $partialAmtTotal = $params['partial_payment_total'];
150 $partialAmtPay = $params['partial_amount_pay'];
151 $params['total_amount'] = $partialAmtTotal;
152 if ($partialAmtPay < $partialAmtTotal) {
153 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
154 $params['is_pay_later'] = 0;
155 $setPrevContribution = FALSE;
159 if ($contributionID) {
160 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
163 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
165 $contribution = new CRM_Contribute_BAO_Contribution();
166 $contribution->copyValues($params);
168 $contribution->id
= $contributionID;
170 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
171 $config = CRM_Core_Config
::singleton();
172 $contribution->currency
= $config->defaultCurrency
;
175 if ($contributionID && $setPrevContribution) {
176 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
179 $result = $contribution->save();
181 // Add financial_trxn details as part of fix for CRM-4724
182 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
183 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
185 //add Account details
186 $params['contribution'] = $contribution;
187 self
::recordFinancialAccounts($params);
189 // reset the group contact cache for this group
190 CRM_Contact_BAO_GroupContactCache
::remove();
192 if ($contributionID) {
193 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
196 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
203 * Given the list of params in the params array, fetch the object
204 * and store the values in the values array
206 * @param array $params input parameters to find object
207 * @param array $values output values of the object
208 * @param array $ids the array that holds all the db ids
210 * @return CRM_Contribute_BAO_Contribution|null the found object or null
214 static function &getValues($params, &$values, &$ids) {
215 if (empty($params)) {
218 $contribution = new CRM_Contribute_BAO_Contribution();
220 $contribution->copyValues($params);
222 if ($contribution->find(TRUE)) {
223 $ids['contribution'] = $contribution->id
;
225 CRM_Core_DAO
::storeValues($contribution, $values);
227 return $contribution;
233 * takes an associative array and creates a contribution object
235 * @param array $params (reference ) an assoc array of name/value pairs
236 * @param array $ids the array that holds all the db ids
238 * @return object CRM_Contribute_BAO_Contribution object
242 static function &create(&$params, $ids = array()) {
243 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
244 foreach ($dateFields as $df) {
245 if (isset($params[$df])) {
246 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
250 $transaction = new CRM_Core_Transaction();
252 $contribution = self
::add($params, $ids);
254 if (is_a($contribution, 'CRM_Core_Error')) {
255 $transaction->rollback();
256 return $contribution;
259 $params['contribution_id'] = $contribution->id
;
261 if (!empty($params['custom']) &&
262 is_array($params['custom'])
264 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
267 $session = CRM_Core_Session
::singleton();
269 if (!empty($params['note'])) {
271 'entity_table' => 'civicrm_contribution',
272 'note' => $params['note'],
273 'entity_id' => $contribution->id
,
274 'contact_id' => $session->get('userID'),
275 'modified_date' => date('Ymd'),
277 if (!$noteParams['contact_id']) {
278 $noteParams['contact_id'] = $params['contact_id'];
280 CRM_Core_BAO_Note
::add($noteParams);
283 // make entry in batch entity batch table
284 if (!empty($params['batch_id'])) {
285 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
286 $titleFields = array(
292 $retrieveRequired = 0;
293 foreach ($titleFields as $titleField) {
294 if(!isset($contribution->$titleField)){
295 $retrieveRequired = 1;
299 if ($retrieveRequired == 1) {
300 $contribution->find(TRUE);
304 // check if activity record exist for this contribution, if
306 $activity = new CRM_Activity_DAO_Activity();
307 $activity->source_record_id
= $contribution->id
;
308 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
312 if (!$activity->find(TRUE)) {
313 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
316 // CRM-13237 : if activity record found, update it with campaign id of contribution
317 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
320 // Handle soft credit and / or link to personal campaign page
321 list($type, $softIDs) = CRM_Contribute_BAO_ContributionSoft
::getSoftCreditType($contribution->id
);
322 if ($pcp = CRM_Utils_Array
::value('pcp', $params)) {
323 if (!empty($type) && $type == 'soft') {
324 $deleteParams = array('contribution_id' => $contribution->id
);
325 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
327 $softParams = array();
328 $softParams['contribution_id'] = $contribution->id
;
329 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
330 $softParams['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP',
331 $pcp['pcp_made_through_id'], 'contact_id'
333 $softParams['currency'] = $contribution->currency
;
334 $softParams['amount'] = $contribution->total_amount
;
335 $softParams['pcp_display_in_roll'] = CRM_Utils_Array
::value('pcp_display_in_roll', $pcp);
336 $softParams['pcp_roll_nickname'] = CRM_Utils_Array
::value('pcp_roll_nickname', $pcp);
337 $softParams['pcp_personal_note'] = CRM_Utils_Array
::value('pcp_personal_note', $pcp);
338 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup
::getValue('soft_credit_type', 'pcp', 'name');
339 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
341 elseif (isset($params['soft_credit'])) {
342 $softParams = $params['soft_credit'];
344 if (!empty($softIDs)) {
345 foreach ( $softIDs as $softID) {
346 if (!in_array($softID, $params['soft_credit_ids'])) {
347 $deleteParams = array('id' => $softID);
348 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
353 foreach ($softParams as $softParam) {
354 $softParam['contribution_id'] = $contribution->id
;
355 $softParam['currency'] = $contribution->currency
;
356 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
357 if (empty($softParam['amount'])) {
358 $softParam['amount'] = $contribution->total_amount
;
360 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
364 $transaction->commit();
366 // do not add to recent items for import, CRM-4399
367 if (empty($params['skipRecentView'])) {
368 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
369 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
371 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
372 $titleFields = array(
378 $retrieveRequired = 0;
379 foreach ($titleFields as $titleField) {
380 if(!isset($contribution->$titleField)){
381 $retrieveRequired = 1;
385 if($retrieveRequired == 1){
386 $contribution->find(TRUE);
388 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
389 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
391 $recentOther = array();
392 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
393 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
394 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
398 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
399 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
400 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
404 // add the recently created Contribution
405 CRM_Utils_Recent
::add($title,
409 $contribution->contact_id
,
415 return $contribution;
419 * Get the values for pseudoconstants for name->value and reverse.
421 * @param array $defaults (reference) the default values, some of which need to be resolved.
422 * @param boolean $reverse true if we want to resolve the values in the reverse direction (value -> name)
428 static function resolveDefaults(&$defaults, $reverse = FALSE) {
429 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
430 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
431 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
432 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
436 * This function is used to convert associative array names to values
439 * This function is used by both the web form layer and the api. Note that
440 * the api needs the name => value conversion, also the view layer typically
441 * requires value => name conversion
443 static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
444 $id = $property . '_id';
446 $src = $reverse ?
$property : $id;
447 $dst = $reverse ?
$id : $property;
449 if (!array_key_exists($src, $defaults)) {
453 $look = $reverse ?
array_flip($lookup) : $lookup;
455 if (is_array($look)) {
456 if (!array_key_exists($defaults[$src], $look)) {
460 $defaults[$dst] = $look[$defaults[$src]];
465 * Takes a bunch of params that are needed to match certain criteria and
466 * retrieves the relevant objects. We'll tweak this function to be more
467 * full featured over a period of time. This is the inverse function of
468 * create. It also stores all the retrieved values in the default array
470 * @param array $params (reference ) an assoc array of name/value pairs
471 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
472 * in a hierarchical manner
473 * @param array $ids (reference) the array that holds all the db ids
475 * @return object CRM_Contribute_BAO_Contribution object
479 static function retrieve(&$params, &$defaults, &$ids) {
480 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
481 return $contribution;
485 * combine all the importable fields from the lower levels object
487 * The ordering is important, since currently we do not have a weight
488 * scheme. Adding weight is super important and should be done in the
489 * next week or so, before this can be called complete.
491 * @return array array of importable Fields
495 static function &importableFields($contactType = 'Individual', $status = TRUE) {
496 if (!self
::$_importableFields) {
497 if (!self
::$_importableFields) {
498 self
::$_importableFields = array();
502 $fields = array('' => array('title' => ts('- do not import -')));
505 $fields = array('' => array('title' => ts('- Contribution Fields -')));
508 $note = CRM_Core_DAO_Note
::import();
509 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
510 unset($tmpFields['option_value']);
511 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
512 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
514 // Using new Dedupe rule.
516 'contact_type' => $contactType,
517 'used' => 'Unsupervised',
519 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
520 $tmpContactField = array();
521 if (is_array($fieldsArray)) {
522 foreach ($fieldsArray as $value) {
523 //skip if there is no dupe rule
524 if ($value == 'none') {
527 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
532 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
533 $tmpContactField[trim($value)] = $contactFields[trim($value)];
535 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
538 $title = $tmpContactField[trim($value)]['title'];
540 $tmpContactField[trim($value)]['title'] = $title;
544 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
545 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
546 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
547 $fields = array_merge($fields, $tmpContactField);
548 $fields = array_merge($fields, $tmpFields);
549 $fields = array_merge($fields, $note);
550 $fields = array_merge($fields, $optionFields);
551 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
552 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
553 self
::$_importableFields = $fields;
555 return self
::$_importableFields;
558 static function &exportableFields() {
559 if (!self
::$_exportableFields) {
560 if (!self
::$_exportableFields) {
561 self
::$_exportableFields = array();
564 $impFields = CRM_Contribute_DAO_Contribution
::export();
565 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
566 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
567 $typeField = CRM_Financial_DAO_FinancialType
::export();
568 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
569 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
570 $contributionStatus = array(
571 'contribution_status' => array(
572 'title' => ts('Contribution Status'),
573 'name' => 'contribution_status',
574 'data_type' => CRM_Utils_Type
::T_STRING
577 $contributionNote = array(
578 'contribution_note' =>
580 'title' => ts('Contribution Note'),
581 'name' => 'contribution_note',
582 'data_type' => CRM_Utils_Type
::T_TEXT
586 $contributionRecurId = array(
587 'contribution_recur_id' =>
589 'title' => ts('Recurring Contributions ID'),
590 'name' => 'contribution_recur_id',
591 'where' => 'civicrm_contribution.contribution_recur_id',
592 'data_type' => CRM_Utils_Type
::T_INT
595 $extraFields = array(
596 'contribution_batch' => array(
597 'title' => ts('Batch Name')
601 $softCreditFields = array(
602 'contribution_soft_credit_name' => array(
603 'name' => 'contribution_soft_credit_name',
604 'title' => 'Soft Credit For',
605 'where' => 'civicrm_contact_d.display_name',
606 'data_type' => CRM_Utils_Type
::T_STRING
608 'contribution_soft_credit_amount' => array(
609 'name' => 'contribution_soft_credit_amount',
610 'title' => 'Soft Credit Amount',
611 'where' => 'civicrm_contribution_soft.amount',
612 'data_type' => CRM_Utils_Type
::T_MONEY
614 'contribution_soft_credit_type' => array(
615 'name' => 'contribution_soft_credit_type',
616 'title' => 'Soft Credit Type',
617 'where' => 'contribution_softcredit_type.label',
618 'data_type' => CRM_Utils_Type
::T_STRING
620 'contribution_soft_credit_contribution_id' => array(
621 'name' => 'contribution_soft_credit_contribution_id',
622 'title' => 'Soft Credit For Contribution ID',
623 'where' => 'civicrm_contribution_soft.contribution_id',
624 'data_type' => CRM_Utils_Type
::T_INT
628 $fields = array_merge($impFields, $typeField, $contributionStatus, $optionField, $expFieldProduct,
629 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
630 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution')
633 self
::$_exportableFields = $fields;
636 return self
::$_exportableFields;
639 static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
643 $where[] = 'contribution_status_id = 1';
647 $where[] = 'contribution_status_id = 3';
652 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
655 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
658 $whereCond = implode(' AND ', $where);
661 SELECT sum( total_amount ) as total_amount,
662 count( civicrm_contribution.id ) as total_count,
664 FROM civicrm_contribution
665 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
667 AND ( is_test = 0 OR is_test IS NULL )
668 AND contact.is_deleted = 0
672 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
675 while ($dao->fetch()) {
676 $count +
= $dao->total_count
;
677 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
680 return array('amount' => implode(', ', $amount),
688 * Delete the indirect records associated with this contribution first
690 * @return $results no of deleted Contribution on success, false otherwise
694 static function deleteContribution($id) {
695 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
697 $transaction = new CRM_Core_Transaction();
700 //delete activity record
702 'source_record_id' => $id,
703 // activity type id for contribution
704 'activity_type_id' => 6,
707 CRM_Activity_BAO_Activity
::deleteActivity($params);
709 //delete billing address if exists for this contribution.
710 self
::deleteAddress($id);
712 //update pledge and pledge payment, CRM-3961
713 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
715 // remove entry from civicrm_price_set_entity, CRM-5095
716 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
717 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
719 // cleanup line items.
720 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
722 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
723 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
725 if ($participantId) {
726 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
729 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
733 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
734 $noteId = key($note);
736 CRM_Core_BAO_Note
::del($noteId, FALSE);
739 $dao = new CRM_Contribute_DAO_Contribution();
742 $results = $dao->delete();
744 $transaction->commit();
746 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
748 // delete the recently created Contribution
749 $contributionRecent = array(
751 'type' => 'Contribution',
753 CRM_Utils_Recent
::del($contributionRecent);
759 * Check if there is a contribution with the same trxn_id or invoice_id
761 * @param array $params (reference ) an assoc array of name/value pairs
762 * @param array $duplicates (reference ) store ids of duplicate contribs
764 * @return boolean true if duplicate, false otherwise
768 static function checkDuplicate($input, &$duplicates, $id = NULL) {
770 $id = CRM_Utils_Array
::value('id', $input);
772 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
773 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
779 $clause[] = "trxn_id = %1";
780 $input[1] = array($trxn_id, 'String');
784 $clause[] = "invoice_id = %2";
785 $input[2] = array($invoice_id, 'String');
788 if (empty($clause)) {
792 $clause = implode(' OR ', $clause);
794 $clause = "( $clause ) AND id != %3";
795 $input[3] = array($id, 'Integer');
798 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
799 $dao = CRM_Core_DAO
::executeQuery($query, $input);
801 while ($dao->fetch()) {
802 $duplicates[] = $dao->id
;
809 * takes an associative array and creates a contribution_product object
811 * the function extract all the params it needs to initialize the create a
812 * contribution_product object. the params array could contain additional unused name/value
815 * @param array $params (reference ) an assoc array of name/value pairs
817 * @return object CRM_Contribute_BAO_ContributionProduct object
821 static function addPremium(&$params) {
822 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
823 $contributionProduct->copyValues($params);
824 return $contributionProduct->save();
828 * Function to get list of contribution fields for profile
829 * For now we only allow custom contribution fields to be in
832 * @param boolean $addExtraFields true if special fields needs to be added
834 * @return return the list of contribution fields
838 static function getContributionFields($addExtraFields = TRUE) {
839 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
840 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
842 if ($addExtraFields) {
843 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
846 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
848 foreach ($contributionFields as $key => $var) {
849 if ($key == 'contribution_contact_id') {
852 elseif ($key == 'contribution_campaign_id') {
853 $var['title'] = ts('Campaign');
855 $fields[$key] = $var;
858 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
863 * Function to add extra fields specific to contribtion
867 static function getSpecialContributionFields() {
868 $extraFields = array(
869 'honor_contact_name' => array(
870 'name' => 'honor_contact_name',
871 'title' => 'Honor Contact Name',
872 'headerPattern' => '/^honor_contact_name$/i',
873 'where' => 'civicrm_contact_c.display_name',
875 'honor_contact_email' => array(
876 'name' => 'honor_contact_email',
877 'title' => 'Honor Contact Email',
878 'headerPattern' => '/^honor_contact_email$/i',
879 'where' => 'honor_email.email',
881 'honor_contact_id' => array(
882 'name' => 'honor_contact_id',
883 'title' => 'Honor Contact ID',
884 'headerPattern' => '/^honor_contact_id$/i',
885 'where' => 'civicrm_contribution.honor_contact_id',
887 'honor_type_label' => array(
888 'name' => 'honor_type_label',
889 'title' => 'Honor Type Label',
890 'headerPattern' => '/^honor_type_label$/i',
891 'where' => 'honor_type.label',
893 'contribution_soft_credit_name' => array(
894 'name' => 'contribution_soft_credit_name',
895 'title' => 'Soft Credit Name',
896 'headerPattern' => '/^soft_credit_name$/i',
897 'where' => 'civicrm_contact_d.display_name',
899 'contribution_soft_credit_email' => array(
900 'name' => 'contribution_soft_credit_email',
901 'title' => 'Soft Credit Email',
902 'headerPattern' => '/^soft_credit_email$/i',
903 'where' => 'soft_email.email',
905 'contribution_soft_credit_phone' => array(
906 'name' => 'contribution_soft_credit_phone',
907 'title' => 'Soft Credit Phone',
908 'headerPattern' => '/^soft_credit_phone$/i',
909 'where' => 'soft_phone.phone',
911 'contribution_soft_credit_contact_id' => array(
912 'name' => 'contribution_soft_credit_contact_id',
913 'title' => 'Soft Credit Contact ID',
914 'headerPattern' => '/^soft_credit_contact_id$/i',
915 'where' => 'civicrm_contribution_soft.contact_id',
922 static function getCurrentandGoalAmount($pageID) {
924 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
925 FROM civicrm_contribution_page p,
926 civicrm_contribution c
927 WHERE p.id = c.contribution_page_id
929 AND c.cancel_date is null
933 $config = CRM_Core_Config
::singleton();
934 $params = array(1 => array($pageID, 'Integer'));
935 $dao = CRM_Core_DAO
::executeQuery($query, $params);
938 return array($dao->goal
, $dao->total
);
941 return array(NULL, NULL);
946 * Function to get list of contribution In Honor of contact Ids
948 * @param int $honorId In Honor of Contact ID
950 * @return return the list of contribution fields
955 static function getHonorContacts($honorId) {
957 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
958 $honorDAO->contact_id
= $honorId;
961 $type = CRM_Contribute_PseudoConstant
::financialType();
963 while ($honorDAO->fetch()) {
964 $contributionDAO = new CRM_Contribute_DAO_Contribution();
965 $contributionDAO->id
= $honorDAO->contribution_id
;
967 if ($contributionDAO->find(TRUE)) {
968 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_OptionGroup
::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id
, 'value');
969 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
970 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
971 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
972 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
973 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
974 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
975 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
976 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
984 * function to get the sort name of a contact for a particular contribution
986 * @param int $id id of the contribution
988 * @return null|string sort name of the contact if found
992 static function sortName($id) {
993 $id = CRM_Utils_Type
::escape($id, 'Integer');
996 SELECT civicrm_contact.sort_name
997 FROM civicrm_contribution, civicrm_contact
998 WHERE civicrm_contribution.contact_id = civicrm_contact.id
999 AND civicrm_contribution.id = {$id}
1001 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1004 static function annual($contactID) {
1005 if (is_array($contactID)) {
1006 $contactIDs = implode(',', $contactID);
1009 $contactIDs = $contactID;
1012 $config = CRM_Core_Config
::singleton();
1013 $startDate = $endDate = NULL;
1015 $currentMonth = date('m');
1016 $currentDay = date('d');
1017 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1018 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1019 (int ) $config->fiscalYearStart
['d'] > $currentDay
1022 $year = date('Y') - 1;
1027 $nextYear = $year +
1;
1029 if ($config->fiscalYearStart
) {
1030 if ($config->fiscalYearStart
['M'] < 10) {
1031 $config->fiscalYearStart
['M'] = '0' . $config->fiscalYearStart
['M'];
1033 if ($config->fiscalYearStart
['d'] < 10) {
1034 $config->fiscalYearStart
['d'] = '0' . $config->fiscalYearStart
['d'];
1036 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1041 $startDate = "$year$monthDay";
1042 $endDate = "$nextYear$monthDay";
1045 SELECT count(*) as count,
1046 sum(total_amount) as amount,
1047 avg(total_amount) as average,
1049 FROM civicrm_contribution b
1050 WHERE b.contact_id IN ( $contactIDs )
1051 AND b.contribution_status_id = 1
1053 AND b.receive_date >= $startDate
1054 AND b.receive_date < $endDate
1057 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1059 $amount = $average = array();
1060 while ($dao->fetch()) {
1061 if ($dao->count
> 0 && $dao->amount
> 0) {
1062 $count +
= $dao->count
;
1063 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1064 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1070 implode(', ', $amount),
1071 implode(', ', $average),
1074 return array(0, 0, 0);
1078 * Check if there is a contribution with the params passed in.
1079 * Used for trxn_id,invoice_id and contribution_id
1081 * @param array $params an assoc array of name/value pairs
1083 * @return array contribution id if success else NULL
1087 static function checkDuplicateIds($params) {
1088 $dao = new CRM_Contribute_DAO_Contribution();
1092 foreach ($params as $k => $v) {
1094 $clause[] = "$k = '$v'";
1097 $clause = implode(' AND ', $clause);
1098 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1099 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1101 while ($dao->fetch()) {
1109 * Function to get the contribution details for component export
1111 * @param int $exportMode export mode
1112 * @param string $componentIds component ids
1114 * @return array associated array
1119 static function getContributionDetails($exportMode, $componentIds) {
1120 $paymentDetails = array();
1121 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1123 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1124 $componentSelect = " civicrm_participant_payment.participant_id id";
1125 $additionalClause = "
1126 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1127 AND civicrm_participant_payment.participant_id {$componentClause} )
1130 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1131 $componentSelect = " civicrm_membership_payment.membership_id id";
1132 $additionalClause = "
1133 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1134 AND civicrm_membership_payment.membership_id {$componentClause} )
1137 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1138 $componentSelect = " civicrm_pledge_payment.id id";
1139 $additionalClause = "
1140 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1141 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1145 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1146 trxn_id, {$componentSelect}
1147 FROM civicrm_contribution
1148 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1149 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1150 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1151 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1152 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1153 AND option_group_contribution_status.id = contribution_status.option_group_id )
1157 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1159 while ($dao->fetch()) {
1160 $paymentDetails[$dao->id
] = array(
1161 'total_amount' => $dao->total_amount
,
1162 'contribution_status' => $dao->status
,
1163 'receive_date' => $dao->receive_date
,
1164 'pay_instru' => $dao->payment_instrument
,
1165 'trxn_id' => $dao->trxn_id
,
1169 return $paymentDetails;
1173 * Function to create address associated with contribution record.
1174 * @param array $params an associated array
1175 * @param int $billingID $billingLocationTypeID
1177 * @return address id
1180 static function createAddress(&$params, $billingLocationTypeID) {
1181 $billingFields = array(
1184 'state_province_id',
1189 //build address array
1190 $addressParams = array();
1191 $addressParams['location_type_id'] = $billingLocationTypeID;
1192 $addressParams['is_billing'] = 1;
1194 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
1195 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
1196 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
1197 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
1199 foreach ($billingFields as $value) {
1200 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
1203 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1205 return $address->id
;
1209 * Delete billing address record related contribution
1211 * @param int $contact_id contact id
1212 * @param int $contribution_id contributionId
1216 static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1218 $contactJoin = NULL;
1220 if ($contributionId) {
1221 $clauses[] = "cc.id = {$contributionId}";
1225 $clauses[] = "cco.id = {$contactId}";
1226 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1229 if (empty($clauses)) {
1230 CRM_Core_Error
::fatal();
1233 $condition = implode(' OR ', $clauses);
1237 FROM civicrm_address ca
1238 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1242 $dao = CRM_Core_DAO
::executeQuery($query);
1244 while ($dao->fetch()) {
1245 $params = array('id' => $dao->id
);
1246 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1251 * This function check online pending contribution associated w/
1252 * Online Event Registration or Online Membership signup.
1254 * @param int $componentId participant/membership id.
1255 * @param string $componentName Event/Membership.
1257 * @return $contributionId pending contribution id.
1260 static function checkOnlinePendingContribution($componentId, $componentName) {
1261 $contributionId = NULL;
1262 if (!$componentId ||
1263 !in_array($componentName, array('Event', 'Membership'))
1265 return $contributionId;
1268 if ($componentName == 'Event') {
1269 $idName = 'participant_id';
1270 $componentTable = 'civicrm_participant';
1271 $paymentTable = 'civicrm_participant_payment';
1272 $source = ts('Online Event Registration');
1275 if ($componentName == 'Membership') {
1276 $idName = 'membership_id';
1277 $componentTable = 'civicrm_membership';
1278 $paymentTable = 'civicrm_membership_payment';
1279 $source = ts('Online Contribution');
1282 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1285 SELECT component.id as {$idName},
1286 componentPayment.contribution_id as contribution_id,
1287 contribution.source source,
1288 contribution.contribution_status_id as contribution_status_id,
1289 contribution.is_pay_later as is_pay_later
1290 FROM $componentTable component
1291 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1292 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1293 WHERE component.id = {$componentId}";
1295 $dao = CRM_Core_DAO
::executeQuery($query);
1297 while ($dao->fetch()) {
1298 if ($dao->contribution_id
&&
1299 $dao->is_pay_later
&&
1300 $dao->contribution_status_id
== $pendingStatusId &&
1301 strpos($dao->source
, $source) !== FALSE
1303 $contributionId = $dao->contribution_id
;
1308 return $contributionId;
1312 * This function update contribution as well as related objects.
1314 static function transitionComponents($params, $processContributionObject = FALSE) {
1315 // get minimum required values.
1316 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1317 $componentId = CRM_Utils_Array
::value('component_id', $params);
1318 $componentName = CRM_Utils_Array
::value('componentName', $params);
1319 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1320 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1322 // if we already processed contribution object pass previous status id.
1323 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1325 $updateResult = array();
1327 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1329 // we process only ( Completed, Cancelled, or Failed ) contributions.
1330 if (!$contributionId ||
1331 !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses),
1332 array_search('Cancelled', $contributionStatuses),
1333 array_search('Failed', $contributionStatuses),
1336 return $updateResult;
1339 if (!$componentName ||
!$componentId) {
1340 // get the related component details.
1341 $componentDetails = self
::getComponentDetails($contributionId);
1344 $componentDetails['contact_id'] = $contactId;
1345 $componentDetails['component'] = $componentName;
1347 if ($componentName == 'event') {
1348 $componentDetails['participant'] = $componentId;
1351 $componentDetails['membership'] = $componentId;
1355 if (!empty($componentDetails['contact_id'])) {
1356 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1362 // do check for required ids.
1363 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1364 return $updateResult;
1367 //now we are ready w/ required ids, start processing.
1369 $baseIPN = new CRM_Core_Payment_BaseIPN();
1371 $input = $ids = $objects = array();
1373 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1374 $ids['contribution'] = $contributionId;
1375 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1376 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1377 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1378 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1379 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1380 $ids['contributionRecur'] = NULL;
1381 $ids['contributionPage'] = NULL;
1383 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1384 CRM_Core_Error
::fatal();
1387 $memberships = &$objects['membership'];
1388 $participant = &$objects['participant'];
1389 $pledgePayment = &$objects['pledge_payment'];
1390 $contribution = &$objects['contribution'];
1392 if ($pledgePayment) {
1393 $pledgePaymentIDs = array();
1394 foreach ($pledgePayment as $key => $object) {
1395 $pledgePaymentIDs[] = $object->id
;
1397 $pledgeID = $pledgePayment[0]->pledge_id
;
1400 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1403 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1404 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1409 // we might want to process contribution object.
1410 $processContribution = FALSE;
1411 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1412 if (is_array($memberships)) {
1413 foreach ($memberships as $membership) {
1415 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1416 $membership->save();
1418 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1419 if ($processContributionObject) {
1420 $processContribution = TRUE;
1427 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1428 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1430 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1431 if ($processContributionObject) {
1432 $processContribution = TRUE;
1436 if ($pledgePayment) {
1437 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1439 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1440 if ($processContributionObject) {
1441 $processContribution = TRUE;
1445 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1446 if (is_array($memberships)) {
1447 foreach ($memberships as $membership) {
1449 $membership->status_id
= array_search('Expired', $membershipStatuses);
1450 $membership->save();
1452 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1453 if ($processContributionObject) {
1454 $processContribution = TRUE;
1460 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1461 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1463 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1464 if ($processContributionObject) {
1465 $processContribution = TRUE;
1469 if ($pledgePayment) {
1470 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1472 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1473 if ($processContributionObject) {
1474 $processContribution = TRUE;
1478 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1480 // only pending contribution related object processed.
1481 if ($previousContriStatusId &&
1482 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1484 // this is case when we already processed contribution object.
1485 return $updateResult;
1487 elseif (!$previousContriStatusId &&
1488 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1490 // this is case when we are going to process contribution object later.
1491 return $updateResult;
1494 if (is_array($memberships)) {
1495 foreach ($memberships as $membership) {
1500 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1501 $membership->membership_type_id
,
1502 $membership->is_test
, $membership->id
1505 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1506 // this picks up membership type changes during renewals
1508 SELECT membership_type_id
1509 FROM civicrm_membership_log
1510 WHERE membership_id=$membership->id
1513 $dao = new CRM_Core_DAO
;
1515 if ($dao->fetch()) {
1516 if (!empty($dao->membership_type_id
)) {
1517 $membership->membership_type_id
= $dao->membership_type_id
;
1518 $membership->save();
1521 // else fall back to using current membership type
1524 // Figure out number of terms
1526 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1527 foreach ($lineitems as $lineitem) {
1528 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1529 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1531 // in case membership_num_terms comes through as null or zero
1532 $numterms = $numterms >= 1 ?
$numterms : 1;
1537 if ($currentMembership) {
1538 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1539 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1540 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1543 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, NULL, NULL, NULL, $numterms);
1546 //get the status for membership.
1547 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1549 $dates['join_date'],
1554 $formattedParams = array(
1555 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1556 array_search('Current', $membershipStatuses)
1558 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1559 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1560 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1563 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1565 $membership->copyValues($formattedParams);
1566 $membership->save();
1568 //updating the membership log
1569 $membershipLog = array();
1570 $membershipLog = $formattedParams;
1571 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1572 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1574 $membershipLog['start_date'] = $logStartDate;
1575 $membershipLog['membership_id'] = $membership->id
;
1576 $membershipLog['modified_id'] = $membership->contact_id
;
1577 $membershipLog['modified_date'] = date('Ymd');
1578 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1580 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1582 //update related Memberships.
1583 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1585 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1588 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1589 if ($processContributionObject) {
1590 $processContribution = TRUE;
1593 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1599 $updatedStatusId = array_search('Registered', $participantStatuses);
1600 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1602 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1603 if ($processContributionObject) {
1604 $processContribution = TRUE;
1608 if ($pledgePayment) {
1609 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1611 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1612 if ($processContributionObject) {
1613 $processContribution = TRUE;
1618 // process contribution object.
1619 if ($processContribution) {
1620 $contributionParams = array();
1622 'contact_id', 'total_amount', 'receive_date', 'is_test', 'campaign_id',
1623 'payment_instrument_id', 'trxn_id', 'invoice_id', 'financial_type_id',
1624 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number',
1626 foreach ($fields as $field) {
1627 if (empty($params[$field])) {
1630 $contributionParams[$field] = $params[$field];
1633 $ids = array('contribution' => $contributionId);
1634 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1637 return $updateResult;
1641 * This function returns all contribution related object ids.
1643 public static function getComponentDetails($contributionId) {
1644 $componentDetails = $pledgePayment = array();
1645 if (!$contributionId) {
1646 return $componentDetails;
1650 SELECT c.id as contribution_id,
1651 c.contact_id as contact_id,
1652 mp.membership_id as membership_id,
1653 m.membership_type_id as membership_type_id,
1654 pp.participant_id as participant_id,
1655 p.event_id as event_id,
1656 pgp.id as pledge_payment_id
1657 FROM civicrm_contribution c
1658 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1659 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1660 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1661 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1662 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1663 WHERE c.id = $contributionId";
1665 $dao = CRM_Core_DAO
::executeQuery($query);
1666 $componentDetails = array();
1668 while ($dao->fetch()) {
1669 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1670 $componentDetails['contact_id'] = $dao->contact_id
;
1671 if ($dao->event_id
) {
1672 $componentDetails['event'] = $dao->event_id
;
1674 if ($dao->participant_id
) {
1675 $componentDetails['participant'] = $dao->participant_id
;
1677 if ($dao->membership_id
) {
1678 if (!isset($componentDetails['membership'])) {
1679 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1681 $componentDetails['membership'][] = $dao->membership_id
;
1682 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1684 if ($dao->pledge_payment_id
) {
1685 $pledgePayment[] = $dao->pledge_payment_id
;
1689 if ($pledgePayment) {
1690 $componentDetails['pledge_payment'] = $pledgePayment;
1693 return $componentDetails;
1696 static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1701 $contactContributionsSQL = "
1702 SELECT contribution.id AS id
1703 FROM civicrm_contribution contribution
1704 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1706 $contactSoftCreditContributionsSQL = "
1707 SELECT contribution.id
1708 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1709 ON ( contribution.id = softContribution.contribution_id )
1710 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1711 $query = "SELECT count( x.id ) count FROM ( ";
1712 $query .= $contactContributionsSQL;
1714 if ($includeSoftCredit) {
1715 $query .= " UNION ";
1716 $query .= $contactSoftCreditContributionsSQL;
1721 return CRM_Core_DAO
::singleValueQuery($query);
1725 * Function to get individual id for onbehalf contribution
1727 * @param int $contributionId contribution id
1728 * @param int $contributorId contributor id
1730 * @return array $ids containing organization id and individual id
1733 static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1737 if (!$contributionId) {
1741 // fetch contributor id if null
1742 if (!$contributorId) {
1743 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1744 $contributionId, 'contact_id'
1748 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
1749 $activityTypeId = array_search('Contribution', $activityTypeIds);
1751 if ($activityTypeId && $contributorId) {
1753 SELECT civicrm_activity_contact.contact_id
1754 FROM civicrm_activity_contact
1755 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1756 WHERE civicrm_activity.activity_type_id = %1
1757 AND civicrm_activity.source_record_id = %2
1758 AND civicrm_activity_contact.record_type_id = %3
1761 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1762 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
1765 1 => array($activityTypeId, 'Integer'),
1766 2 => array($contributionId, 'Integer'),
1767 3 => array($sourceID, 'Integer'),
1770 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
1772 // for on behalf contribution source is individual and contributor is organization
1773 if ($sourceContactId && $sourceContactId != $contributorId) {
1774 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
1775 // get rel type id for employee of relation
1776 foreach ($relationshipTypeIds as $id => $typeVals) {
1777 if ($typeVals['name_a_b'] == 'Employee of') {
1778 $relationshipTypeId = $id;
1783 $rel = new CRM_Contact_DAO_Relationship();
1784 $rel->relationship_type_id
= $relationshipTypeId;
1785 $rel->contact_id_a
= $sourceContactId;
1786 $rel->contact_id_b
= $contributorId;
1787 if ($rel->find(TRUE)) {
1788 $ids['individual_id'] = $rel->contact_id_a
;
1789 $ids['organization_id'] = $rel->contact_id_b
;
1801 static function getContributionDates() {
1802 $config = CRM_Core_Config
::singleton();
1803 $currentMonth = date('m');
1804 $currentDay = date('d');
1805 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1806 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1807 (int ) $config->fiscalYearStart
['d'] > $currentDay
1810 $year = date('Y') - 1;
1815 $year = array('Y' => $year);
1816 $yearDate = $config->fiscalYearStart
;
1817 $yearDate = array_merge($year, $yearDate);
1818 $yearDate = CRM_Utils_Date
::format($yearDate);
1820 $monthDate = date('Ym') . '01';
1826 'yearDate' => $yearDate,
1827 'monthDate' => $monthDate,
1832 * Load objects relations to contribution object
1833 * Objects are stored in the $_relatedObjects property
1834 * In the first instance we are just moving functionality from BASEIpn -
1835 * see http://issues.civicrm.org/jira/browse/CRM-9996
1837 * @param array $input Input as delivered from Payment Processor
1838 * @param array $ids Ids as Loaded by Payment Processor
1839 * @param boolean $required Is Payment processor / contribution page required
1840 * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
1841 * Note that the unit test for the BaseIPN class tests this function
1843 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
1845 $ids = array_merge($this->getComponentDetails($this->id
),$ids);
1846 if(empty($ids['contact']) && isset($this->contact_id
)){
1847 $ids['contact'] = $this->contact_id
;
1850 if (empty($this->_component
)) {
1851 if (! empty($ids['event'])) {
1852 $this->_component
= 'event';
1855 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
1858 $paymentProcessorID = CRM_Utils_Array
::value('paymentProcessor', $ids);
1859 $contributionType = new CRM_Financial_BAO_FinancialType();
1860 $contributionType->id
= $this->financial_type_id
;
1861 if (!$contributionType->find(TRUE)) {
1862 throw new Exception("Could not find financial type record: " . $this->financial_type_id
);
1864 if (!empty($ids['contact'])) {
1865 $this->_relatedObjects
['contact'] = new CRM_Contact_BAO_Contact();
1866 $this->_relatedObjects
['contact']->id
= $ids['contact'];
1867 $this->_relatedObjects
['contact']->find(TRUE);
1869 $this->_relatedObjects
['contributionType'] = $contributionType;
1871 if ($this->_component
== 'contribute') {
1872 // retrieve the other optional objects first so
1873 // stuff down the line can use this info and do things
1875 //in any case get the memberships associated with the contribution
1876 //because we now support multiple memberships w/ price set
1877 // see if there are any other memberships to be considered for same contribution.
1879 SELECT membership_id
1880 FROM civicrm_membership_payment
1881 WHERE contribution_id = %1 ";
1882 $params = array(1 => array($this->id
, 'Integer'));
1884 $dao = CRM_Core_DAO
::executeQuery($query, $params );
1885 while ($dao->fetch()) {
1886 if ($dao->membership_id
) {
1887 if (!is_array($ids['membership'])) {
1888 $ids['membership'] = array();
1890 $ids['membership'][] = $dao->membership_id
;
1894 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
1895 foreach ($ids['membership'] as $id) {
1897 $membership = new CRM_Member_BAO_Membership();
1898 $membership->id
= $id;
1899 if (!$membership->find(TRUE)) {
1900 throw new Exception("Could not find membership record: $id");
1902 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
1903 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
1904 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
1905 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
1906 $membership->free();
1911 if (!empty($ids['pledge_payment'])) {
1913 foreach ($ids['pledge_payment'] as $key => $paymentID) {
1914 if (empty($paymentID)) {
1917 $payment = new CRM_Pledge_BAO_PledgePayment();
1918 $payment->id
= $paymentID;
1919 if (!$payment->find(TRUE)) {
1920 throw new Exception("Could not find pledge payment record: " . $paymentID);
1922 $this->_relatedObjects
['pledge_payment'][] = $payment;
1926 if (!empty($ids['contributionRecur'])) {
1927 $recur = new CRM_Contribute_BAO_ContributionRecur();
1928 $recur->id
= $ids['contributionRecur'];
1929 if (!$recur->find(TRUE)) {
1930 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
1932 $this->_relatedObjects
['contributionRecur'] = &$recur;
1933 //get payment processor id from recur object.
1934 $paymentProcessorID = $recur->payment_processor_id
;
1936 //for normal contribution get the payment processor id.
1937 if (!$paymentProcessorID) {
1938 if ($this->contribution_page_id
) {
1939 // get the payment processor id from contribution page
1940 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
1941 $this->contribution_page_id
,
1945 //fail to load payment processor id.
1946 elseif (empty($ids['pledge_payment'])) {
1947 $loadObjectSuccess = TRUE;
1949 throw new Exception("Could not find contribution page for contribution record: " . $this->id
);
1951 return $loadObjectSuccess;
1956 // we are in event mode
1957 // make sure event exists and is valid
1958 $event = new CRM_Event_BAO_Event();
1959 $event->id
= $ids['event'];
1960 if ($ids['event'] &&
1963 throw new Exception("Could not find event: " . $ids['event']);
1966 $this->_relatedObjects
['event'] = &$event;
1968 $participant = new CRM_Event_BAO_Participant();
1969 $participant->id
= $ids['participant'];
1970 if ($ids['participant'] &&
1971 !$participant->find(TRUE)
1973 throw new Exception("Could not find participant: " . $ids['participant']);
1975 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
1977 $this->_relatedObjects
['participant'] = &$participant;
1979 if (!$paymentProcessorID) {
1980 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
1984 $loadObjectSuccess = TRUE;
1985 if ($paymentProcessorID) {
1986 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
1987 $this->is_test ?
'test' : 'live'
1989 $ids['paymentProcessor'] = $paymentProcessorID;
1990 $this->_relatedObjects
['paymentProcessor'] = &$paymentProcessor;
1992 elseif ($required) {
1993 $loadObjectSuccess = FALSE;
1994 throw new Exception("Could not find payment processor for contribution record: " . $this->id
);
1997 return $loadObjectSuccess;
2001 * Create array of message information - ie. return html version, txt version, to field
2003 * @param array $input incoming information
2004 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2005 * just check presence of recur object but maintaining legacy approach
2007 * @param array $ids IDs of related objects
2008 * @param array $values any values that may have already been compiled by calling process
2009 * This is augmented by values 'gathered' by gatherMessageValues
2010 * @param bool $returnMessageText distinguishes between whether to send message or return
2011 * message text. We are working towards this function ALWAYS returning message text & calling
2012 * function doing emails / pdfs with it
2013 * @return array $messageArray - messages
2015 function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2016 if (empty($this->_relatedObjects
)) {
2017 $this->loadRelatedObjects($input, $ids);
2019 if (empty($this->_component
)) {
2020 $this->_component
= CRM_Utils_Array
::value('component', $input);
2023 //not really sure what params might be passed in but lets merge em into values
2024 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2025 $template = CRM_Core_Smarty
::singleton();
2026 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2027 //what does recur 'mean here - to do with payment processor return functionality but
2028 // what is the importance
2029 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2030 $paymentObject = &CRM_Core_Payment
::singleton(
2031 $this->is_test ?
'test' : 'live',
2032 $this->_relatedObjects
['paymentProcessor']
2035 $entityID = $entity = NULL;
2036 if (isset($ids['contribution'])) {
2037 $entity = 'contribution';
2038 $entityID = $ids['contribution'];
2040 if (isset($ids['membership']) && $ids['membership']) {
2041 $entity = 'membership';
2042 $entityID = $ids['membership'];
2045 $url = $paymentObject->subscriptionURL($entityID, $entity);
2046 $template->assign('cancelSubscriptionUrl', $url);
2048 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2049 $template->assign('updateSubscriptionBillingUrl', $url);
2051 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2052 $template->assign('updateSubscriptionUrl', $url);
2054 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2055 //direct mode showing billing block, so use directIPN for temporary
2056 $template->assign('contributeMode', 'directIPN');
2059 // todo remove strtolower - check consistency
2060 if (strtolower($this->_component
) == 'event') {
2061 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2062 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2066 $values['contribution_id'] = $this->id
;
2067 if (!empty($ids['related_contact'])) {
2068 $values['related_contact'] = $ids['related_contact'];
2069 if (isset($ids['onbehalf_dupe_alert'])) {
2070 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2072 $entityBlock = array(
2073 'contact_id' => $ids['contact'],
2074 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2075 'Home', 'id', 'name'
2078 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2079 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2082 if ($this->is_test
) {
2085 if (!empty($this->_relatedObjects
['membership'])) {
2086 foreach ($this->_relatedObjects
['membership'] as $membership) {
2087 if ($membership->id
) {
2088 $values['membership_id'] = $membership->id
;
2090 // need to set the membership values here
2091 $template->assign('membership_assign', 1);
2092 $template->assign('membership_name',
2093 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2095 $template->assign('mem_start_date', $membership->start_date
);
2096 $template->assign('mem_join_date', $membership->join_date
);
2097 $template->assign('mem_end_date', $membership->end_date
);
2098 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2099 $template->assign('mem_status', $membership_status);
2100 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2101 $template->assign('is_pay_later', 1);
2104 // if separate payment there are two contributions recorded and the
2105 // admin will need to send a receipt for each of them separately.
2106 // we dont link the two in the db (but can potentially infer it if needed)
2107 $template->assign('is_separate_payment', 0);
2109 if ($recur && $paymentObject) {
2110 $url = $paymentObject->subscriptionURL($membership->id
, 'membership');
2111 $template->assign('cancelSubscriptionUrl', $url);
2112 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2113 $template->assign('updateSubscriptionBillingUrl', $url);
2114 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2115 $template->assign('updateSubscriptionUrl', $url);
2118 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2121 // otherwise if its about sending emails, continue sending without return, as we
2122 // don't want to exit the loop.
2127 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2133 * Gather values for contribution mail - this function has been created
2134 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2135 * Values related to the contribution in question are gathered
2137 * @param array $input input into function (probably from payment processor)
2138 * @param array $ids the set of ids related to the inpurt
2140 * @return array $values
2142 * NB don't add direct calls to the function as we intend to change the signature
2144 function _gatherMessageValues($input, &$values, $ids = array()) {
2145 // set display address of contributor
2146 if ($this->address_id
) {
2147 $addressParams = array('id' => $this->address_id
);
2148 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2149 $addressDetails = array_values($addressDetails);
2150 $values['address'] = $addressDetails[0]['display'];
2152 if ($this->_component
== 'contribute') {
2153 if (isset($this->contribution_page_id
)) {
2154 CRM_Contribute_BAO_ContributionPage
::setValues(
2155 $this->contribution_page_id
,
2158 if ($this->contribution_page_id
) {
2159 // CRM-8254 - override default currency if applicable
2160 $config = CRM_Core_Config
::singleton();
2161 $config->defaultCurrency
= CRM_Utils_Array
::value(
2164 $config->defaultCurrency
2168 // no contribution page -probably back office
2170 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2171 $values['is_email_receipt'] = 1;
2172 $values['title'] = 'Contribution';
2174 // set lineItem for contribution
2176 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2177 if (!empty($lineItem)) {
2178 $itemId = key($lineItem);
2179 foreach ($lineItem as &$eachItem) {
2180 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership']) ) {
2181 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2182 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2183 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2186 $values['lineItem'][0] = $lineItem;
2187 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2191 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2195 // if this is onbehalf of contribution then set related contact
2196 if (!empty($relatedContact['individual_id'])) {
2197 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2202 $eventParams = array(
2203 'id' => $this->_relatedObjects
['event']->id
,
2205 $values['event'] = array();
2207 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2209 //get location details
2210 $locationParams = array(
2211 'entity_id' => $this->_relatedObjects
['event']->id
,
2212 'entity_table' => 'civicrm_event',
2214 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2216 $ufJoinParams = array(
2217 'entity_table' => 'civicrm_event',
2218 'entity_id' => $ids['event'],
2219 'module' => 'CiviEvent',
2222 list($custom_pre_id,
2224 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2226 $values['custom_pre_id'] = $custom_pre_id;
2227 $values['custom_post_id'] = $custom_post_ids;
2229 // set lineItem for event contribution
2231 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2232 if (!empty($participantIds)) {
2233 foreach ($participantIds as $pIDs) {
2234 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2235 if (!CRM_Utils_System
::isNull($lineItem)) {
2236 $values['lineItem'][] = $lineItem;
2247 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2248 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2249 * Note we send directly from this function in some cases because it is only partly refactored
2250 * Don't call this function directly as the signature will change
2252 function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = True) {
2253 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2254 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2255 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2256 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2257 $template->assign('useForMember', true);
2259 //assign honor infomation to receiptmessage
2260 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2262 if (isset($softRecord['soft_credit'])) {
2263 //if id of contribution page is present
2264 if (!empty($values['id'])) {
2265 $values['honor'] = array(
2266 'honor_profile_values' => array(),
2267 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2268 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2270 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2272 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2273 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2276 //offline contribution
2277 $softCreditTypes = $softCredits = array();
2278 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2279 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2280 $softCredits[$key] = array(
2281 'Name' => $softCredit['contact_name'],
2282 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency'])
2285 $template->assign('softCreditTypes', $softCreditTypes);
2286 $template->assign('softCredits', $softCredits);
2290 $dao = new CRM_Contribute_DAO_ContributionProduct();
2291 $dao->contribution_id
= $this->id
;
2292 if ($dao->find(TRUE)) {
2293 $premiumId = $dao->product_id
;
2294 $template->assign('option', $dao->product_option
);
2296 $productDAO = new CRM_Contribute_DAO_Product();
2297 $productDAO->id
= $premiumId;
2298 $productDAO->find(TRUE);
2299 $template->assign('selectPremium', TRUE);
2300 $template->assign('product_name', $productDAO->name
);
2301 $template->assign('price', $productDAO->price
);
2302 $template->assign('sku', $productDAO->sku
);
2304 $template->assign('title', CRM_Utils_Array
::value('title',$values));
2305 $amount = CRM_Utils_Array
::value('total_amount', $input,(CRM_Utils_Array
::value('amount', $input)),null);
2306 if(empty($amount) && isset($this->total_amount
)){
2307 $amount = $this->total_amount
;
2309 $template->assign('amount', $amount);
2310 // add the new contribution values
2311 if (strtolower($this->_component
) == 'contribute') {
2313 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2314 $softDAO->contribution_id
= $this->id
;
2315 if ($softDAO->find(TRUE)) {
2316 $template->assign('pcpBlock', TRUE);
2317 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2318 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2319 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2321 //assign the pcp page title for email subject
2322 $pcpDAO = new CRM_PCP_DAO_PCP();
2323 $pcpDAO->id
= $softDAO->pcp_id
;
2324 if ($pcpDAO->find(TRUE)) {
2325 $template->assign('title', $pcpDAO->title
);
2330 if ($this->financial_type_id
) {
2331 $values['financial_type_id'] = $this->financial_type_id
;
2335 $template->assign('trxn_id', $this->trxn_id
);
2336 $template->assign('receive_date',
2337 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2339 $template->assign('contributeMode', 'notify');
2340 $template->assign('action', $this->is_test ?
1024 : 1);
2341 $template->assign('receipt_text',
2342 CRM_Utils_Array
::value('receipt_text',
2346 $template->assign('is_monetary', 1);
2347 $template->assign('is_recur', (bool) $recur);
2348 $template->assign('currency', $this->currency
);
2349 $template->assign('address', CRM_Utils_Address
::format($input));
2350 if ($this->_component
== 'event') {
2351 $template->assign('title', $values['event']['title']);
2352 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2353 $viewRoles = array();
2354 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2355 $viewRoles[] = $participantRoles[$v];
2357 $values['event']['participant_role'] = implode(', ', $viewRoles);
2358 $template->assign('event', $values['event']);
2359 $template->assign('location', $values['location']);
2360 $template->assign('customPre', $values['custom_pre_id']);
2361 $template->assign('customPost', $values['custom_post_id']);
2364 if ($this->_relatedObjects
['participant']->is_test
) {
2368 $values['params'] = array();
2369 //to get email of primary participant.
2370 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2371 $primaryAmount[] = array('label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects
['participant']->fee_amount
);
2372 //build an array of cId/pId of participants
2373 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2374 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2375 //send receipt to additional participant if exists
2376 if (count($additionalIDs)) {
2377 $template->assign('isPrimary', 0);
2378 $template->assign('customProfile', NULL);
2379 //set additionalParticipant true
2380 $values['params']['additionalParticipant'] = TRUE;
2381 foreach ($additionalIDs as $pId => $cId) {
2383 //to change the status pending to completed
2384 $additional = new CRM_Event_DAO_Participant();
2385 $additional->id
= $pId;
2386 $additional->contact_id
= $cId;
2387 $additional->find(TRUE);
2388 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2389 $additional->status_id
= 1;
2390 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2391 //if additional participant dont have email
2393 if (!$additionalParticipantInfo) {
2394 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2396 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2397 $primaryAmount[] = array('label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount
);
2398 $additional->save();
2399 $additional->free();
2400 $template->assign('amount', $amount);
2401 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2405 //build an array of custom profile and assigning it to template
2406 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2408 if (count($customProfile)) {
2409 $template->assign('customProfile', $customProfile);
2412 // for primary contact
2413 $values['params']['additionalParticipant'] = FALSE;
2414 $template->assign('isPrimary', 1);
2415 $template->assign('amount', $primaryAmount);
2416 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2417 if ($this->payment_instrument_id
) {
2418 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2419 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2421 // carry paylater, since we did not created billing,
2422 // so need to pull email from primary location, CRM-4395
2423 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2429 * Function to check whether payment processor supports
2430 * cancellation of contribution subscription
2432 * @param int $contributionId contribution id
2438 static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2439 $cacheKeyString = "$contributionId";
2440 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2442 static $supportsCancel = array();
2444 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2445 $supportsCancel[$cacheKeyString] = FALSE;
2446 $isCancelled = FALSE;
2448 if ($isNotCancelled) {
2449 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2452 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2453 if (!empty($paymentObject)) {
2454 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2457 return $supportsCancel[$cacheKeyString];
2461 * Function to check whether subscription is already cancelled
2463 * @param int $contributionId contribution id
2465 * @return string $status contribution status
2469 static function isSubscriptionCancelled($contributionId) {
2471 SELECT cr.contribution_status_id
2472 FROM civicrm_contribution_recur cr
2473 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2474 WHERE con.id = %1 LIMIT 1";
2475 $params = array(1 => array($contributionId, 'Integer'));
2476 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2477 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2478 if ($status == 'Cancelled') {
2485 * Function to create all financial accounts entry
2487 * @param array $params contribution object, line item array and params for trxn
2493 static function recordFinancialAccounts(&$params, $financialTrxnVals = NULL) {
2494 $skipRecords = $update = FALSE;
2495 // in few scenarios we require the trxn record details which has got created
2497 $additionalParticipantId = array();
2498 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2500 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2501 $entityId = $params['participant_id'];
2502 $entityTable = 'civicrm_participant';
2503 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2506 $entityId = $params['contribution']->id
;
2507 $entityTable = 'civicrm_contribution';
2510 $entityID[] = $entityId;
2511 if (!empty($additionalParticipantId)) {
2512 $entityID +
= $additionalParticipantId;
2514 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2515 if (empty($params['prevContribution'])) {
2522 $statusId = $params['contribution']->contribution_status_id
;
2523 // CRM-13964 partial payment
2524 if (CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2525 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
2526 $partialAmtPay = $params['partial_amount_pay'];
2527 $partialAmtTotal = $params['partial_payment_total'];
2529 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2530 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2531 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
2532 $params['total_amount'] = $partialAmtPay;
2534 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
2535 if (empty($balanceTrxnInfo['trxn_id'])) {
2536 // create new balance transaction record
2537 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2538 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2540 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2541 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2542 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
2543 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2544 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2545 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2546 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
2547 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
2548 $balanceTrxnParams['status_id'] = $statusId;
2549 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2550 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2551 if (!empty($params['payment_processor'])) {
2552 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2554 CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
2558 // build line item array if its not set in $params
2559 if (empty($params['line_item']) ||
$additionalParticipantId) {
2560 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable));
2563 if (CRM_Utils_Array
::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2564 !(CRM_Utils_Array
::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later
)) {
2565 $skipRecords = TRUE;
2566 $pendingStatus = array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses));
2567 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $params), $pendingStatus)) {
2568 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2569 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
2571 elseif (!empty($params['payment_processor'])) {
2572 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2574 elseif (!empty($params['payment_instrument_id'])) {
2575 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
2578 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2579 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2580 $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);
2583 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
2584 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2585 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
2588 //build financial transaction params
2589 $trxnParams = array(
2590 'contribution_id' => $params['contribution']->id
,
2591 'to_financial_account_id' => $params['to_financial_account_id'],
2592 'trxn_date' => date('YmdHis'),
2593 'total_amount' => $totalAmount,
2594 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
2595 'net_amount' => CRM_Utils_Array
::value('net_amount', $params),
2596 'currency' => $params['contribution']->currency
,
2597 'trxn_id' => $params['contribution']->trxn_id
,
2598 'status_id' => $statusId,
2599 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
2600 'check_number' => CRM_Utils_Array
::value('check_number', $params),
2603 if (!empty($params['payment_processor'])) {
2604 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2607 if (isset($fromFinancialAccountId)) {
2608 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2611 // consider external values passed for recording transaction entry
2612 if (!empty($financialTrxnVals)) {
2613 $trxnParams = array_merge($trxnParams, $financialTrxnVals);
2616 $params['trxnParams'] = $trxnParams;
2618 if (!empty($params['prevContribution'])) {
2619 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
2620 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
2621 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
2622 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
2623 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
2624 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2625 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2627 //if financial type is changed
2628 if (!empty($params['financial_type_id']) &&
2629 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
) {
2630 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2631 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
2632 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
2633 if ($oldFinancialAccount != $newFinancialAccount) {
2634 $params['total_amount'] = 0;
2635 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
2636 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2637 $params['prevContribution']->financial_type_id
, $relationTypeId);
2640 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2641 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2642 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2645 self
::updateFinancialAccounts($params, 'changeFinancialType');
2646 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2647 $params['financial_account_id'] = $newFinancialAccount;
2648 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2649 self
::updateFinancialAccounts($params);
2650 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2654 //Update contribution status
2655 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
2656 if (!empty($params['contribution_status_id']) &&
2657 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2658 //Update Financial Records
2659 self
::updateFinancialAccounts($params, 'changedStatus');
2662 // change Payment Instrument for a Completed contribution
2663 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2664 // instrument is null and now new payment instrument is added along with the payment
2665 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2666 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
2667 if (array_key_exists('payment_instrument_id', $params)) {
2668 $params['trxnParams']['total_amount'] = - $trxnParams['total_amount'];
2669 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
2670 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)) {
2671 //check if status is changed from Pending to Completed
2672 // do not update payment instrument changes for Pending to Completed
2673 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
2674 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))) {
2675 // for all other statuses create new financial records
2676 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2677 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2678 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2681 else if ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
2682 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
2683 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
) {
2684 // for any other payment instrument changes create new financial records
2685 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2686 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2687 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2689 else if (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
2690 $params['contribution']->check_number
!= $params['prevContribution']->check_number
) {
2691 // another special case when check number is changed, create new financial records
2692 // create financial trxn with negative amount
2693 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
2694 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2695 // create financial trxn with positive amount
2696 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
2697 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2698 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
2702 //if Change contribution amount
2703 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
2704 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
2705 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2706 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
2707 if (isset($totalAmount) &&
2708 $totalAmount != $params['prevContribution']->total_amount
) {
2709 //Update Financial Records
2710 $params['trxnParams']['from_financial_account_id'] = NULL;
2711 self
::updateFinancialAccounts($params, 'changedAmount');
2716 // records finanical trxn and entity financial trxn
2717 // also make it available as return value
2718 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
2719 $params['entity_id'] = $financialTxn->id
;
2722 // record line items and finacial items
2723 if (empty($params['skipLineItem'])) {
2724 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
2727 // create batch entry if batch_id is passed
2728 if (!empty($params['batch_id'])) {
2729 $entityParams = array(
2730 'batch_id' => $params['batch_id'],
2731 'entity_table' => 'civicrm_financial_trxn',
2732 'entity_id' => $financialTxn->id
,
2734 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
2737 // when a fee is charged
2738 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
2739 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
2742 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2743 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
) {
2744 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2745 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
2746 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
2748 unset($params['line_item']);
2754 * Function to update all financial accounts entry
2756 * @param array $params contribution object, line item array and params for trxn
2758 * @param string $context update scenarios
2763 static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2764 $itemAmount = $trxnID = NULL;
2765 //get all the statuses
2766 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2767 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2768 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2769 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2770 && $context == 'changePaymentInstrument') {
2773 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
2774 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
2776 if ($context == 'changedStatus') {
2777 //get all the statuses
2778 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2780 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
2781 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
2782 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))) {
2783 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2785 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2786 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)) {
2787 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
2788 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2789 $params['trxnParams']['to_financial_account_id'] = NULL;
2790 $params['trxnParams']['total_amount'] = - $params['total_amount'];
2792 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2793 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
2794 $financialTypeID, $relationTypeId);
2796 $itemAmount = $params['trxnParams']['total_amount'];
2798 elseif ($context == 'changePaymentInstrument') {
2799 if ($params['trxnParams']['total_amount'] < 0) {
2800 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
2801 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2802 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2803 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
2807 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2808 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
2811 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
2812 $params['entity_id'] = $trxn->id
;
2814 if ($context == 'changedStatus') {
2815 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
2816 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
2817 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))) {
2818 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2819 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2821 $entityParams = array(
2822 'entity_table' => 'civicrm_financial_item',
2823 'financial_trxn_id' => $trxn->id
,
2825 foreach ($params['line_item'] as $fieldId => $fields) {
2826 foreach ($fields as $fieldValueId => $fieldValues) {
2828 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
2829 2 => array($fieldValues['id'], 'Integer'),
2831 CRM_Core_DAO
::executeQuery($query, $fparams);
2833 1 => array($fieldValues['id'], 'Integer'),
2835 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
2836 while ($financialItem->fetch()) {
2837 $entityParams['entity_id'] = $financialItem->id
;
2838 $entityParams['amount'] = $financialItem->amount
;
2839 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
2846 if ($context != 'changePaymentInstrument') {
2847 $itemParams['entity_table'] = 'civicrm_line_item';
2848 $trxnIds['id'] = $params['entity_id'];
2849 foreach ($params['line_item'] as $fieldId => $fields) {
2850 foreach ($fields as $fieldValueId => $fieldValues) {
2851 $prevParams['entity_id'] = $fieldValues['id'];
2852 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
2854 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
2855 if ($params['contribution']->receive_date
) {
2856 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
2859 $financialAccount = $prevfinancialItem->financial_account_id
;
2860 if (!empty($params['financial_account_id'])) {
2861 $financialAccount = $params['financial_account_id'];
2864 $currency = $params['prevContribution']->currency
;
2865 if ($params['contribution']->currency
) {
2866 $currency = $params['contribution']->currency
;
2868 if (!empty($params['is_quick_config'])) {
2869 $amount = $itemAmount;
2871 $amount = $params['total_amount'];
2876 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
2879 $amount = $diff * $fieldValues['line_total'];
2882 $itemParams = array(
2883 'transaction_date' => $receiveDate,
2884 'contact_id' => $params['prevContribution']->contact_id
,
2885 'currency' => $currency,
2886 'amount' => $amount,
2887 'description' => $prevfinancialItem->description
,
2888 'status_id' => $prevfinancialItem->status_id
,
2889 'financial_account_id' => $financialAccount,
2890 'entity_table' => 'civicrm_line_item',
2891 'entity_id' => $fieldValues['id']
2893 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
2900 * Function to check status validation on update of a contribution
2902 * @param array $values previous form values before submit
2904 * @param array $fields the input form values
2906 * @param array $errors list of errors
2911 static function checkStatusValidation($values, &$fields, &$errors) {
2912 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
2913 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
2914 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
2918 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2919 $checkStatus = array(
2920 'Cancelled' => array('Completed', 'Refunded'),
2921 'Completed' => array('Cancelled', 'Refunded'),
2922 'Pending' => array('Cancelled', 'Completed', 'Failed'),
2923 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
2924 'Refunded' => array('Cancelled', 'Completed')
2927 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
2928 $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']]));
2933 * Function to delete contribution of contact
2937 * @param integer $contactId contact id
2942 static function deleteContactContribution($contactId) {
2943 $contribution = new CRM_Contribute_DAO_Contribution();
2944 $contribution->contact_id
= $contactId;
2945 $contribution->find();
2946 while ($contribution->fetch()) {
2947 self
::deleteContribution($contribution->id
);
2952 * Get options for a given contribution field.
2953 * @see CRM_Core_DAO::buildOptions
2955 * @param String $fieldName
2956 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
2957 * @param Array $props: whatever is known about this dao object
2959 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2960 $className = __CLASS__
;
2962 switch ($fieldName) {
2963 // This field is not part of this object but the api supports it
2964 case 'payment_processor':
2965 $className = 'CRM_Contribute_BAO_ContributionPage';
2966 // Filter results by contribution page
2967 if (!empty($props['contribution_page_id'])) {
2968 $page = civicrm_api('contribution_page', 'getsingle', array(
2970 'id' => ($props['contribution_page_id'])
2972 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
2973 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
2976 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
2980 * Function to validate financial type
2984 * @param integer $financialTypeId Financial Type id
2989 static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
2990 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
2991 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
2993 if (!$financialAccount) {
2994 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3001 * Function to record additional payment for partial and refund contributions
3003 * @param integer $contributionId : is the invoice contribution id (got created after processing participant payment)
3004 * @param array $trxnData : to take user provided input of transaction details.
3005 * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
3007 static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3008 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3009 $getInfoOf['id'] = $contributionId;
3010 $defaults = array();
3011 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3013 if ($paymentType == 'owed') {
3014 // build params for recording financial trxn entry
3015 $params['contribution'] = $contributionDAO;
3016 $params = array_merge($defaults, $params);
3017 $params['skipLineItem'] = TRUE;
3018 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3019 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3020 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3023 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3024 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3025 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3027 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3028 $trxnId = $trxnId['trxn_id'];
3031 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3032 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3033 FROM civicrm_financial_trxn ft
3034 LEFT JOIN civicrm_entity_financial_trxn eft
3035 ON (ft.id = eft.financial_trxn_id)
3036 WHERE eft.entity_table = 'civicrm_contribution'
3037 AND eft.entity_id = {$contributionId}
3038 AND ft.to_financial_account_id != {$toFinancialAccount}
3039 AND ft.status_id = {$statusId}
3041 $sumOfPayments = CRM_Core_DAO
::singleValueQuery($sql);
3044 if ($contributionDAO->total_amount
== $sumOfPayments) {
3045 // update contribution status
3046 $contributionUpdate['id'] = $contributionId;
3047 $contributionUpdate['contribution_status_id'] = $statusId;
3048 $contributionUpdate['skipLineItem'] = TRUE;
3049 // note : not using the self::add method,
3050 // the reason because it performs 'status change' related code execution for financial records
3051 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3052 // are coded below i.e. just updating financial_item status to 'Paid'
3053 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3055 if ($participantId) {
3056 // update participant status
3057 $participantUpdate['id'] = $participantId;
3058 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3059 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3060 CRM_Event_BAO_Participant
::add($participantUpdate);
3063 // update financial item statuses
3064 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3065 $paidStatus = array_search('Paid', $financialItemStatus);
3067 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3068 $sqlFinancialItemUpdate = "
3069 UPDATE civicrm_financial_item fi
3070 LEFT JOIN civicrm_entity_financial_trxn eft
3071 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3072 SET status_id = {$paidStatus}
3073 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3075 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3078 elseif ($paymentType == 'refund') {
3079 // build params for recording financial trxn entry
3080 $params['contribution'] = $contributionDAO;
3081 $params = array_merge($defaults, $params);
3082 $params['skipLineItem'] = TRUE;
3083 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3084 $trxnsData['total_amount'] = - $trxnsData['total_amount'];
3086 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3087 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3088 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3090 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3092 // note : not using the self::add method,
3093 // the reason because it performs 'status change' related code execution for financial records
3094 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3095 // are coded below i.e. just updating financial_item status to 'Paid'
3096 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3098 // add financial item entry
3099 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3100 $getLine['entity_id'] = $contributionDAO->id
;
3101 $getLine['entity_table'] = 'civicrm_contribution';
3102 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3103 $addFinancialEntry = array(
3104 'transaction_date' => $financialTrxn->trxn_date
,
3105 'contact_id' => $contributionDAO->contact_id
,
3106 'amount' => $financialTrxn->total_amount
,
3107 'status_id' => array_search('Paid', $financialItemStatus),
3108 'entity_id' => $lineItemId->id
,
3109 'entity_table' => 'civicrm_line_item'
3111 $trxnIds['id'] = $financialTrxn->id
;
3112 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3114 if ($participantId) {
3115 // update participant status
3116 $participantUpdate['id'] = $participantId;
3117 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3118 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3119 CRM_Event_BAO_Participant
::add($participantUpdate);
3123 // activity creation
3124 if (!empty($financialTrxn)) {
3125 if ($participantId) {
3126 $inputParams['id'] = $participantId;
3129 $component = 'event';
3130 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3131 $entityObj = $entityObj[$participantId];
3133 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3135 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3137 return $financialTrxn;
3140 static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3141 if ($component == 'event') {
3142 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3143 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3144 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3145 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3146 $targetCid = $entityObj->contact_id
;
3147 // source record id would be the contribution id
3148 $srcRecId = $contributionId;
3152 $activityParams = array(
3153 'source_contact_id' => $targetCid,
3154 'source_record_id' => $srcRecId,
3155 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3159 'subject' => $subject,
3160 'activity_date_time' => $date,
3161 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3165 'skipRecentView' => TRUE,
3168 // create activity with target contacts
3169 $session = CRM_Core_Session
::singleton();
3170 $id = $session->get('userID');
3172 $activityParams['source_contact_id'] = $id;
3173 $activityParams['target_contact_id'][] = $targetCid;
3175 CRM_Activity_BAO_Activity
::create($activityParams);
3178 static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3179 if ($component == 'event') {
3180 $entity = 'participant';
3181 $entityTable = 'civicrm_participant';
3182 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3184 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3185 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3191 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3192 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3195 if (empty($total) ||
$usingLineTotal) {
3196 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3199 $baseTrxnId = $total['trxn_id'];
3200 $total = $total['total_amount'];
3203 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3204 $info['total'] = $total;
3205 $info['paid'] = $total - $paymentBalance;
3206 $info['balance'] = $paymentBalance;
3208 $info['component'] = $component;
3210 if ($getTrxnInfo && $baseTrxnId) {
3212 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3213 FROM civicrm_contribution con
3214 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3215 LEFT JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
3216 WHERE con.id = {$contributionId}
3219 // conditioned WHERE clause
3221 // if balance trxn exists don't include details of it in transaction info
3222 $sql .= " AND ft.id != {$baseTrxnId} ";
3224 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3226 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3227 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3228 while($resultDAO->fetch()) {
3229 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3230 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3232 'total_amount' => $resultDAO->total_amount
,
3233 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3234 'payment_instrument' => $paidByLabel,
3235 'receive_date' => $resultDAO->trxn_date
,
3236 'trxn_id' => $resultDAO->trxn_id
,
3237 'status' => $statuses[$resultDAO->status_id
],
3239 if ($paidByName == 'Check') {
3240 $val['check_number'] = $resultDAO->check_number
;
3244 $info['transaction'] = $rows;