3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
33 class CRM_Contribute_BAO_Contribution
extends CRM_Contribute_DAO_Contribution
{
36 * Static field for all the contribution information that we can potentially import
40 static $_importableFields = NULL;
43 * Static field for all the contribution information that we can potentially export
47 static $_exportableFields = NULL;
50 * Field for all the objects related to this contribution
51 * @var array of objects (e.g membership object, participant object)
53 public $_relatedObjects = array();
56 * Field for the component - either 'event' (participant) or 'contribute'
57 * (any item related to a contribution page e.g. membership, pledge, contribution)
58 * This is used for composing messages because they have dependency on the
59 * contribution_page or event page - although over time we may eliminate that
61 * @var string component or event
63 public $_component = NULL;
66 * Possibly obsolete variable.
68 * If you use it please explain why it is set in the create function here.
72 public $trxn_result_code;
77 public function __construct() {
78 parent
::__construct();
82 * Takes an associative array and creates a contribution object.
84 * the function extract all the params it needs to initialize the create a
85 * contribution object. the params array could contain additional unused name/value
88 * @param array $params
89 * (reference ) an assoc array of name/value pairs.
91 * The array that holds all the db ids.
93 * @return CRM_Contribute_BAO_Contribution|void
95 public static function add(&$params, $ids = array()) {
99 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
100 $contributionID = CRM_Utils_Array
::value('contribution', $ids, CRM_Utils_Array
::value('id', $params));
101 $duplicates = array();
102 if (self
::checkDuplicate($params, $duplicates, $contributionID)) {
103 $error = CRM_Core_Error
::singleton();
104 $d = implode(', ', $duplicates);
105 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
108 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
113 // first clean up all the money fields
114 $moneyFields = array(
118 'non_deductible_amount',
121 //if priceset is used, no need to cleanup money
122 if (!empty($params['skipCleanMoney'])) {
123 unset($moneyFields[0]);
126 foreach ($moneyFields as $field) {
127 if (isset($params[$field])) {
128 $params[$field] = CRM_Utils_Rule
::cleanMoney($params[$field]);
132 //set defaults in create mode
133 if (!$contributionID) {
134 CRM_Core_DAO
::setCreateDefaults($params, self
::getDefaults());
137 //if contribution is created with cancelled or refunded status, add credit note id
138 if (!empty($params['contribution_status_id'])) {
139 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
140 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
141 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
142 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
144 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
145 $params['creditnote_id'] = self
::createCreditNoteId();
150 // Since the fee amount is expecting this (later on) ensure it is always set.
151 // It would only not be set for an update where it is unchanged.
152 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
155 self
::calculateMissingAmountParams($params, $contributionID);
157 if (!empty($params['payment_instrument_id'])) {
158 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument('name');
159 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
160 $params['check_number'] = 'null';
164 $setPrevContribution = TRUE;
165 // CRM-13964 partial payment
166 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
167 $partialAmtTotal = $params['partial_payment_total'];
168 $partialAmtPay = $params['partial_amount_pay'];
169 $params['total_amount'] = $partialAmtTotal;
170 if ($partialAmtPay < $partialAmtTotal) {
171 $params['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name');
172 $params['is_pay_later'] = 0;
173 $setPrevContribution = FALSE;
176 if ($contributionID && $setPrevContribution) {
177 $params['prevContribution'] = self
::getValues(array('id' => $contributionID), CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
180 if ($contributionID) {
181 CRM_Utils_Hook
::pre('edit', 'Contribution', $contributionID, $params);
184 CRM_Utils_Hook
::pre('create', 'Contribution', NULL, $params);
186 $contribution = new CRM_Contribute_BAO_Contribution();
187 $contribution->copyValues($params);
189 $contribution->id
= $contributionID;
191 if (empty($contribution->id
)) {
192 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
193 if (!CRM_Utils_Rule
::currencyCode($contribution->currency
)) {
194 $contribution->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
198 $result = $contribution->save();
200 // Add financial_trxn details as part of fix for CRM-4724
201 $contribution->trxn_result_code
= CRM_Utils_Array
::value('trxn_result_code', $params);
202 $contribution->payment_processor
= CRM_Utils_Array
::value('payment_processor', $params);
204 //add Account details
205 $params['contribution'] = $contribution;
206 self
::recordFinancialAccounts($params);
208 if (self
::isUpdateToRecurringContribution($params)) {
209 CRM_Contribute_BAO_ContributionRecur
::updateOnNewPayment(
210 (!empty($params['contribution_recur_id']) ?
$params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id
),
211 $contributionStatus[$params['contribution_status_id']]
215 // reset the group contact cache for this group
216 CRM_Contact_BAO_GroupContactCache
::remove();
218 if ($contributionID) {
219 CRM_Utils_Hook
::post('edit', 'Contribution', $contribution->id
, $contribution);
222 CRM_Utils_Hook
::post('create', 'Contribution', $contribution->id
, $contribution);
229 * Is this contribution updating an existing recurring contribution.
231 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
232 * pending payment is being confirmed (or failing).
234 * @param array $params
238 public static function isUpdateToRecurringContribution($params) {
239 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
242 if (empty($params['prevContribution']) ||
empty($params['contribution_status_id'])) {
245 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id
)) {
248 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
249 if ($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)) {
256 * Get defaults for new entity.
259 public static function getDefaults() {
261 'payment_instrument_id' => key(CRM_Core_OptionGroup
::values('payment_instrument',
262 FALSE, FALSE, FALSE, 'AND is_default = 1')
264 'contribution_status_id' => CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name'),
269 * Fetch the object and store the values in the values array.
271 * @param array $params
272 * Input parameters to find object.
273 * @param array $values
274 * Output values of the object.
276 * The array that holds all the db ids.
278 * @return CRM_Contribute_BAO_Contribution|null
279 * The found object or null
281 public static function getValues($params, &$values, &$ids) {
282 if (empty($params)) {
285 $contribution = new CRM_Contribute_BAO_Contribution();
287 $contribution->copyValues($params);
289 if ($contribution->find(TRUE)) {
290 $ids['contribution'] = $contribution->id
;
292 CRM_Core_DAO
::storeValues($contribution, $values);
294 return $contribution;
296 $null = NULL; // return by reference
301 * Get the values and resolve the most common mappings.
303 * Since contribution status is resolved in almost every function that calls getValues it makes
304 * sense to have an extra function to resolve it rather than repeat the code.
306 * Think carefully before adding more mappings to be resolved as there could be performance implications
307 * if this function starts to be called from more iterative functions.
309 * @param array $params
310 * Input parameters to find object.
313 * Array of the found contribution.
314 * @throws CRM_Core_Exception
316 public static function getValuesWithMappings($params) {
317 $values = $ids = array();
318 $contribution = self
::getValues($params, $values, $ids);
319 if (is_null($contribution)) {
320 throw new CRM_Core_Exception('No contribution found');
322 $values['contribution_status'] = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
327 * Calculate net_amount & fee_amount if they are not set.
329 * Net amount should be total - fee.
330 * This should only be called for new contributions.
332 * @param array $params
333 * Params for a new contribution before they are saved.
334 * @param int|null $contributionID
335 * Contribution ID if we are dealing with an update.
337 * @throws \CiviCRM_API3_Exception
339 public static function calculateMissingAmountParams(&$params, $contributionID) {
340 if (!$contributionID && !isset($params['fee_amount'])) {
341 if (isset($params['total_amount']) && isset($params['net_amount'])) {
342 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
345 $params['fee_amount'] = 0;
348 if (!isset($params['net_amount'])) {
349 if (!$contributionID) {
350 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
353 if (isset($params['fee_amount']) ||
isset($params['total_amount'])) {
354 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
355 // net_amount may need adjusting.
356 $contribution = civicrm_api3('Contribution', 'getsingle', array(
357 'id' => $contributionID,
358 'return' => array('total_amount', 'net_amount'),
360 $totalAmount = isset($params['total_amount']) ?
$params['total_amount'] : CRM_Utils_Array
::value('total_amount', $contribution);
361 $feeAmount = isset($params['fee_amount']) ?
$params['fee_amount'] : CRM_Utils_Array
::value('fee_amount', $contribution);
362 $params['net_amount'] = $totalAmount - $feeAmount;
370 * @param $billingLocationTypeID
374 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
375 $hasBillingField = FALSE;
376 $billingFields = array(
384 //build address array
385 $addressParams = array();
386 $addressParams['location_type_id'] = $billingLocationTypeID;
387 $addressParams['is_billing'] = 1;
389 $billingFirstName = CRM_Utils_Array
::value('billing_first_name', $params);
390 $billingMiddleName = CRM_Utils_Array
::value('billing_middle_name', $params);
391 $billingLastName = CRM_Utils_Array
::value('billing_last_name', $params);
392 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingMiddleName}" . CRM_Core_DAO
::VALUE_SEPARATOR
. "{$billingLastName}";
394 foreach ($billingFields as $value) {
395 $addressParams[$value] = CRM_Utils_Array
::value("billing_{$value}-{$billingLocationTypeID}", $params);
396 if (!empty($addressParams[$value])) {
397 $hasBillingField = TRUE;
400 return array($hasBillingField, $addressParams);
404 * Get address params ready to be passed to the payment processor.
406 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
407 * To create an address we need state_province_id.
409 * @param array $params
410 * @param int $billingLocationTypeID
414 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
415 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
416 foreach ($addressParams as $name => $field) {
417 if (substr($name, 0, 8) == 'billing_') {
418 $addressParams[substr($name, 9)] = $addressParams[$field];
421 return array($hasBillingField, $addressParams);
425 * Get the number of terms for this contribution for a given membership type
426 * based on querying the line item table and relevant price field values
427 * Note that any one contribution should only be able to have one line item relating to a particular membership
430 * @param int $membershipTypeID
432 * @param int $contributionID
436 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
437 $numTerms = CRM_Core_DAO
::singleValueQuery("
438 SELECT membership_num_terms FROM civicrm_line_item li
439 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
440 WHERE contribution_id = %1 AND membership_type_id = %2",
441 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
443 // default of 1 is precautionary
444 return empty($numTerms) ?
1 : $numTerms;
448 * Takes an associative array and creates a contribution object.
450 * @param array $params
451 * (reference ) an assoc array of name/value pairs.
453 * The array that holds all the db ids.
455 * @return CRM_Contribute_BAO_Contribution
457 public static function create(&$params, $ids = array()) {
458 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
459 foreach ($dateFields as $df) {
460 if (isset($params[$df])) {
461 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
465 //if contribution is created with cancelled or refunded status, add credit note id
466 if (!empty($params['contribution_status_id'])) {
467 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
469 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
470 ||
$params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
472 if (empty($params['creditnote_id']) ||
$params['creditnote_id'] == "null") {
473 $params['creditnote_id'] = self
::createCreditNoteId();
478 $transaction = new CRM_Core_Transaction();
480 $contribution = self
::add($params, $ids);
482 if (is_a($contribution, 'CRM_Core_Error')) {
483 $transaction->rollback();
484 return $contribution;
487 $params['contribution_id'] = $contribution->id
;
489 if (!empty($params['custom']) &&
490 is_array($params['custom'])
492 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
495 $session = CRM_Core_Session
::singleton();
497 if (!empty($params['note'])) {
499 'entity_table' => 'civicrm_contribution',
500 'note' => $params['note'],
501 'entity_id' => $contribution->id
,
502 'contact_id' => $session->get('userID'),
503 'modified_date' => date('Ymd'),
505 if (!$noteParams['contact_id']) {
506 $noteParams['contact_id'] = $params['contact_id'];
508 CRM_Core_BAO_Note
::add($noteParams);
511 // make entry in batch entity batch table
512 if (!empty($params['batch_id'])) {
513 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
514 $titleFields = array(
520 $retrieveRequired = 0;
521 foreach ($titleFields as $titleField) {
522 if (!isset($contribution->$titleField)) {
523 $retrieveRequired = 1;
527 if ($retrieveRequired == 1) {
528 $contribution->find(TRUE);
532 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
534 $transaction->commit();
536 // check if activity record exist for this contribution, if
538 $activity = new CRM_Activity_DAO_Activity();
539 $activity->source_record_id
= $contribution->id
;
540 $activity->activity_type_id
= CRM_Core_OptionGroup
::getValue('activity_type',
544 if (!$activity->find(TRUE)) {
545 if (empty($contribution->contact_id
)) {
546 $contribution->find(TRUE);
548 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Offline');
551 // CRM-13237 : if activity record found, update it with campaign id of contribution
552 CRM_Core_DAO
::setFieldValue('CRM_Activity_BAO_Activity', $activity->id
, 'campaign_id', $contribution->campaign_id
);
555 // do not add to recent items for import, CRM-4399
556 if (empty($params['skipRecentView'])) {
557 $url = CRM_Utils_System
::url('civicrm/contact/view/contribution',
558 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
560 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
561 $titleFields = array(
567 $retrieveRequired = 0;
568 foreach ($titleFields as $titleField) {
569 if (!isset($contribution->$titleField)) {
570 $retrieveRequired = 1;
574 if ($retrieveRequired == 1) {
575 $contribution->find(TRUE);
577 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
578 $title = CRM_Contact_BAO_Contact
::displayName($contribution->contact_id
) . ' - (' . CRM_Utils_Money
::format($contribution->total_amount
, $contribution->currency
) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id
] . ')';
580 $recentOther = array();
581 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::UPDATE
)) {
582 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
583 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
587 if (CRM_Core_Permission
::checkActionPermission('CiviContribute', CRM_Core_Action
::DELETE
)) {
588 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/contribution',
589 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
593 // add the recently created Contribution
594 CRM_Utils_Recent
::add($title,
598 $contribution->contact_id
,
604 return $contribution;
608 * Get the values for pseudoconstants for name->value and reverse.
610 * @param array $defaults
611 * (reference) the default values, some of which need to be resolved.
612 * @param bool $reverse
613 * True if we want to resolve the values in the reverse direction (value -> name).
615 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
616 self
::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant
::financialType(), $reverse);
617 self
::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant
::paymentInstrument(), $reverse);
618 self
::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant
::contributionStatus(), $reverse);
619 self
::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant
::pcPage(), $reverse);
623 * Convert associative array names to values and vice-versa.
625 * This function is used by both the web form layer and the api. Note that
626 * the api needs the name => value conversion, also the view layer typically
627 * requires value => name conversion
629 * @param array $defaults
630 * @param string $property
631 * @param array $lookup
632 * @param bool $reverse
636 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
637 $id = $property . '_id';
639 $src = $reverse ?
$property : $id;
640 $dst = $reverse ?
$id : $property;
642 if (!array_key_exists($src, $defaults)) {
646 $look = $reverse ?
array_flip($lookup) : $lookup;
648 if (is_array($look)) {
649 if (!array_key_exists($defaults[$src], $look)) {
653 $defaults[$dst] = $look[$defaults[$src]];
658 * Retrieve DB object based on input parameters.
660 * It also stores all the retrieved values in the default array.
662 * @param array $params
663 * (reference ) an assoc array of name/value pairs.
664 * @param array $defaults
665 * (reference ) an assoc array to hold the name / value pairs.
666 * in a hierarchical manner
668 * (reference) the array that holds all the db ids.
670 * @return CRM_Contribute_BAO_Contribution
672 public static function retrieve(&$params, &$defaults, &$ids) {
673 $contribution = CRM_Contribute_BAO_Contribution
::getValues($params, $defaults, $ids);
674 return $contribution;
678 * Combine all the importable fields from the lower levels object.
680 * The ordering is important, since currently we do not have a weight
681 * scheme. Adding weight is super important and should be done in the
682 * next week or so, before this can be called complete.
684 * @param string $contactType
685 * @param bool $status
688 * array of importable Fields
690 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
691 if (!self
::$_importableFields) {
692 if (!self
::$_importableFields) {
693 self
::$_importableFields = array();
697 $fields = array('' => array('title' => ts('- do not import -')));
700 $fields = array('' => array('title' => ts('- Contribution Fields -')));
703 $note = CRM_Core_DAO_Note
::import();
704 $tmpFields = CRM_Contribute_DAO_Contribution
::import();
705 unset($tmpFields['option_value']);
706 $optionFields = CRM_Core_OptionValue
::getFields($mode = 'contribute');
707 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
709 // Using new Dedupe rule.
711 'contact_type' => $contactType,
712 'used' => 'Unsupervised',
714 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
715 $tmpContactField = array();
716 if (is_array($fieldsArray)) {
717 foreach ($fieldsArray as $value) {
718 //skip if there is no dupe rule
719 if ($value == 'none') {
722 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
727 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
728 $tmpContactField[trim($value)] = $contactFields[trim($value)];
730 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
733 $title = $tmpContactField[trim($value)]['title'];
735 $tmpContactField[trim($value)]['title'] = $title;
739 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
740 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
741 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
742 $fields = array_merge($fields, $tmpContactField);
743 $fields = array_merge($fields, $tmpFields);
744 $fields = array_merge($fields, $note);
745 $fields = array_merge($fields, $optionFields);
746 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType
::export());
747 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
748 self
::$_importableFields = $fields;
750 return self
::$_importableFields;
754 * Combine all the exportable fields from the lower level objects.
756 * @param bool $checkPermission
759 * array of exportable Fields
761 public static function &exportableFields($checkPermission = TRUE) {
762 if (!self
::$_exportableFields) {
763 if (!self
::$_exportableFields) {
764 self
::$_exportableFields = array();
767 $impFields = CRM_Contribute_DAO_Contribution
::export();
768 $expFieldProduct = CRM_Contribute_DAO_Product
::export();
769 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct
::export();
770 $typeField = CRM_Financial_DAO_FinancialType
::export();
771 $financialAccount = CRM_Financial_DAO_FinancialAccount
::export();
772 $optionField = CRM_Core_OptionValue
::getFields($mode = 'contribute');
773 $contributionStatus = array(
774 'contribution_status' => array(
775 'title' => ts('Contribution Status'),
776 'name' => 'contribution_status',
777 'data_type' => CRM_Utils_Type
::T_STRING
,
781 $contributionPage = array(
782 'contribution_page' => array(
783 'title' => ts('Contribution Page'),
784 'name' => 'contribution_page',
785 'where' => 'civicrm_contribution_page.title',
786 'data_type' => CRM_Utils_Type
::T_STRING
,
790 $contributionNote = array(
791 'contribution_note' => array(
792 'title' => ts('Contribution Note'),
793 'name' => 'contribution_note',
794 'data_type' => CRM_Utils_Type
::T_TEXT
,
798 $contributionRecurId = array(
799 'contribution_recur_id' => array(
800 'title' => ts('Recurring Contributions ID'),
801 'name' => 'contribution_recur_id',
802 'where' => 'civicrm_contribution.contribution_recur_id',
803 'data_type' => CRM_Utils_Type
::T_INT
,
807 $extraFields = array(
808 'contribution_batch' => array(
809 'title' => ts('Batch Name'),
814 $campaignTitle = array(
815 'contribution_campaign_title' => array(
816 'title' => ts('Campaign Title'),
817 'name' => 'campaign_title',
818 'where' => 'civicrm_campaign.title',
819 'data_type' => CRM_Utils_Type
::T_STRING
,
822 $softCreditFields = array(
823 'contribution_soft_credit_name' => array(
824 'name' => 'contribution_soft_credit_name',
825 'title' => 'Soft Credit For',
826 'where' => 'civicrm_contact_d.display_name',
827 'data_type' => CRM_Utils_Type
::T_STRING
,
829 'contribution_soft_credit_amount' => array(
830 'name' => 'contribution_soft_credit_amount',
831 'title' => 'Soft Credit Amount',
832 'where' => 'civicrm_contribution_soft.amount',
833 'data_type' => CRM_Utils_Type
::T_MONEY
,
835 'contribution_soft_credit_type' => array(
836 'name' => 'contribution_soft_credit_type',
837 'title' => 'Soft Credit Type',
838 'where' => 'contribution_softcredit_type.label',
839 'data_type' => CRM_Utils_Type
::T_STRING
,
841 'contribution_soft_credit_contribution_id' => array(
842 'name' => 'contribution_soft_credit_contribution_id',
843 'title' => 'Soft Credit For Contribution ID',
844 'where' => 'civicrm_contribution_soft.contribution_id',
845 'data_type' => CRM_Utils_Type
::T_INT
,
847 'contribution_soft_credit_contact_id' => array(
848 'name' => 'contribution_soft_credit_contact_id',
849 'title' => 'Soft Credit For Contact ID',
850 'where' => 'civicrm_contact_d.id',
851 'data_type' => CRM_Utils_Type
::T_INT
,
855 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
857 'contribution_product_id' => array(
858 'title' => ts('Premium'),
859 'name' => 'contribution_product_id',
860 'where' => 'civicrm_product.id',
861 'data_type' => CRM_Utils_Type
::T_INT
,
865 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
866 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
867 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
870 self
::$_exportableFields = $fields;
873 return self
::$_exportableFields;
877 * @param null $status
878 * @param null $startDate
879 * @param null $endDate
883 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
887 $where[] = 'contribution_status_id = 1';
891 $where[] = 'contribution_status_id = 3';
896 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
899 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
901 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
902 if ($financialTypes) {
903 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
904 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
907 $where[] = "c.financial_type_id IN (0)";
910 $whereCond = implode(' AND ', $where);
913 SELECT sum( total_amount ) as total_amount,
914 count( c.id ) as total_count,
916 FROM civicrm_contribution c
917 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
918 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
920 AND ( is_test = 0 OR is_test IS NULL )
921 AND contact.is_deleted = 0
925 $dao = CRM_Core_DAO
::executeQuery($query);
928 while ($dao->fetch()) {
929 $count +
= $dao->total_count
;
930 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
934 'amount' => implode(', ', $amount),
942 * Delete the indirect records associated with this contribution first.
947 * $results no of deleted Contribution on success, false otherwise
949 public static function deleteContribution($id) {
950 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
952 $transaction = new CRM_Core_Transaction();
955 //delete activity record
957 'source_record_id' => $id,
958 // activity type id for contribution
959 'activity_type_id' => 6,
962 CRM_Activity_BAO_Activity
::deleteActivity($params);
964 //delete billing address if exists for this contribution.
965 self
::deleteAddress($id);
967 //update pledge and pledge payment, CRM-3961
968 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
970 // remove entry from civicrm_price_set_entity, CRM-5095
971 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
972 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
974 // cleanup line items.
975 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
977 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
978 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
980 if ($participantId) {
981 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
984 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
988 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
989 $noteId = key($note);
991 CRM_Core_BAO_Note
::del($noteId, FALSE);
994 $dao = new CRM_Contribute_DAO_Contribution();
997 $results = $dao->delete();
999 $transaction->commit();
1001 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
1003 // delete the recently created Contribution
1004 $contributionRecent = array(
1006 'type' => 'Contribution',
1008 CRM_Utils_Recent
::del($contributionRecent);
1014 * React to a financial transaction (payment) failure.
1016 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1017 * payments is important for forensic and outreach reasons.
1019 * @param int $contributionID
1020 * @param int $contactID
1021 * @param string $message
1023 * @throws \CiviCRM_API3_Exception
1025 public static function failPayment($contributionID, $contactID, $message) {
1026 civicrm_api3('activity', 'create', array(
1027 'activity_type_id' => 'Failed Payment',
1028 'details' => $message,
1029 'subject' => ts('Payment failed at payment processor'),
1030 'source_record_id' => $contributionID,
1031 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1037 * Check if there is a contribution with the same trxn_id or invoice_id.
1039 * @param array $input
1040 * An assoc array of name/value pairs.
1041 * @param array $duplicates
1042 * (reference) store ids of duplicate contribs.
1046 * true if duplicate, false otherwise
1048 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1050 $id = CRM_Utils_Array
::value('id', $input);
1052 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1053 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1059 $clause[] = "trxn_id = %1";
1060 $input[1] = array($trxn_id, 'String');
1064 $clause[] = "invoice_id = %2";
1065 $input[2] = array($invoice_id, 'String');
1068 if (empty($clause)) {
1072 $clause = implode(' OR ', $clause);
1074 $clause = "( $clause ) AND id != %3";
1075 $input[3] = array($id, 'Integer');
1078 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1079 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1081 while ($dao->fetch()) {
1082 $duplicates[] = $dao->id
;
1089 * Takes an associative array and creates a contribution_product object.
1091 * the function extract all the params it needs to initialize the create a
1092 * contribution_product object. the params array could contain additional unused name/value
1095 * @param array $params
1096 * (reference) an assoc array of name/value pairs.
1098 * @return CRM_Contribute_DAO_ContributionProduct
1100 public static function addPremium(&$params) {
1101 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1102 $contributionProduct->copyValues($params);
1103 return $contributionProduct->save();
1107 * Get list of contribution fields for profile.
1108 * For now we only allow custom contribution fields to be in
1111 * @param bool $addExtraFields
1112 * True if special fields needs to be added.
1115 * the list of contribution fields
1117 public static function getContributionFields($addExtraFields = TRUE) {
1118 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1119 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1121 if ($addExtraFields) {
1122 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1125 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1127 foreach ($contributionFields as $key => $var) {
1128 if ($key == 'contribution_contact_id') {
1131 elseif ($key == 'contribution_campaign_id') {
1132 $var['title'] = ts('Campaign');
1134 $fields[$key] = $var;
1137 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1142 * Add extra fields specific to contribution.
1144 public static function getSpecialContributionFields() {
1145 $extraFields = array(
1146 'contribution_soft_credit_name' => array(
1147 'name' => 'contribution_soft_credit_name',
1148 'title' => 'Soft Credit Name',
1149 'headerPattern' => '/^soft_credit_name$/i',
1150 'where' => 'civicrm_contact_d.display_name',
1152 'contribution_soft_credit_email' => array(
1153 'name' => 'contribution_soft_credit_email',
1154 'title' => 'Soft Credit Email',
1155 'headerPattern' => '/^soft_credit_email$/i',
1156 'where' => 'soft_email.email',
1158 'contribution_soft_credit_phone' => array(
1159 'name' => 'contribution_soft_credit_phone',
1160 'title' => 'Soft Credit Phone',
1161 'headerPattern' => '/^soft_credit_phone$/i',
1162 'where' => 'soft_phone.phone',
1164 'contribution_soft_credit_contact_id' => array(
1165 'name' => 'contribution_soft_credit_contact_id',
1166 'title' => 'Soft Credit Contact ID',
1167 'headerPattern' => '/^soft_credit_contact_id$/i',
1168 'where' => 'civicrm_contribution_soft.contact_id',
1170 'contribution_pcp_title' => array(
1171 'name' => 'contribution_pcp_title',
1172 'title' => 'Personal Campaign Page Title',
1173 'headerPattern' => '/^contribution_pcp_title$/i',
1174 'where' => 'contribution_pcp.title',
1178 return $extraFields;
1182 * @param int $pageID
1186 public static function getCurrentandGoalAmount($pageID) {
1188 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1189 FROM civicrm_contribution_page p,
1190 civicrm_contribution c
1191 WHERE p.id = c.contribution_page_id
1193 AND c.cancel_date is null
1197 $config = CRM_Core_Config
::singleton();
1198 $params = array(1 => array($pageID, 'Integer'));
1199 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1201 if ($dao->fetch()) {
1202 return array($dao->goal
, $dao->total
);
1205 return array(NULL, NULL);
1210 * Get list of contribution In Honor of contact Ids.
1212 * @param int $honorId
1213 * In Honor of Contact ID.
1216 * list of contribution fields
1218 public static function getHonorContacts($honorId) {
1220 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1221 $honorDAO->contact_id
= $honorId;
1224 $type = CRM_Contribute_PseudoConstant
::financialType();
1226 while ($honorDAO->fetch()) {
1227 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1228 $contributionDAO->id
= $honorDAO->contribution_id
;
1230 if ($contributionDAO->find(TRUE)) {
1231 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1232 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1233 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1234 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1235 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1236 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1237 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1238 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1239 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1247 * Get the sort name of a contact for a particular contribution.
1250 * Id of the contribution.
1252 * @return null|string
1253 * sort name of the contact if found
1255 public static function sortName($id) {
1256 $id = CRM_Utils_Type
::escape($id, 'Integer');
1259 SELECT civicrm_contact.sort_name
1260 FROM civicrm_contribution, civicrm_contact
1261 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1262 AND civicrm_contribution.id = {$id}
1264 return CRM_Core_DAO
::singleValueQuery($query);
1268 * @param int $contactID
1272 public static function annual($contactID) {
1273 if (is_array($contactID)) {
1274 $contactIDs = implode(',', $contactID);
1277 $contactIDs = $contactID;
1280 $config = CRM_Core_Config
::singleton();
1281 $startDate = $endDate = NULL;
1283 $currentMonth = date('m');
1284 $currentDay = date('d');
1285 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1286 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1287 (int ) $config->fiscalYearStart
['d'] > $currentDay
1290 $year = date('Y') - 1;
1295 $nextYear = $year +
1;
1297 if ($config->fiscalYearStart
) {
1298 $newFiscalYearStart = $config->fiscalYearStart
;
1299 if ($newFiscalYearStart['M'] < 10) {
1300 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1302 if ($newFiscalYearStart['d'] < 10) {
1303 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1305 $config->fiscalYearStart
= $newFiscalYearStart;
1306 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1311 $startDate = "$year$monthDay";
1312 $endDate = "$nextYear$monthDay";
1313 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1314 $additionalWhere = " AND b.financial_type_id IN (0)";
1315 $liWhere = " AND i.financial_type_id IN (0)";
1316 if (!empty($financialTypes)) {
1317 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1318 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1321 SELECT count(*) as count,
1322 sum(total_amount) as amount,
1323 avg(total_amount) as average,
1325 FROM civicrm_contribution b
1326 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1327 WHERE b.contact_id IN ( $contactIDs )
1328 AND b.contribution_status_id = 1
1330 AND b.receive_date >= $startDate
1331 AND b.receive_date < $endDate
1335 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1337 $amount = $average = array();
1338 while ($dao->fetch()) {
1339 if ($dao->count
> 0 && $dao->amount
> 0) {
1340 $count +
= $dao->count
;
1341 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1342 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1348 implode(', ', $amount),
1349 implode(', ', $average),
1352 return array(0, 0, 0);
1356 * Check if there is a contribution with the params passed in.
1358 * Used for trxn_id,invoice_id and contribution_id
1360 * @param array $params
1361 * An assoc array of name/value pairs.
1364 * contribution id if success else NULL
1366 public static function checkDuplicateIds($params) {
1367 $dao = new CRM_Contribute_DAO_Contribution();
1371 foreach ($params as $k => $v) {
1373 $clause[] = "$k = '$v'";
1376 $clause = implode(' AND ', $clause);
1377 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1378 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1380 while ($dao->fetch()) {
1388 * Get the contribution details for component export.
1390 * @param int $exportMode
1392 * @param string $componentIds
1398 public static function getContributionDetails($exportMode, $componentIds) {
1399 $paymentDetails = array();
1400 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1402 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1403 $componentSelect = " civicrm_participant_payment.participant_id id";
1404 $additionalClause = "
1405 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1406 AND civicrm_participant_payment.participant_id {$componentClause} )
1409 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1410 $componentSelect = " civicrm_membership_payment.membership_id id";
1411 $additionalClause = "
1412 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1413 AND civicrm_membership_payment.membership_id {$componentClause} )
1416 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1417 $componentSelect = " civicrm_pledge_payment.id id";
1418 $additionalClause = "
1419 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1420 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1424 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1425 trxn_id, {$componentSelect}
1426 FROM civicrm_contribution
1427 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1428 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1429 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1430 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1431 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1432 AND option_group_contribution_status.id = contribution_status.option_group_id )
1436 $dao = CRM_Core_DAO
::executeQuery($query);
1438 while ($dao->fetch()) {
1439 $paymentDetails[$dao->id
] = array(
1440 'total_amount' => $dao->total_amount
,
1441 'contribution_status' => $dao->status
,
1442 'receive_date' => $dao->receive_date
,
1443 'pay_instru' => $dao->payment_instrument
,
1444 'trxn_id' => $dao->trxn_id
,
1448 return $paymentDetails;
1452 * Create address associated with contribution record.
1454 * As long as there is one or more billing field in the parameters we will create the address.
1456 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1459 * @param array $params
1460 * @param int $billingLocationTypeID
1465 public static function createAddress($params, $billingLocationTypeID) {
1466 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1467 if ($hasBillingField) {
1468 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1469 return $address->id
;
1476 * Delete billing address record related contribution.
1478 * @param int $contributionId
1479 * @param int $contactId
1481 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1483 $contactJoin = NULL;
1485 if ($contributionId) {
1486 $clauses[] = "cc.id = {$contributionId}";
1490 $clauses[] = "cco.id = {$contactId}";
1491 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1494 if (empty($clauses)) {
1495 CRM_Core_Error
::fatal();
1498 $condition = implode(' OR ', $clauses);
1502 FROM civicrm_address ca
1503 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1507 $dao = CRM_Core_DAO
::executeQuery($query);
1509 while ($dao->fetch()) {
1510 $params = array('id' => $dao->id
);
1511 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1516 * This function check online pending contribution associated w/
1517 * Online Event Registration or Online Membership signup.
1519 * @param int $componentId
1520 * Participant/membership id.
1521 * @param string $componentName
1525 * pending contribution id.
1527 public static function checkOnlinePendingContribution($componentId, $componentName) {
1528 $contributionId = NULL;
1529 if (!$componentId ||
1530 !in_array($componentName, array('Event', 'Membership'))
1532 return $contributionId;
1535 if ($componentName == 'Event') {
1536 $idName = 'participant_id';
1537 $componentTable = 'civicrm_participant';
1538 $paymentTable = 'civicrm_participant_payment';
1539 $source = ts('Online Event Registration');
1542 if ($componentName == 'Membership') {
1543 $idName = 'membership_id';
1544 $componentTable = 'civicrm_membership';
1545 $paymentTable = 'civicrm_membership_payment';
1546 $source = ts('Online Contribution');
1549 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1552 SELECT component.id as {$idName},
1553 componentPayment.contribution_id as contribution_id,
1554 contribution.source source,
1555 contribution.contribution_status_id as contribution_status_id,
1556 contribution.is_pay_later as is_pay_later
1557 FROM $componentTable component
1558 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1559 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1560 WHERE component.id = {$componentId}";
1562 $dao = CRM_Core_DAO
::executeQuery($query);
1564 while ($dao->fetch()) {
1565 if ($dao->contribution_id
&&
1566 $dao->is_pay_later
&&
1567 $dao->contribution_status_id
== $pendingStatusId &&
1568 strpos($dao->source
, $source) !== FALSE
1570 $contributionId = $dao->contribution_id
;
1575 return $contributionId;
1579 * Update contribution as well as related objects.
1581 * This function by-passes hooks - to address this - don't use this function.
1585 * Use api contribute.completetransaction
1586 * For failures use failPayment (preferably exposing by api in the process).
1588 * @param array $params
1589 * @param bool $processContributionObject
1592 * @throws \Exception
1594 public static function transitionComponents($params, $processContributionObject = FALSE) {
1595 // get minimum required values.
1596 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1597 $componentId = CRM_Utils_Array
::value('component_id', $params);
1598 $componentName = CRM_Utils_Array
::value('componentName', $params);
1599 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1600 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1602 // if we already processed contribution object pass previous status id.
1603 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1605 $updateResult = array();
1607 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1609 // we process only ( Completed, Cancelled, or Failed ) contributions.
1610 if (!$contributionId ||
1611 !in_array($contributionStatusId, array(
1612 array_search('Completed', $contributionStatuses),
1613 array_search('Cancelled', $contributionStatuses),
1614 array_search('Failed', $contributionStatuses),
1617 return $updateResult;
1620 if (!$componentName ||
!$componentId) {
1621 // get the related component details.
1622 $componentDetails = self
::getComponentDetails($contributionId);
1625 $componentDetails['contact_id'] = $contactId;
1626 $componentDetails['component'] = $componentName;
1628 if ($componentName == 'event') {
1629 $componentDetails['participant'] = $componentId;
1632 $componentDetails['membership'] = $componentId;
1636 if (!empty($componentDetails['contact_id'])) {
1637 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1643 // do check for required ids.
1644 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1645 return $updateResult;
1648 //now we are ready w/ required ids, start processing.
1650 $baseIPN = new CRM_Core_Payment_BaseIPN();
1652 $input = $ids = $objects = array();
1654 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1655 $ids['contribution'] = $contributionId;
1656 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1657 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1658 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1659 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1660 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1661 $ids['contributionRecur'] = NULL;
1662 $ids['contributionPage'] = NULL;
1664 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1665 CRM_Core_Error
::fatal();
1668 $memberships = &$objects['membership'];
1669 $participant = &$objects['participant'];
1670 $pledgePayment = &$objects['pledge_payment'];
1671 $contribution = &$objects['contribution'];
1673 if ($pledgePayment) {
1674 $pledgePaymentIDs = array();
1675 foreach ($pledgePayment as $key => $object) {
1676 $pledgePaymentIDs[] = $object->id
;
1678 $pledgeID = $pledgePayment[0]->pledge_id
;
1681 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1684 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1685 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1690 // we might want to process contribution object.
1691 $processContribution = FALSE;
1692 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1693 if (is_array($memberships)) {
1694 foreach ($memberships as $membership) {
1696 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1697 $membership->save();
1699 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1700 if ($processContributionObject) {
1701 $processContribution = TRUE;
1708 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1709 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1711 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1712 if ($processContributionObject) {
1713 $processContribution = TRUE;
1717 if ($pledgePayment) {
1718 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1720 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1721 if ($processContributionObject) {
1722 $processContribution = TRUE;
1726 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1727 if (is_array($memberships)) {
1728 foreach ($memberships as $membership) {
1730 $membership->status_id
= array_search('Expired', $membershipStatuses);
1731 $membership->save();
1733 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1734 if ($processContributionObject) {
1735 $processContribution = TRUE;
1741 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1742 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1744 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1745 if ($processContributionObject) {
1746 $processContribution = TRUE;
1750 if ($pledgePayment) {
1751 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1753 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1754 if ($processContributionObject) {
1755 $processContribution = TRUE;
1759 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1761 // only pending contribution related object processed.
1762 if ($previousContriStatusId &&
1763 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1765 // this is case when we already processed contribution object.
1766 return $updateResult;
1768 elseif (!$previousContriStatusId &&
1769 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1771 // this is case when we are going to process contribution object later.
1772 return $updateResult;
1775 if (is_array($memberships)) {
1776 foreach ($memberships as $membership) {
1781 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1782 $membership->membership_type_id
,
1783 $membership->is_test
, $membership->id
1786 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1787 // this picks up membership type changes during renewals
1789 SELECT membership_type_id
1790 FROM civicrm_membership_log
1791 WHERE membership_id=$membership->id
1794 $dao = new CRM_Core_DAO();
1796 if ($dao->fetch()) {
1797 if (!empty($dao->membership_type_id
)) {
1798 $membership->membership_type_id
= $dao->membership_type_id
;
1799 $membership->save();
1802 // else fall back to using current membership type
1805 // Figure out number of terms
1807 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1808 foreach ($lineitems as $lineitem) {
1809 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1810 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1812 // in case membership_num_terms comes through as null or zero
1813 $numterms = $numterms >= 1 ?
$numterms : 1;
1818 // CRM-15735-to update the membership status as per the contribution receive date
1820 if (!empty($params['receive_date'])) {
1821 $joinDate = $params['receive_date'];
1822 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1823 $membership->end_date
,
1824 $membership->join_date
,
1825 $params['receive_date'],
1827 $membership->membership_type_id
,
1830 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1831 $membership->save();
1834 if ($currentMembership) {
1835 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1836 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1837 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1840 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1843 //get the status for membership.
1844 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1846 $dates['join_date'],
1849 $membership->membership_type_id
,
1853 $formattedParams = array(
1854 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1855 array_search('Current', $membershipStatuses)
1857 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1858 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1859 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1862 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1864 $membership->copyValues($formattedParams);
1865 $membership->save();
1867 //updating the membership log
1868 $membershipLog = array();
1869 $membershipLog = $formattedParams;
1870 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1871 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1873 $membershipLog['start_date'] = $logStartDate;
1874 $membershipLog['membership_id'] = $membership->id
;
1875 $membershipLog['modified_id'] = $membership->contact_id
;
1876 $membershipLog['modified_date'] = date('Ymd');
1877 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1879 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1881 //update related Memberships.
1882 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1884 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1887 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1888 if ($processContributionObject) {
1889 $processContribution = TRUE;
1892 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1898 $updatedStatusId = array_search('Registered', $participantStatuses);
1899 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1901 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1902 if ($processContributionObject) {
1903 $processContribution = TRUE;
1907 if ($pledgePayment) {
1908 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1910 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1911 if ($processContributionObject) {
1912 $processContribution = TRUE;
1917 // process contribution object.
1918 if ($processContribution) {
1919 $contributionParams = array();
1926 'payment_instrument_id',
1929 'financial_type_id',
1930 'contribution_status_id',
1931 'non_deductible_amount',
1935 foreach ($fields as $field) {
1936 if (empty($params[$field])) {
1939 $contributionParams[$field] = $params[$field];
1942 $ids = array('contribution' => $contributionId);
1943 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1946 return $updateResult;
1950 * Returns all contribution related object ids.
1952 * @param $contributionId
1956 public static function getComponentDetails($contributionId) {
1957 $componentDetails = $pledgePayment = array();
1958 if (!$contributionId) {
1959 return $componentDetails;
1963 SELECT c.id as contribution_id,
1964 c.contact_id as contact_id,
1965 c.contribution_recur_id,
1966 mp.membership_id as membership_id,
1967 m.membership_type_id as membership_type_id,
1968 pp.participant_id as participant_id,
1969 p.event_id as event_id,
1970 pgp.id as pledge_payment_id
1971 FROM civicrm_contribution c
1972 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1973 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1974 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1975 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1976 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1977 WHERE c.id = $contributionId";
1979 $dao = CRM_Core_DAO
::executeQuery($query);
1980 $componentDetails = array();
1982 while ($dao->fetch()) {
1983 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1984 $componentDetails['contact_id'] = $dao->contact_id
;
1985 if ($dao->event_id
) {
1986 $componentDetails['event'] = $dao->event_id
;
1988 if ($dao->participant_id
) {
1989 $componentDetails['participant'] = $dao->participant_id
;
1991 if ($dao->membership_id
) {
1992 if (!isset($componentDetails['membership'])) {
1993 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1995 $componentDetails['membership'][] = $dao->membership_id
;
1996 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1998 if ($dao->pledge_payment_id
) {
1999 $pledgePayment[] = $dao->pledge_payment_id
;
2001 if ($dao->contribution_recur_id
) {
2002 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
2006 if ($pledgePayment) {
2007 $componentDetails['pledge_payment'] = $pledgePayment;
2010 return $componentDetails;
2014 * @param int $contactId
2015 * @param bool $includeSoftCredit
2017 * @return null|string
2019 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2023 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2024 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2025 $liWhere = " AND i.financial_type_id IN (0)";
2026 if (!empty($financialTypes)) {
2027 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2028 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2030 $contactContributionsSQL = "
2031 SELECT contribution.id AS id
2032 FROM civicrm_contribution contribution
2033 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2034 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2038 $contactSoftCreditContributionsSQL = "
2039 SELECT contribution.id
2040 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2041 ON ( contribution.id = softContribution.contribution_id )
2042 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2043 $query = "SELECT count( x.id ) count FROM ( ";
2044 $query .= $contactContributionsSQL;
2046 if ($includeSoftCredit) {
2047 $query .= " UNION ";
2048 $query .= $contactSoftCreditContributionsSQL;
2053 return CRM_Core_DAO
::singleValueQuery($query);
2057 * Repeat a transaction as part of a recurring series.
2059 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2060 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2061 * subsequent call to the contribution.completetransaction api.
2063 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2065 * @param CRM_Contribute_BAO_Contribution $contribution
2066 * @param array $input
2067 * @param array $contributionParams
2071 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
2072 if (!empty($contribution->id
)) {
2075 if (empty($contribution->id
)) {
2076 // Unclear why this would only be set for repeats.
2077 if (!empty($input['amount'])) {
2078 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2080 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionParams['contribution_recur_id']);
2081 if (!empty($contributionParams['contribution_recur_id'])) {
2082 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2083 'id' => $contributionParams['contribution_recur_id'],
2085 if (!empty($recurringContribution['campaign_id'])) {
2086 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2087 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2089 if (!empty($recurringContribution['financial_type_id'])) {
2090 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2091 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2094 $contributionParams['skipLineItem'] = TRUE;
2095 $contributionParams['status_id'] = 'Pending';
2096 if (isset($contributionParams['financial_type_id'])) {
2097 // Give precedence to passed in type.
2098 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2101 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2103 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2104 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2105 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2106 $contribution->id
= $createContribution['id'];
2107 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2108 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2114 * Get individual id for onbehalf contribution.
2116 * @param int $contributionId
2118 * @param int $contributorId
2122 * containing organization id and individual id
2124 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2128 if (!$contributionId) {
2132 // fetch contributor id if null
2133 if (!$contributorId) {
2134 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2135 $contributionId, 'contact_id'
2139 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2140 $activityTypeId = array_search('Contribution', $activityTypeIds);
2142 if ($activityTypeId && $contributorId) {
2144 SELECT civicrm_activity_contact.contact_id
2145 FROM civicrm_activity_contact
2146 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2147 WHERE civicrm_activity.activity_type_id = %1
2148 AND civicrm_activity.source_record_id = %2
2149 AND civicrm_activity_contact.record_type_id = %3
2152 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2153 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2156 1 => array($activityTypeId, 'Integer'),
2157 2 => array($contributionId, 'Integer'),
2158 3 => array($sourceID, 'Integer'),
2161 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2163 // for on behalf contribution source is individual and contributor is organization
2164 if ($sourceContactId && $sourceContactId != $contributorId) {
2165 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2166 // get rel type id for employee of relation
2167 foreach ($relationshipTypeIds as $id => $typeVals) {
2168 if ($typeVals['name_a_b'] == 'Employee of') {
2169 $relationshipTypeId = $id;
2174 $rel = new CRM_Contact_DAO_Relationship();
2175 $rel->relationship_type_id
= $relationshipTypeId;
2176 $rel->contact_id_a
= $sourceContactId;
2177 $rel->contact_id_b
= $contributorId;
2178 if ($rel->find(TRUE)) {
2179 $ids['individual_id'] = $rel->contact_id_a
;
2180 $ids['organization_id'] = $rel->contact_id_b
;
2191 public static function getContributionDates() {
2192 $config = CRM_Core_Config
::singleton();
2193 $currentMonth = date('m');
2194 $currentDay = date('d');
2195 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2196 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2197 (int ) $config->fiscalYearStart
['d'] > $currentDay
2200 $year = date('Y') - 1;
2205 $year = array('Y' => $year);
2206 $yearDate = $config->fiscalYearStart
;
2207 $yearDate = array_merge($year, $yearDate);
2208 $yearDate = CRM_Utils_Date
::format($yearDate);
2210 $monthDate = date('Ym') . '01';
2216 'yearDate' => $yearDate,
2217 'monthDate' => $monthDate,
2222 * Load objects relations to contribution object.
2223 * Objects are stored in the $_relatedObjects property
2224 * In the first instance we are just moving functionality from BASEIpn -
2225 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2227 * Note that the unit test for the BaseIPN class tests this function
2229 * @param array $input
2230 * Input as delivered from Payment Processor.
2232 * Ids as Loaded by Payment Processor.
2233 * @param bool $loadAll
2234 * Load all related objects - even where id not passed in? (allows API to call this).
2239 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2241 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2242 if (empty($ids['contact']) && isset($this->contact_id
)) {
2243 $ids['contact'] = $this->contact_id
;
2246 if (empty($this->_component
)) {
2247 if (!empty($ids['event'])) {
2248 $this->_component
= 'event';
2251 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2255 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2256 // refactoring than anything else, and has unit test coverage.
2257 if (empty($this->financial_type_id
)) {
2261 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2266 if (!$paymentProcessorID && $this->contribution_page_id
) {
2267 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2268 $this->contribution_page_id
,
2271 if ($paymentProcessorID) {
2272 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2276 $ids['contributionType'] = $this->financial_type_id
;
2277 $ids['financialType'] = $this->financial_type_id
;
2280 'contact' => 'CRM_Contact_BAO_Contact',
2281 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2282 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2283 'financialType' => 'CRM_Financial_BAO_FinancialType',
2285 foreach ($entities as $entity => $bao) {
2286 if (!empty($ids[$entity])) {
2287 $this->_relatedObjects
[$entity] = new $bao();
2288 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2289 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2290 throw new CRM_Core_Exception($entity . ' could not be loaded');
2295 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2296 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2299 if (!empty($ids['pledge_payment'])) {
2300 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2301 if (empty($paymentID)) {
2304 $payment = new CRM_Pledge_BAO_PledgePayment();
2305 $payment->id
= $paymentID;
2306 if (!$payment->find(TRUE)) {
2307 throw new Exception("Could not find pledge payment record: " . $paymentID);
2309 $this->_relatedObjects
['pledge_payment'][] = $payment;
2313 $this->loadRelatedMembershipObjects($ids);
2315 if ($this->_component
!= 'contribute') {
2316 // we are in event mode
2317 // make sure event exists and is valid
2318 $event = new CRM_Event_BAO_Event();
2319 $event->id
= $ids['event'];
2320 if ($ids['event'] &&
2323 throw new Exception("Could not find event: " . $ids['event']);
2326 $this->_relatedObjects
['event'] = &$event;
2328 $participant = new CRM_Event_BAO_Participant();
2329 $participant->id
= $ids['participant'];
2330 if ($ids['participant'] &&
2331 !$participant->find(TRUE)
2333 throw new Exception("Could not find participant: " . $ids['participant']);
2335 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2337 $this->_relatedObjects
['participant'] = &$participant;
2339 // get the payment processor id from event - this is inaccurate see CRM-16923
2340 // in future we should look at throwing an exception here rather than an dubious guess.
2341 if (!$paymentProcessorID) {
2342 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2343 if ($paymentProcessorID) {
2344 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2349 if ($paymentProcessorID) {
2350 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2351 $this->is_test ?
'test' : 'live'
2353 $ids['paymentProcessor'] = $paymentProcessorID;
2354 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2360 * Create array of message information - ie. return html version, txt version, to field
2362 * @param array $input
2363 * Incoming information.
2364 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2365 * just check presence of recur object but maintaining legacy approach
2368 * IDs of related objects.
2369 * @param array $values
2370 * Any values that may have already been compiled by calling process.
2371 * This is augmented by values 'gathered' by gatherMessageValues
2372 * @param bool $recur
2373 * @param bool $returnMessageText
2374 * Distinguishes between whether to send message or return.
2375 * message text. We are working towards this function ALWAYS returning message text & calling
2376 * function doing emails / pdfs with it
2382 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2383 $this->loadRelatedObjects($input, $ids);
2385 if (empty($this->_component
)) {
2386 $this->_component
= CRM_Utils_Array
::value('component', $input);
2389 //not really sure what params might be passed in but lets merge em into values
2390 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2391 if (!empty($input['receipt_date'])) {
2392 $values['receipt_date'] = $input['receipt_date'];
2395 $template = CRM_Core_Smarty
::singleton();
2396 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2397 //what does recur 'mean here - to do with payment processor return functionality but
2398 // what is the importance
2399 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2400 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2402 $entityID = $entity = NULL;
2403 if (isset($ids['contribution'])) {
2404 $entity = 'contribution';
2405 $entityID = $ids['contribution'];
2407 if (!empty($ids['membership'])) {
2408 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2409 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2410 // line having loaded an array
2411 $ids['membership'] = (array) $ids['membership'];
2412 $entity = 'membership';
2413 $entityID = $ids['membership'][0];
2416 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2417 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2418 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2420 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2421 //direct mode showing billing block, so use directIPN for temporary
2422 $template->assign('contributeMode', 'directIPN');
2425 // todo remove strtolower - check consistency
2426 if (strtolower($this->_component
) == 'event') {
2427 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2428 $values['event'] = array();
2430 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2432 //get location details
2433 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2434 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2436 $ufJoinParams = array(
2437 'entity_table' => 'civicrm_event',
2438 'entity_id' => $ids['event'],
2439 'module' => 'CiviEvent',
2442 list($custom_pre_id,
2444 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2446 $values['custom_pre_id'] = $custom_pre_id;
2447 $values['custom_post_id'] = $custom_post_ids;
2448 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2449 //and cases involving status updation through ipn
2450 // whatever that means!
2451 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2452 // perhaps we should throw an e-notice if amount is set & force total_amount?
2453 if (!empty($input['amount'])) {
2454 $values['totalAmount'] = $input['amount'];
2457 if ($values['event']['is_email_confirm']) {
2458 $values['is_email_receipt'] = 1;
2461 if (!empty($ids['contribution'])) {
2462 $values['contributionId'] = $ids['contribution'];
2465 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2466 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2470 $values['contribution_id'] = $this->id
;
2471 if (!empty($ids['related_contact'])) {
2472 $values['related_contact'] = $ids['related_contact'];
2473 if (isset($ids['onbehalf_dupe_alert'])) {
2474 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2476 $entityBlock = array(
2477 'contact_id' => $ids['contact'],
2478 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2479 'Home', 'id', 'name'
2482 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2483 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2486 if ($this->is_test
) {
2489 if (!empty($this->_relatedObjects
['membership'])) {
2490 foreach ($this->_relatedObjects
['membership'] as $membership) {
2491 if ($membership->id
) {
2492 $values['isMembership'] = TRUE;
2493 $values['membership_assign'] = TRUE;
2495 // need to set the membership values here
2496 $template->assign('membership_name',
2497 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2499 $template->assign('mem_start_date', $membership->start_date
);
2500 $template->assign('mem_join_date', $membership->join_date
);
2501 $template->assign('mem_end_date', $membership->end_date
);
2502 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2503 $template->assign('mem_status', $membership_status);
2504 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2505 $template->assign('is_pay_later', 1);
2508 // if separate payment there are two contributions recorded and the
2509 // admin will need to send a receipt for each of them separately.
2510 // we dont link the two in the db (but can potentially infer it if needed)
2511 $template->assign('is_separate_payment', 0);
2513 if ($recur && $paymentObject) {
2514 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2515 $template->assign('cancelSubscriptionUrl', $url);
2516 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2517 $template->assign('updateSubscriptionBillingUrl', $url);
2518 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2519 $template->assign('updateSubscriptionUrl', $url);
2522 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2525 // otherwise if its about sending emails, continue sending without return, as we
2526 // don't want to exit the loop.
2531 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2537 * Gather values for contribution mail - this function has been created
2538 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2539 * Values related to the contribution in question are gathered
2541 * @param array $input
2542 * Input into function (probably from payment processor).
2543 * @param array $values
2545 * The set of ids related to the input.
2549 public function _gatherMessageValues($input, &$values, $ids = array()) {
2550 // set display address of contributor
2551 if ($this->address_id
) {
2552 $addressParams = array('id' => $this->address_id
);
2553 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2554 $addressDetails = array_values($addressDetails);
2555 $values['address'] = $addressDetails[0]['display'];
2557 if ($this->_component
== 'contribute') {
2558 //get soft contributions
2559 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2560 if (!empty($softContributions)) {
2561 $values['softContributions'] = $softContributions['soft_credit'];
2563 if (isset($this->contribution_page_id
)) {
2564 CRM_Contribute_BAO_ContributionPage
::setValues(
2565 $this->contribution_page_id
,
2568 if ($this->contribution_page_id
) {
2569 // CRM-8254 - override default currency if applicable
2570 $config = CRM_Core_Config
::singleton();
2571 $config->defaultCurrency
= CRM_Utils_Array
::value(
2574 $config->defaultCurrency
2578 // no contribution page -probably back office
2580 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2581 $values['is_email_receipt'] = 1;
2582 $values['title'] = 'Contribution';
2584 // set lineItem for contribution
2586 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2587 if (!empty($lineItem)) {
2588 $itemId = key($lineItem);
2589 foreach ($lineItem as &$eachItem) {
2590 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2591 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2592 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2593 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2596 $values['lineItem'][0] = $lineItem;
2597 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2601 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2605 // if this is onbehalf of contribution then set related contact
2606 if (!empty($relatedContact['individual_id'])) {
2607 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2612 $eventParams = array(
2613 'id' => $this->_relatedObjects
['event']->id
,
2615 $values['event'] = array();
2617 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2618 // add custom fields for event
2619 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2621 $eventCustomGroup = array();
2622 foreach ($eventGroupTree as $key => $group) {
2623 if ($key === 'info') {
2627 foreach ($group['fields'] as $k => $customField) {
2628 $groupLabel = $group['title'];
2629 if (!empty($customField['customValue'])) {
2630 foreach ($customField['customValue'] as $customFieldValues) {
2631 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2636 $values['event']['customGroup'] = $eventCustomGroup;
2638 //get participant details
2639 $participantParams = array(
2640 'id' => $this->_relatedObjects
['participant']->id
,
2643 $values['participant'] = array();
2645 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2646 // add custom fields for event
2647 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2648 $participantCustomGroup = array();
2649 foreach ($participantGroupTree as $key => $group) {
2650 if ($key === 'info') {
2654 foreach ($group['fields'] as $k => $customField) {
2655 $groupLabel = $group['title'];
2656 if (!empty($customField['customValue'])) {
2657 foreach ($customField['customValue'] as $customFieldValues) {
2658 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2663 $values['participant']['customGroup'] = $participantCustomGroup;
2665 //get location details
2666 $locationParams = array(
2667 'entity_id' => $this->_relatedObjects
['event']->id
,
2668 'entity_table' => 'civicrm_event',
2670 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2672 $ufJoinParams = array(
2673 'entity_table' => 'civicrm_event',
2674 'entity_id' => $ids['event'],
2675 'module' => 'CiviEvent',
2678 list($custom_pre_id,
2680 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2682 $values['custom_pre_id'] = $custom_pre_id;
2683 $values['custom_post_id'] = $custom_post_ids;
2685 // set lineItem for event contribution
2687 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2688 if (!empty($participantIds)) {
2689 foreach ($participantIds as $pIDs) {
2690 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2691 if (!CRM_Utils_System
::isNull($lineItem)) {
2692 $values['lineItem'][] = $lineItem;
2699 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2701 $customGroup = array();
2702 foreach ($groupTree as $key => $group) {
2703 if ($key === 'info') {
2707 foreach ($group['fields'] as $k => $customField) {
2708 $groupLabel = $group['title'];
2709 if (!empty($customField['customValue'])) {
2710 foreach ($customField['customValue'] as $customFieldValues) {
2711 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2716 $values['customGroup'] = $customGroup;
2722 * Assign message variables to template but try to break the habit.
2724 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2725 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2726 * multiple recurring payments for processors like IATS that use tokens.
2728 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2729 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2730 * Note we send directly from this function in some cases because it is only partly refactored.
2732 * Don't call this function directly as the signature will change.
2736 * @param CRM_Core_SMARTY $template
2737 * @param bool $recur
2738 * @param bool $returnMessageText
2742 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2743 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2744 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2745 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2746 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2747 $values['useForMember'] = TRUE;
2749 //assign honor information to receipt message
2750 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2752 if (isset($softRecord['soft_credit'])) {
2753 //if id of contribution page is present
2754 if (!empty($values['id'])) {
2755 $values['honor'] = array(
2756 'honor_profile_values' => array(),
2757 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2758 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2760 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2762 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2763 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2766 //offline contribution
2767 $softCreditTypes = $softCredits = array();
2768 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2769 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2770 $softCredits[$key] = array(
2771 'Name' => $softCredit['contact_name'],
2772 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2775 $template->assign('softCreditTypes', $softCreditTypes);
2776 $template->assign('softCredits', $softCredits);
2780 $dao = new CRM_Contribute_DAO_ContributionProduct();
2781 $dao->contribution_id
= $this->id
;
2782 if ($dao->find(TRUE)) {
2783 $premiumId = $dao->product_id
;
2784 $template->assign('option', $dao->product_option
);
2786 $productDAO = new CRM_Contribute_DAO_Product();
2787 $productDAO->id
= $premiumId;
2788 $productDAO->find(TRUE);
2789 $template->assign('selectPremium', TRUE);
2790 $template->assign('product_name', $productDAO->name
);
2791 $template->assign('price', $productDAO->price
);
2792 $template->assign('sku', $productDAO->sku
);
2794 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2795 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2796 if (!$values['amount'] && isset($this->total_amount
)) {
2797 $values['amount'] = $this->total_amount
;
2800 // add the new contribution values
2801 if (strtolower($this->_component
) == 'contribute') {
2803 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2804 $softDAO->contribution_id
= $this->id
;
2805 if ($softDAO->find(TRUE)) {
2806 $template->assign('pcpBlock', TRUE);
2807 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2808 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2809 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2811 //assign the pcp page title for email subject
2812 $pcpDAO = new CRM_PCP_DAO_PCP();
2813 $pcpDAO->id
= $softDAO->pcp_id
;
2814 if ($pcpDAO->find(TRUE)) {
2815 $template->assign('title', $pcpDAO->title
);
2820 if ($this->financial_type_id
) {
2821 $values['financial_type_id'] = $this->financial_type_id
;
2824 $template->assign('trxn_id', $this->trxn_id
);
2825 $template->assign('receive_date',
2826 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2828 $template->assign('contributeMode', 'notify');
2829 $template->assign('action', $this->is_test ?
1024 : 1);
2830 $template->assign('receipt_text',
2831 CRM_Utils_Array
::value('receipt_text',
2835 $template->assign('is_monetary', 1);
2836 $template->assign('is_recur', (bool) $recur);
2837 $template->assign('currency', $this->currency
);
2838 $template->assign('address', CRM_Utils_Address
::format($input));
2839 if (!empty($values['customGroup'])) {
2840 $template->assign('customGroup', $values['customGroup']);
2842 if (!empty($values['softContributions'])) {
2843 $template->assign('softContributions', $values['softContributions']);
2845 if ($this->_component
== 'event') {
2846 $template->assign('title', $values['event']['title']);
2847 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2848 $viewRoles = array();
2849 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2850 $viewRoles[] = $participantRoles[$v];
2852 $values['event']['participant_role'] = implode(', ', $viewRoles);
2853 $template->assign('event', $values['event']);
2854 $template->assign('participant', $values['participant']);
2855 $template->assign('location', $values['location']);
2856 $template->assign('customPre', $values['custom_pre_id']);
2857 $template->assign('customPost', $values['custom_post_id']);
2860 if ($this->_relatedObjects
['participant']->is_test
) {
2864 $values['params'] = array();
2865 //to get email of primary participant.
2866 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2867 $primaryAmount[] = array(
2868 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2869 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2871 //build an array of cId/pId of participants
2872 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2873 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2874 //send receipt to additional participant if exists
2875 if (count($additionalIDs)) {
2876 $template->assign('isPrimary', 0);
2877 $template->assign('customProfile', NULL);
2878 //set additionalParticipant true
2879 $values['params']['additionalParticipant'] = TRUE;
2880 foreach ($additionalIDs as $pId => $cId) {
2882 //to change the status pending to completed
2883 $additional = new CRM_Event_DAO_Participant();
2884 $additional->id
= $pId;
2885 $additional->contact_id
= $cId;
2886 $additional->find(TRUE);
2887 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2888 $additional->status_id
= 1;
2889 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2890 //if additional participant dont have email
2892 if (!$additionalParticipantInfo) {
2893 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2895 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2896 $primaryAmount[] = array(
2897 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2898 'amount' => $additional->fee_amount
,
2900 $additional->save();
2901 $additional->free();
2902 $template->assign('amount', $amount);
2903 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2907 //build an array of custom profile and assigning it to template
2908 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2910 if (count($customProfile)) {
2911 $template->assign('customProfile', $customProfile);
2914 // for primary contact
2915 $values['params']['additionalParticipant'] = FALSE;
2916 $template->assign('isPrimary', 1);
2917 $template->assign('amount', $primaryAmount);
2918 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2919 if ($this->payment_instrument_id
) {
2920 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2921 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2923 // carry paylater, since we did not created billing,
2924 // so need to pull email from primary location, CRM-4395
2925 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2931 * Check whether payment processor supports
2932 * cancellation of contribution subscription
2934 * @param int $contributionId
2937 * @param bool $isNotCancelled
2941 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2942 $cacheKeyString = "$contributionId";
2943 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2945 static $supportsCancel = array();
2947 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2948 $supportsCancel[$cacheKeyString] = FALSE;
2949 $isCancelled = FALSE;
2951 if ($isNotCancelled) {
2952 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2955 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2956 if (!empty($paymentObject)) {
2957 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2960 return $supportsCancel[$cacheKeyString];
2964 * Check whether subscription is already cancelled.
2966 * @param int $contributionId
2970 * contribution status
2972 public static function isSubscriptionCancelled($contributionId) {
2974 SELECT cr.contribution_status_id
2975 FROM civicrm_contribution_recur cr
2976 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2977 WHERE con.id = %1 LIMIT 1";
2978 $params = array(1 => array($contributionId, 'Integer'));
2979 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2980 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2981 if ($status == 'Cancelled') {
2988 * Create all financial accounts entry.
2990 * @param array $params
2991 * Contribution object, line item array and params for trxn.
2994 * @param array $financialTrxnValues
2996 * @return null|object
2998 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2999 $skipRecords = $update = $return = $isRelatedId = FALSE;
3001 $additionalParticipantId = array();
3002 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3003 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
3005 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
3006 $entityId = $params['participant_id'];
3007 $entityTable = 'civicrm_participant';
3008 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
3010 elseif (!empty($params['membership_id'])) {
3011 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3012 // are created off one contribution should be handled elsewhere
3013 $entityId = $params['membership_id'];
3014 $entityTable = 'civicrm_membership';
3017 $entityId = $params['contribution']->id
;
3018 $entityTable = 'civicrm_contribution';
3021 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3022 $isRelatedId = TRUE;
3025 $entityID[] = $entityId;
3026 if (!empty($additionalParticipantId)) {
3027 $entityID +
= $additionalParticipantId;
3029 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3030 if (empty($params['prevContribution'])) {
3037 $statusId = $params['contribution']->contribution_status_id
;
3038 // CRM-13964 partial payment
3039 if ($contributionStatus == 'Partially paid'
3040 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3042 $partialAmtPay = $params['partial_amount_pay'];
3043 $partialAmtTotal = $params['partial_payment_total'];
3045 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3046 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3047 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3048 $params['total_amount'] = $partialAmtPay;
3050 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3051 if (empty($balanceTrxnInfo['trxn_id'])) {
3052 // create new balance transaction record
3053 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3054 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3056 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3057 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3058 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3059 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3060 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3061 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3062 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3063 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3064 $balanceTrxnParams['status_id'] = $statusId;
3065 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3066 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3067 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3068 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3070 $balanceTrxnParams['is_payment'] = 1;
3072 if (!empty($params['payment_processor'])) {
3073 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3075 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3079 // build line item array if its not set in $params
3080 if (empty($params['line_item']) ||
$additionalParticipantId) {
3081 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3084 if ($contributionStatus != 'Failed' &&
3085 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3087 $skipRecords = TRUE;
3088 $pendingStatus = array(
3092 if (in_array($contributionStatus, $pendingStatus)) {
3093 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
3094 $params['financial_type_id'],
3095 'Accounts Receivable Account is'
3098 elseif (!empty($params['payment_processor'])) {
3099 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3101 elseif (!empty($params['payment_instrument_id'])) {
3102 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3105 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3106 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3107 $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);
3110 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3111 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3112 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3115 //build financial transaction params
3116 $trxnParams = array(
3117 'contribution_id' => $params['contribution']->id
,
3118 'to_financial_account_id' => $params['to_financial_account_id'],
3119 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3120 'total_amount' => $totalAmount,
3121 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3122 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3123 'currency' => $params['contribution']->currency
,
3124 'trxn_id' => $params['contribution']->trxn_id
,
3125 'status_id' => $statusId,
3126 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3127 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3129 if ($contributionStatus == 'Refunded' ||
$contributionStatus == 'Chargeback') {
3130 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3131 if (isset($params['refund_trxn_id'])) {
3132 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3133 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3136 //CRM-16259, set is_payment flag for non pending status
3137 if (!in_array($contributionStatus, $pendingStatus)) {
3138 $trxnParams['is_payment'] = 1;
3140 if (!empty($params['payment_processor'])) {
3141 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3144 if (isset($fromFinancialAccountId)) {
3145 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3148 // consider external values passed for recording transaction entry
3149 if (!empty($financialTrxnValues)) {
3150 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3153 $params['trxnParams'] = $trxnParams;
3155 if (!empty($params['prevContribution'])) {
3157 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3158 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3159 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3160 if (!isset($params['trxnParams']['trxn_id'])) {
3161 // Actually I have no idea why we are overwriting any values from the previous contribution.
3162 // (filling makes sense to me). However, only protecting this value as I really really know we
3163 // don't want this one overwritten.
3165 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3167 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3169 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3170 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3171 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3173 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3174 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3177 //if financial type is changed
3178 if (!empty($params['financial_type_id']) &&
3179 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3181 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3182 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3183 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3184 if ($oldFinancialAccount != $newFinancialAccount) {
3185 $params['total_amount'] = 0;
3186 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3187 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3188 $params['prevContribution']->financial_type_id
, $relationTypeId);
3191 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3192 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3193 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3196 self
::updateFinancialAccounts($params, 'changeFinancialType');
3197 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3198 $params['financial_account_id'] = $newFinancialAccount;
3199 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3200 self
::updateFinancialAccounts($params);
3201 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3206 //Update contribution status
3207 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3208 if (!isset($params['refund_trxn_id'])) {
3209 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3210 // gets preference over another so I am only 'protecting' a very specific tested flow
3211 // and letting natural justice take care of the rest.
3212 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3214 if (!empty($params['contribution_status_id']) &&
3215 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3217 //Update Financial Records
3218 self
::updateFinancialAccounts($params, 'changedStatus');
3222 // change Payment Instrument for a Completed contribution
3223 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3224 // instrument is null and now new payment instrument is added along with the payment
3225 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3226 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3227 if (array_key_exists('payment_instrument_id', $params)) {
3228 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3229 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3230 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3232 //check if status is changed from Pending to Completed
3233 // do not update payment instrument changes for Pending to Completed
3234 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3235 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3237 // for all other statuses create new financial records
3238 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3239 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3240 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3244 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3245 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3246 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3248 // for any other payment instrument changes create new financial records
3249 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3250 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3251 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3254 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3255 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3257 // another special case when check number is changed, create new financial records
3258 // create financial trxn with negative amount
3259 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3260 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3261 // create financial trxn with positive amount
3262 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3263 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3264 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3269 //if Change contribution amount
3270 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3271 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3272 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3273 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3274 if (isset($totalAmount) &&
3275 $totalAmount != $params['prevContribution']->total_amount
3277 //Update Financial Records
3278 $params['trxnParams']['from_financial_account_id'] = NULL;
3279 self
::updateFinancialAccounts($params, 'changedAmount');
3284 // Looks like we might have a data correction update.
3285 // This would be a case where a transaction id has been entered but it is incorrect &
3286 // the person goes back in & fixes it, as opposed to a new transaction.
3287 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3288 // the data fix scenario.
3290 if (isset($params['refund_trxn_id'])) {
3291 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3292 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3293 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3300 // records finanical trxn and entity financial trxn
3301 // also make it available as return value
3302 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3303 $params['entity_id'] = $financialTxn->id
;
3306 // record line items and financial items
3307 if (empty($params['skipLineItem'])) {
3308 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3311 // create batch entry if batch_id is passed and
3312 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3313 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3314 $entityParams = array(
3315 'batch_id' => $params['batch_id'],
3316 'entity_table' => 'civicrm_financial_trxn',
3317 'entity_id' => $financialTxn->id
,
3319 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3322 // when a fee is charged
3323 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3324 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3327 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3328 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3330 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3331 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3332 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3334 unset($params['line_item']);
3340 * Update all financial accounts entry.
3342 * @param array $params
3343 * Contribution object, line item array and params for trxn.
3345 * @param string $context
3348 * @param null $skipTrxn
3351 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3352 $itemAmount = $trxnID = NULL;
3353 //get all the statuses
3354 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3355 $previousContributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['prevContribution']->contribution_status_id
, 'name');
3356 if (($previousContributionStatus == 'Pending'
3357 ||
$previousContributionStatus == 'In Progress')
3358 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3359 && $context == 'changePaymentInstrument'
3363 if ((($previousContributionStatus == 'Partially paid'
3364 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3365 ||
($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later
== TRUE
3366 && $params['contribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus)))
3367 && $context == 'changedStatus'
3371 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3372 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3374 if ($context == 'changedStatus') {
3375 //get all the statuses
3376 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3377 $cancelledTaxAmount = 0;
3378 if ($previousContributionStatus == 'Completed'
3379 && (self
::isContributionStatusNegative($params['contribution']->contribution_status_id
))
3381 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3382 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3383 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3384 $creditNoteId = self
::createCreditNoteId();
3385 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3388 elseif (($previousContributionStatus == 'Pending'
3389 && $params['prevContribution']->is_pay_later
) ||
$previousContributionStatus == 'In Progress'
3391 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3392 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3393 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3395 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3396 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3397 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3398 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3399 $creditNoteId = self
::createCreditNoteId();
3400 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3404 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3407 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3409 elseif ($context == 'changePaymentInstrument') {
3410 if ($params['trxnParams']['total_amount'] < 0) {
3411 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3412 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3413 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3414 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3418 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3419 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3423 if ($context == 'changedStatus') {
3424 if (($previousContributionStatus == 'Pending'
3425 ||
$previousContributionStatus == 'In Progress')
3426 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3428 if (empty($params['line_item'])) {
3430 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3431 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3432 // & this can be removed
3435 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3436 $params['entity_id'] = $trxn->id
;
3437 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3438 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3440 $entityParams = array(
3441 'entity_table' => 'civicrm_financial_item',
3442 'financial_trxn_id' => $trxn->id
,
3444 foreach ($params['line_item'] as $fieldId => $fields) {
3445 foreach ($fields as $fieldValueId => $fieldValues) {
3447 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3448 2 => array($fieldValues['id'], 'Integer'),
3450 CRM_Core_DAO
::executeQuery($query, $fparams);
3452 1 => array($fieldValues['id'], 'Integer'),
3454 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3455 while ($financialItem->fetch()) {
3456 $entityParams['entity_id'] = $financialItem->id
;
3457 $entityParams['amount'] = $financialItem->amount
;
3458 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3466 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3467 $params['entity_id'] = $trxn->id
;
3468 if ($context != 'changePaymentInstrument') {
3469 $itemParams['entity_table'] = 'civicrm_line_item';
3470 $trxnIds['id'] = $params['entity_id'];
3471 foreach ($params['line_item'] as $fieldId => $fields) {
3472 foreach ($fields as $fieldValueId => $fieldValues) {
3473 $prevParams['entity_id'] = $fieldValues['id'];
3474 $prevFinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3476 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3477 if ($params['contribution']->receive_date
) {
3478 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3481 $financialAccount = self
::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
3483 $currency = $params['prevContribution']->currency
;
3484 if ($params['contribution']->currency
) {
3485 $currency = $params['contribution']->currency
;
3488 if ($context == 'changeFinancialType' || self
::isContributionStatusNegative($params['contribution']->contribution_status_id
)) {
3491 if (!empty($params['is_quick_config'])) {
3492 $amount = $itemAmount;
3494 $amount = $params['total_amount'];
3498 $amount = $diff * $fieldValues['line_total'];
3501 $itemParams = array(
3502 'transaction_date' => $receiveDate,
3503 'contact_id' => $params['prevContribution']->contact_id
,
3504 'currency' => $currency,
3505 'amount' => $amount,
3506 'description' => $prevFinancialItem->description
,
3507 'status_id' => $prevFinancialItem->status_id
,
3508 'financial_account_id' => $financialAccount,
3509 'entity_table' => 'civicrm_line_item',
3510 'entity_id' => $fieldValues['id'],
3512 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3514 if ($fieldValues['tax_amount']) {
3515 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3516 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3517 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3518 $itemParams['description'] = $taxTerm;
3519 if ($fieldValues['financial_type_id']) {
3520 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3522 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3527 if ($context == 'changeFinancialType') {
3528 $params['skipLineItem'] = FALSE;
3529 foreach ($params['line_item'] as &$lineItems) {
3530 foreach ($lineItems as &$line) {
3531 $line['financial_type_id'] = $params['financial_type_id'];
3538 * Is this contribution status a reversal.
3540 * If so we would expect to record a negative value in the financial_trxn table.
3542 * @param int $status_id
3546 public static function isContributionStatusNegative($status_id) {
3547 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3548 return in_array(CRM_Contribute_PseudoConstant
::contributionStatus($status_id, 'name'), $reversalStatuses);
3552 * Check status validation on update of a contribution.
3554 * @param array $values
3555 * Previous form values before submit.
3557 * @param array $fields
3558 * The input form values.
3560 * @param array $errors
3565 public static function checkStatusValidation($values, &$fields, &$errors) {
3566 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3567 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3568 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3572 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3573 $checkStatus = array(
3574 'Cancelled' => array('Completed', 'Refunded'),
3575 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
3576 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
3577 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3578 'Refunded' => array('Cancelled', 'Completed'),
3579 'Partially paid' => array('Completed'),
3582 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3583 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3585 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3586 1 => $contributionStatuses[$values['contribution_status_id']],
3587 2 => $contributionStatuses[$fields['contribution_status_id']],
3593 * Delete contribution of contact.
3597 * @param int $contactId
3601 public static function deleteContactContribution($contactId) {
3602 $contribution = new CRM_Contribute_DAO_Contribution();
3603 $contribution->contact_id
= $contactId;
3604 $contribution->find();
3605 while ($contribution->fetch()) {
3606 self
::deleteContribution($contribution->id
);
3611 * Get options for a given contribution field.
3612 * @see CRM_Core_DAO::buildOptions
3614 * @param string $fieldName
3615 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3616 * @param array $props whatever is known about this dao object.
3618 * @return array|bool
3620 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3621 $className = __CLASS__
;
3623 switch ($fieldName) {
3624 // This field is not part of this object but the api supports it
3625 case 'payment_processor':
3626 $className = 'CRM_Contribute_BAO_ContributionPage';
3627 // Filter results by contribution page
3628 if (!empty($props['contribution_page_id'])) {
3629 $page = civicrm_api('contribution_page', 'getsingle', array(
3631 'id' => ($props['contribution_page_id']),
3633 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3634 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3638 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3639 case 'honor_type_id':
3640 $className = 'CRM_Contribute_BAO_ContributionSoft';
3641 $fieldName = 'soft_credit_type_id';
3642 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3645 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3649 * Validate financial type.
3653 * @param int $financialTypeId
3654 * Financial Type id.
3656 * @param string $relationName
3658 * @return array|bool
3660 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3661 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3662 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3664 if (!$financialAccount) {
3665 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3672 * Function to record additional payment for partial and refund contributions.
3674 * @param int $contributionId
3675 * is the invoice contribution id (got created after processing participant payment).
3676 * @param array $trxnsData
3677 * to take user provided input of transaction details.
3678 * @param string $paymentType
3679 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3680 * @param int $participantId
3682 * @return null|object
3684 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3685 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3686 $getInfoOf['id'] = $contributionId;
3687 $defaults = array();
3688 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3689 if (!$participantId) {
3690 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3693 if ($paymentType == 'owed') {
3694 // build params for recording financial trxn entry
3695 $params['contribution'] = $contributionDAO;
3696 $params = array_merge($defaults, $params);
3697 $params['skipLineItem'] = TRUE;
3698 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3699 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3700 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3701 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3704 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3705 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3706 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3708 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3709 if (!empty($trxnId)) {
3710 $trxnId = $trxnId['trxn_id'];
3712 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3713 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3716 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3717 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3718 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3722 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3723 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3724 FROM civicrm_financial_trxn ft
3725 LEFT JOIN civicrm_entity_financial_trxn eft
3726 ON (ft.id = eft.financial_trxn_id)
3727 WHERE eft.entity_table = 'civicrm_contribution'
3728 AND eft.entity_id = {$contributionId}
3729 AND ft.to_financial_account_id != {$toFinancialAccount}
3730 AND ft.status_id = {$statusId}
3732 $query = CRM_Core_DAO
::executeQuery($sql);
3734 $sumOfPayments = $query->sum_of_payments
;
3737 if ($contributionDAO->total_amount
== $sumOfPayments) {
3738 // update contribution status and
3739 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3740 $contributionDAO->contribution_status_id
= $statusId;
3741 $contributionDAO->cancel_date
= 'null';
3742 $contributionDAO->cancel_reason
= NULL;
3743 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3744 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3745 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3746 $contributionDAO->save();
3748 //Change status of financial record too
3749 $financialTrxn->status_id
= $statusId;
3750 $financialTrxn->save();
3752 // note : not using the self::add method,
3753 // the reason because it performs 'status change' related code execution for financial records
3754 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3755 // are coded below i.e. just updating financial_item status to 'Paid'
3757 if ($participantId) {
3758 // update participant status
3759 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3760 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3761 foreach ($ids as $val) {
3762 $participantUpdate['id'] = $val;
3763 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3764 CRM_Event_BAO_Participant
::add($participantUpdate);
3768 // update financial item statuses
3769 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3770 $paidStatus = array_search('Paid', $financialItemStatus);
3772 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3773 $sqlFinancialItemUpdate = "
3774 UPDATE civicrm_financial_item fi
3775 LEFT JOIN civicrm_entity_financial_trxn eft
3776 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3777 SET status_id = {$paidStatus}
3778 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3780 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3783 elseif ($paymentType == 'refund') {
3784 // build params for recording financial trxn entry
3785 $params['contribution'] = $contributionDAO;
3786 $params = array_merge($defaults, $params);
3787 $params['skipLineItem'] = TRUE;
3788 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3789 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3791 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3792 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3793 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3795 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3797 // note : not using the self::add method,
3798 // the reason because it performs 'status change' related code execution for financial records
3799 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3800 // are coded below i.e. just updating financial_item status to 'Paid'
3801 if ($updateStatus) {
3802 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3804 // add financial item entry
3805 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3806 $getLine['entity_id'] = $contributionDAO->id
;
3807 $getLine['entity_table'] = 'civicrm_contribution';
3808 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3809 if (!empty($lineItemId->id
)) {
3810 $addFinancialEntry = array(
3811 'transaction_date' => $financialTrxn->trxn_date
,
3812 'contact_id' => $contributionDAO->contact_id
,
3813 'amount' => $financialTrxn->total_amount
,
3814 'status_id' => array_search('Paid', $financialItemStatus),
3815 'entity_id' => $lineItemId->id
,
3816 'entity_table' => 'civicrm_line_item',
3818 $trxnIds['id'] = $financialTrxn->id
;
3819 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3821 if ($participantId) {
3822 // update participant status
3823 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3824 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3825 foreach ($ids as $val) {
3826 $participantUpdate['id'] = $val;
3827 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3828 CRM_Event_BAO_Participant
::add($participantUpdate);
3833 // activity creation
3834 if (!empty($financialTrxn)) {
3835 if ($participantId) {
3836 $inputParams['id'] = $participantId;
3839 $component = 'event';
3840 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3841 $entityObj = $entityObj[$participantId];
3843 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3845 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3847 return $financialTrxn;
3853 * @param $activityType
3855 * @param int $contributionId
3857 * @throws CRM_Core_Exception
3859 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3860 if ($component == 'event') {
3861 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3862 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3863 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3864 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3865 $targetCid = $entityObj->contact_id
;
3866 // source record id would be the contribution id
3867 $srcRecId = $contributionId;
3871 $activityParams = array(
3872 'source_contact_id' => $targetCid,
3873 'source_record_id' => $srcRecId,
3874 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3878 'subject' => $subject,
3879 'activity_date_time' => $date,
3880 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3884 'skipRecentView' => TRUE,
3887 // create activity with target contacts
3888 $session = CRM_Core_Session
::singleton();
3889 $id = $session->get('userID');
3891 $activityParams['source_contact_id'] = $id;
3892 $activityParams['target_contact_id'][] = $targetCid;
3894 CRM_Activity_BAO_Activity
::create($activityParams);
3898 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3902 * @param bool $getTrxnInfo
3903 * @param bool $usingLineTotal
3907 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3908 if ($component == 'event') {
3909 $entity = 'participant';
3910 $entityTable = 'civicrm_participant';
3911 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3913 if (!$contributionId) {
3914 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3915 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3916 $id = $primaryParticipantId;
3918 if (!$contributionId) {
3924 $contributionId = $id;
3925 $entity = 'contribution';
3926 $entityTable = 'civicrm_contribution';
3929 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3930 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3936 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3937 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3940 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3941 // for additional participants
3942 if ($entityTable == 'civicrm_participant') {
3943 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3945 foreach ($ids as $val) {
3946 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3950 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3954 $baseTrxnId = $total['trxn_id'];
3955 $total = $total['total_amount'];
3958 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3959 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3961 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3962 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3963 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3965 if ($paymentBalance == 0 && $contributionIsPayLater) {
3966 $paymentBalance = $total;
3969 $info['total'] = $total;
3970 $info['paid'] = $total - $paymentBalance;
3971 $info['balance'] = $paymentBalance;
3973 $info['component'] = $component;
3974 $info['payLater'] = $contributionIsPayLater;
3976 if ($getTrxnInfo && $baseTrxnId) {
3977 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3979 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
3981 ft.payment_instrument_id,
3982 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3984 FROM civicrm_contribution con
3985 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3986 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
3987 AND ft.to_financial_account_id != {$feeFinancialAccount}
3988 INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
3989 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
3990 INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
3992 WHERE con.id = {$contributionId}
3996 // conditioned WHERE clause
3998 // if balance trxn exists don't include details of it in transaction info
3999 $sql .= " AND ft.id != {$baseTrxnId} ";
4001 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
4003 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
4005 while ($resultDAO->fetch()) {
4006 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4007 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
4009 'total_amount' => $resultDAO->total_amount
,
4010 'financial_type' => $resultDAO->financial_account
,
4011 'payment_instrument' => $paidByLabel,
4012 'receive_date' => $resultDAO->trxn_date
,
4013 'trxn_id' => $resultDAO->trxn_id
,
4014 'status' => $statuses[$resultDAO->status_id
],
4016 if ($paidByName == 'Check') {
4017 $val['check_number'] = $resultDAO->check_number
;
4021 $info['transaction'] = $rows;
4027 * Get financial account id has 'Sales Tax Account is'
4028 * account relationship with financial type
4030 * @param int $financialTypeId
4032 * @return FinancialAccountId
4034 public static function getFinancialAccountId($financialTypeId) {
4035 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4036 $searchParams = array(
4037 'entity_table' => 'civicrm_financial_type',
4038 'entity_id' => $financialTypeId,
4039 'account_relationship' => $accountRel,
4042 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4044 return CRM_Utils_Array
::value('financial_account_id', $result);
4050 * @param array $params
4051 * @param bool $isLineItem
4055 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4056 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4058 // Update contribution.
4059 if (!empty($params['id'])) {
4060 $id = $params['id'];
4061 $values = $ids = array();
4062 $contrbutionParams = array('id' => $id);
4063 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
4065 // To assign pervious finantial type on update of contribution
4066 if (!isset($params['financial_type_id'])) {
4067 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
4069 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4070 // Assisn tax Amount on update of contrbution
4071 if (!empty($prevContributionValue->tax_amount
)) {
4072 $params['tax_amount'] = 'null';
4073 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4074 foreach ($params['line_item'] as $setID => $priceField) {
4075 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4076 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4083 // New Contrbution and update of contribution with tax rate financial type
4084 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4085 empty($params['skipLineItem']) && !$isLineItem
4087 $taxRateParams = $taxRates[$params['financial_type_id']];
4088 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount(CRM_Utils_Array
::value('total_amount', $params), $taxRateParams);
4089 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4091 // Get Line Item on update of contribution
4092 if (isset($params['id'])) {
4093 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4096 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4098 foreach ($params['line_item'] as $setID => $priceField) {
4099 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4100 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4103 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $params) +
$params['tax_amount'];
4105 elseif (isset($params['api.line_item.create'])) {
4106 // Update total amount of contribution using lineItem
4107 $taxAmountArray = array();
4108 foreach ($params['api.line_item.create'] as $key => $value) {
4109 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4110 $taxRate = $taxRates[$value['financial_type_id']];
4111 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4112 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4115 $params['tax_amount'] = array_sum($taxAmountArray);
4116 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4119 // update line item of contrbution
4120 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4121 $taxRate = $taxRates[$params['financial_type_id']];
4122 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4123 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4130 * Check financial type validation on update of a contribution.
4132 * @param Integer $financialTypeId
4133 * Value of latest Financial Type.
4135 * @param Integer $contributionId
4138 * @param array $errors
4143 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4144 if (!empty($financialTypeId)) {
4145 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4146 if ($oldFinancialTypeId == $financialTypeId) {
4150 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4152 '1' => array($contributionId, 'Integer'),
4154 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4155 if ($result->N
> 1) {
4156 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
4161 * Update related pledge payment payments.
4163 * This function has been refactored out of the back office contribution form and may
4164 * still overlap with other functions.
4166 * @param string $action
4167 * @param int $pledgePaymentID
4168 * @param int $contributionID
4169 * @param bool $adjustTotalAmount
4170 * @param float $total_amount
4171 * @param float $original_total_amount
4172 * @param int $contribution_status_id
4173 * @param int $original_contribution_status_id
4175 public static function updateRelatedPledge(
4181 $original_total_amount,
4182 $contribution_status_id,
4183 $original_contribution_status_id
4185 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4189 if ($pledgePaymentID) {
4190 //store contribution id in payment record.
4191 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4194 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4201 if (!$pledgePaymentID) {
4204 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4210 $updatePledgePaymentStatus = FALSE;
4212 // If either the status or the amount has changed we update the pledge status.
4213 if ($action & CRM_Core_Action
::ADD
) {
4214 $updatePledgePaymentStatus = TRUE;
4216 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4217 ($original_total_amount != $total_amount))
4219 $updatePledgePaymentStatus = TRUE;
4222 if ($updatePledgePaymentStatus) {
4223 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4224 array($pledgePaymentID),
4225 $contribution_status_id,
4234 * Compute the stats values
4236 * @param $stat either 'mode' or 'median'
4238 * @param $alias of civicrm_contribution
4240 public static function computeStats($stat, $sql, $alias = NULL) {
4241 $mode = $median = array();
4244 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4245 while ($modeDAO->fetch()) {
4246 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4247 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4256 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4257 foreach ($currencies as $currency => $val) {
4259 $where = "AND {$alias}.currency = '{$currency}'";
4260 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4264 $medianRow = floor($rowCount / 2);
4265 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4271 $medianValue = "SELECT {$alias}.total_amount as median
4273 ORDER BY median LIMIT {$medianRow},{$offset}";
4274 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4275 while ($medianValDAO->fetch()) {
4277 $midValue = $midValue +
$medianValDAO->median
;
4280 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4284 $midValue = $midValue / 2;
4285 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4296 * Is there only one line item attached to the contribution.
4302 * @throws \CiviCRM_API3_Exception
4304 public static function isSingleLineItem($id) {
4305 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4306 return ($lineItemCount == 1);
4310 * Complete an order.
4312 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4314 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4316 * Moving it out of the BaseIPN class is just the first step.
4318 * @param array $input
4320 * @param array $objects
4321 * @param CRM_Core_Transaction $transaction
4323 * @param CRM_Contribute_BAO_Contribution $contribution
4324 * @param bool $isRecurring
4325 * Duplication of param needs review. Only used by AuthorizeNetIPN
4326 * @param int $isFirstOrLastRecurringPayment
4327 * Deprecated param only used by AuthorizeNetIPN.
4329 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4330 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4331 // The previous details are used when calculating line items so keep it before any code that 'does something'
4332 if (!empty($contribution->id
)) {
4333 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4334 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4336 $inputContributionWhiteList = array(
4341 'payment_instrument_id',
4347 if (self
::isSingleLineItem($primaryContributionID)) {
4348 $inputContributionWhiteList[] = 'financial_type_id';
4351 $participant = CRM_Utils_Array
::value('participant', $objects);
4352 $memberships = CRM_Utils_Array
::value('membership', $objects);
4353 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4354 $event = CRM_Utils_Array
::value('event', $objects);
4356 $contributionParams = array_merge(array(
4357 'contribution_status_id' => 'Completed',
4358 'source' => self
::getRecurringContributionDescription($contribution, $event),
4359 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4362 if (!empty($recurContrib->id
)) {
4363 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4365 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4367 if (empty($contributionParams['receive_date']) && $changeDate) {
4368 $contributionParams['receive_date'] = $changeDate;
4371 self
::repeatTransaction($contribution, $input, $contributionParams);
4372 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4374 if (is_numeric($memberships)) {
4375 $memberships = array($objects['membership']);
4379 if (isset($input['is_email_receipt'])) {
4380 $values['is_email_receipt'] = $input['is_email_receipt'];
4383 if ($input['component'] == 'contribute') {
4384 if ($contribution->contribution_page_id
) {
4385 // Figure out what we gain from this.
4386 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4388 elseif ($recurContrib && $recurContrib->id
) {
4389 $values['amount'] = $recurContrib->amount
;
4390 $values['financial_type_id'] = $objects['contributionType']->id
;
4391 $values['title'] = $source = ts('Offline Recurring Contribution');
4392 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4393 $values['receipt_from_name'] = $domainValues[0];
4394 $values['receipt_from_email'] = $domainValues[1];
4397 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4398 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4399 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4400 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4403 if (!empty($values['is_email_receipt'])) {
4404 $contributionParams['receipt_date'] = $changeDate;
4407 if (!empty($memberships)) {
4408 foreach ($memberships as $membershipTypeIdKey => $membership) {
4410 $membershipParams = array(
4411 'id' => $membership->id
,
4412 'contact_id' => $membership->contact_id
,
4413 'is_test' => $membership->is_test
,
4414 'membership_type_id' => $membership->membership_type_id
,
4417 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4418 $membershipParams['membership_type_id'],
4419 $membershipParams['is_test'],
4420 $membershipParams['id']
4423 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4424 // this picks up membership type changes during renewals
4426 SELECT membership_type_id
4427 FROM civicrm_membership_log
4428 WHERE membership_id={$membershipParams['id']}
4431 $dao = CRM_Core_DAO
::executeQuery($sql);
4432 if ($dao->fetch()) {
4433 if (!empty($dao->membership_type_id
)) {
4434 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4439 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4440 $membershipParams['membership_type_id'],
4441 $primaryContributionID
4443 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4444 if ($currentMembership) {
4446 * Fixed FOR CRM-4433
4447 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4448 * when Contribution mode is notify and membership is for renewal )
4450 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4452 // @todo - we should pass membership_type_id instead of null here but not
4453 // adding as not sure of testing
4454 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4455 $changeDate, NULL, $membershipParams['num_terms']
4458 $dates['join_date'] = $currentMembership['join_date'];
4461 //get the status for membership.
4462 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4464 $dates['join_date'],
4467 $membershipParams['membership_type_id'],
4471 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4472 //we might be renewing membership,
4473 //so make status override false.
4474 $membershipParams['is_override'] = FALSE;
4475 //CRM-17723 - reset static $relatedContactIds array()
4477 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4478 civicrm_api3('Membership', 'create', $membershipParams);
4484 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4485 if ($event->is_email_confirm
) {
4486 // @todo this should be set by the function that sends the mail after sending.
4487 $contributionParams['receipt_date'] = $changeDate;
4489 $participantParams['id'] = $participant->id
;
4490 $participantParams['status_id'] = 'Registered';
4491 civicrm_api3('Participant', 'create', $participantParams);
4495 $contributionParams['id'] = $contribution->id
;
4497 civicrm_api3('Contribution', 'create', $contributionParams);
4499 // Add new soft credit against current $contribution.
4500 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4501 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4504 $paymentProcessorId = '';
4505 if (isset($objects['paymentProcessor'])) {
4506 if (is_array($objects['paymentProcessor'])) {
4507 $paymentProcessorId = $objects['paymentProcessor']['id'];
4510 $paymentProcessorId = $objects['paymentProcessor']->id
;
4514 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4515 'labelColumn' => 'name',
4518 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4519 $input['payment_processor'] = $paymentProcessorId;
4522 if (!empty($contribution->_relatedObjects
['participant'])) {
4523 $input['contribution_mode'] = 'participant';
4524 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4525 $input['skipLineItem'] = 1;
4527 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4528 $input['skipLineItem'] = TRUE;
4529 $input['contribution_mode'] = 'membership';
4530 $contribution->contribution_status_id
= $contributionStatuses['Completed'];
4531 $contribution->trxn_id
= CRM_Utils_Array
::value('trxn_id', $input);
4532 $contribution->receive_date
= CRM_Utils_Date
::isoToMysql($contribution->receive_date
);
4534 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4535 $input['total_amount'] = $input['amount'];
4536 $input['contribution'] = $contribution;
4537 $input['financial_type_id'] = $contribution->financial_type_id
;
4538 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4539 // and subsequent payments. In this case the line items are created at
4540 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4541 // and since the contribution is saved prior to this line there is always a contribution-id,
4542 // however there is never a prevContribution (which appears to mean original contribution not previous
4543 // contribution - or preUpdateContributionObject most accurately)
4544 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4545 // to mean "are we updating an exisitng pending contribution"
4546 //I was able to make the unit test complete as fataling here doesn't prevent
4547 // the contribution being created - but activities would not be created or emails sent
4549 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4551 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4552 $transaction->commit();
4554 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4556 // create an activity record
4557 if ($input['component'] == 'contribute') {
4559 $targetContactID = NULL;
4560 if (!empty($ids['related_contact'])) {
4561 $targetContactID = $contribution->contact_id
;
4562 $contribution->contact_id
= $ids['related_contact'];
4564 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4568 CRM_Activity_BAO_Activity
::addActivity($participant);
4571 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4572 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4573 if (!array_key_exists('is_email_receipt', $values) ||
4574 $values['is_email_receipt'] == 1
4576 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4577 CRM_Core_Error
::debug_log_message("Receipt sent");
4580 CRM_Core_Error
::debug_log_message("Success: Database updated");
4582 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4583 $isFirstOrLastRecurringPayment);
4588 * Send receipt from contribution.
4590 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4592 * Note that the compose message part has been moved to contribution
4593 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4595 * @param array $input
4596 * Incoming data from Payment processor.
4598 * Related object IDs.
4599 * @param CRM_Contribute_BAO_Contribution $contribution
4600 * @param array $values
4601 * Values related to objects that have already been loaded.
4602 * @param bool $recur
4603 * Is it part of a recurring contribution.
4604 * @param bool $returnMessageText
4605 * Should text be returned instead of sent. This.
4606 * is because the function is also used to generate pdfs
4610 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4611 $input['is_recur'] = $recur;
4612 $input['receipt_date'] = $contribution->receipt_date
;
4613 // set receipt from e-mail and name in value
4614 if (!$returnMessageText) {
4615 $session = CRM_Core_Session
::singleton();
4616 $userID = $session->get('userID');
4617 if (!empty($userID)) {
4618 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4619 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4620 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4623 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4627 * Generate credit note id with next avaible number
4632 public static function createCreditNoteId() {
4633 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4635 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4636 $creditNoteId = NULL;
4640 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4641 $result = civicrm_api3('Contribution', 'getcount', array(
4643 'creditnote_id' => $creditNoteId,
4645 } while ($result > 0);
4647 return $creditNoteId;
4651 * Load related memberships.
4653 * Note that in theory it should be possible to retrieve these from the line_item table
4654 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4655 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4656 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4657 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4659 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4665 public function loadRelatedMembershipObjects(&$ids) {
4667 SELECT membership_id
4668 FROM civicrm_membership_payment
4669 WHERE contribution_id = %1 ";
4670 $params = array(1 => array($this->id
, 'Integer'));
4672 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4673 while ($dao->fetch()) {
4674 if ($dao->membership_id
) {
4675 if (!is_array($ids['membership'])) {
4676 $ids['membership'] = array();
4678 $ids['membership'][] = $dao->membership_id
;
4682 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4683 foreach ($ids['membership'] as $id) {
4685 $membership = new CRM_Member_BAO_Membership();
4686 $membership->id
= $id;
4687 if (!$membership->find(TRUE)) {
4688 throw new Exception("Could not find membership record: $id");
4690 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4691 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4692 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4693 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4694 $membership->free();
4701 * This function is used to record partial payments for contribution
4703 * @param array $contribution
4705 * @param array $params
4709 public static function recordPartialPayment($contribution, $params) {
4710 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4711 $pendingStatus = array(
4712 array_search('Pending', $contributionStatuses),
4713 array_search('In Progress', $contributionStatuses),
4715 $statusId = array_search('Completed', $contributionStatuses);
4716 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4717 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4718 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4720 elseif (!empty($params['payment_processor'])) {
4721 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4723 elseif (!empty($params['payment_instrument_id'])) {
4724 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4727 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4728 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4729 $balanceTrxnParams['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);
4731 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4732 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4733 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4734 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4735 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4736 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4737 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4738 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4739 $balanceTrxnParams['currency'] = $contribution['currency'];
4740 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4741 $balanceTrxnParams['status_id'] = $statusId;
4742 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4743 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4744 if ($fromFinancialAccountId != NULL &&
4745 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4747 $balanceTrxnParams['is_payment'] = 1;
4749 if (!empty($params['payment_processor'])) {
4750 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4752 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4756 * Get the description (source field) for the recurring contribution.
4758 * @param CRM_Contribute_BAO_Contribution $contribution
4759 * @param CRM_Event_DAO_Event|null $event
4762 * @throws \CiviCRM_API3_Exception
4764 protected static function getRecurringContributionDescription($contribution, $event) {
4765 if (!empty($contribution->contribution_page_id
)) {
4766 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4767 'id' => $contribution->contribution_page_id
,
4768 'return' => 'title',
4770 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4773 return ts('Online Event Registration') . ': ' . $event->title
;
4775 return 'recurring contribution';
4779 * Function to add payments for contribution
4780 * for Partially Paid status
4782 * @param array $lineItems
4783 * @param array $contributions
4786 public static function addPayments($lineItems, $contributions) {
4787 // get financial trxn which is a payment
4788 $ftSql = "SELECT ft.id
4789 FROM civicrm_financial_trxn ft
4790 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
4791 WHERE eft.entity_id = %1 AND ft.is_payment = 1";
4792 $sql = "SELECT fi.id, li.price_field_value_id
4793 FROM civicrm_financial_item fi
4794 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id
4795 WHERE li.contribution_id = %1";
4797 foreach ($contributions as $k => $contribution) {
4798 if ($contribution->contribution_status_id
!= CRM_Core_OptionGroup
::getValue('contribution_status', 'Partially paid', 'name')) {
4801 $ftId = CRM_Core_DAO
::singleValueQuery($ftSql, array(1 => array($contribution->id
, 'Integer')));
4802 // get financial item
4803 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($contribution->id
, 'Integer')));
4804 while ($dao->fetch()) {
4805 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4809 'entity_table' => 'civicrm_financial_item',
4810 'financial_trxn_id' => $ftId,
4812 foreach ($lineItems as $key => $value) {
4813 $paid = $value['line_total'] * ($contribution->net_amount
/ $contribution->total_amount
);
4814 // Record Entity Financial Trxn
4815 $params['amount'] = round($paid, 2);
4816 $params['entity_id'] = $ftIds[$value['price_field_value_id']];
4818 civicrm_api3('EntityFinancialTrxn', 'create', $params);
4824 * Function use to store line item proportionaly in
4825 * in entity financial trxn table
4827 * @param array $params
4828 * array of contribution params.
4829 * @param object $trxn
4830 * CRM_Financial_DAO_FinancialTrxn object
4831 * @param array $contribution
4834 public static function assignProportionalLineItems($params, $trxn, $contribution) {
4835 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
4836 if (!empty($lineItems)) {
4837 // get financial item
4838 $sql = "SELECT fi.id, li.price_field_value_id
4839 FROM civicrm_financial_item fi
4840 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
4841 WHERE li.contribution_id = %1";
4842 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($params['contribution_id'], 'Integer')));
4843 while ($dao->fetch()) {
4844 $ftIds[$dao->price_field_value_id
] = $dao->id
;
4847 'entity_table' => 'civicrm_financial_item',
4848 'financial_trxn_id' => $trxn->id
,
4850 foreach ($lineItems as $key => $value) {
4851 $paid = $value['line_total'] * ($params['total_amount'] / $contribution['total_amount']);
4852 // Record Entity Financial Trxn
4853 $eftParams['amount'] = round($paid, 2);
4854 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
4856 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
4862 * Function to check line items
4864 * @param array $params
4865 * array of order params.
4868 public static function checkLineItems(&$params) {
4869 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
4870 $lineItemAmount = 0;
4871 foreach ($params['line_items'] as &$lineItems) {
4872 foreach ($lineItems['line_item'] as &$item) {
4873 if (empty($item['financial_type_id'])) {
4874 $item['financial_type_id'] = $params['financial_type_id'];
4876 $lineItemAmount +
= $item['line_total'];
4879 if (!isset($totalAmount)) {
4880 $params['total_amount'] = $lineItemAmount;
4882 elseif ($totalAmount != $lineItemAmount) {
4883 throw new API_Exception("Line item total doesn't match with total amount.");
4888 * Get the financial account for the item associated with the new transaction.
4890 * @param array $params
4891 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
4895 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
4897 if (!empty($params['financial_account_id'])) {
4898 return $params['financial_account_id'];
4900 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus($params['contribution_status_id'], 'name');
4901 $preferredAccountsRelationships = array(
4902 'Refunded' => 'Credit/Contra Revenue Account is',
4903 'Chargeback' => 'Chargeback Account is',
4905 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4906 $financialTypeID = !empty($params['financial_type_id']) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
4907 return CRM_Financial_BAO_FinancialAccount
::getFinancialAccountForFinancialTypeByRelationship(
4909 $preferredAccountsRelationships[$contributionStatus]
4912 return $prevFinancialItem->financial_account_id
;