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');
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'),
813 $softCreditFields = array(
814 'contribution_soft_credit_name' => array(
815 'name' => 'contribution_soft_credit_name',
816 'title' => 'Soft Credit For',
817 'where' => 'civicrm_contact_d.display_name',
818 'data_type' => CRM_Utils_Type
::T_STRING
,
820 'contribution_soft_credit_amount' => array(
821 'name' => 'contribution_soft_credit_amount',
822 'title' => 'Soft Credit Amount',
823 'where' => 'civicrm_contribution_soft.amount',
824 'data_type' => CRM_Utils_Type
::T_MONEY
,
826 'contribution_soft_credit_type' => array(
827 'name' => 'contribution_soft_credit_type',
828 'title' => 'Soft Credit Type',
829 'where' => 'contribution_softcredit_type.label',
830 'data_type' => CRM_Utils_Type
::T_STRING
,
832 'contribution_soft_credit_contribution_id' => array(
833 'name' => 'contribution_soft_credit_contribution_id',
834 'title' => 'Soft Credit For Contribution ID',
835 'where' => 'civicrm_contribution_soft.contribution_id',
836 'data_type' => CRM_Utils_Type
::T_INT
,
838 'contribution_soft_credit_contact_id' => array(
839 'name' => 'contribution_soft_credit_contact_id',
840 'title' => 'Soft Credit For Contact ID',
841 'where' => 'civicrm_contact_d.id',
842 'data_type' => CRM_Utils_Type
::T_INT
,
846 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
848 'contribution_product_id' => array(
849 'title' => ts('Premium'),
850 'name' => 'contribution_product_id',
851 'where' => 'civicrm_product.id',
852 'data_type' => CRM_Utils_Type
::T_INT
,
856 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
857 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums,
858 CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
861 self
::$_exportableFields = $fields;
864 return self
::$_exportableFields;
868 * @param null $status
869 * @param null $startDate
870 * @param null $endDate
874 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
878 $where[] = 'contribution_status_id = 1';
882 $where[] = 'contribution_status_id = 3';
887 $where[] = "receive_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
890 $where[] = "receive_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
892 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
893 if ($financialTypes) {
894 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
895 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
898 $where[] = "c.financial_type_id IN (0)";
901 $whereCond = implode(' AND ', $where);
904 SELECT sum( total_amount ) as total_amount,
905 count( c.id ) as total_count,
907 FROM civicrm_contribution c
908 INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
909 LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
911 AND ( is_test = 0 OR is_test IS NULL )
912 AND contact.is_deleted = 0
916 $dao = CRM_Core_DAO
::executeQuery($query);
919 while ($dao->fetch()) {
920 $count +
= $dao->total_count
;
921 $amount[] = CRM_Utils_Money
::format($dao->total_amount
, $dao->currency
);
925 'amount' => implode(', ', $amount),
933 * Delete the indirect records associated with this contribution first.
938 * $results no of deleted Contribution on success, false otherwise
940 public static function deleteContribution($id) {
941 CRM_Utils_Hook
::pre('delete', 'Contribution', $id, CRM_Core_DAO
::$_nullArray);
943 $transaction = new CRM_Core_Transaction();
946 //delete activity record
948 'source_record_id' => $id,
949 // activity type id for contribution
950 'activity_type_id' => 6,
953 CRM_Activity_BAO_Activity
::deleteActivity($params);
955 //delete billing address if exists for this contribution.
956 self
::deleteAddress($id);
958 //update pledge and pledge payment, CRM-3961
959 CRM_Pledge_BAO_PledgePayment
::resetPledgePayment($id);
961 // remove entry from civicrm_price_set_entity, CRM-5095
962 if (CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution', $id)) {
963 CRM_Price_BAO_PriceSet
::removeFrom('civicrm_contribution', $id);
965 // cleanup line items.
966 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
968 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
969 CRM_Core_BAO_FinancialTrxn
::deleteFinancialTrxn($id);
971 if ($participantId) {
972 CRM_Price_BAO_LineItem
::deleteLineItems($participantId, 'civicrm_participant');
975 CRM_Price_BAO_LineItem
::deleteLineItems($id, 'civicrm_contribution');
979 $note = CRM_Core_BAO_Note
::getNote($id, 'civicrm_contribution');
980 $noteId = key($note);
982 CRM_Core_BAO_Note
::del($noteId, FALSE);
985 $dao = new CRM_Contribute_DAO_Contribution();
988 $results = $dao->delete();
990 $transaction->commit();
992 CRM_Utils_Hook
::post('delete', 'Contribution', $dao->id
, $dao);
994 // delete the recently created Contribution
995 $contributionRecent = array(
997 'type' => 'Contribution',
999 CRM_Utils_Recent
::del($contributionRecent);
1005 * React to a financial transaction (payment) failure.
1007 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1008 * payments is important for forensic and outreach reasons.
1010 * @param int $contributionID
1011 * @param int $contactID
1012 * @param string $message
1014 * @throws \CiviCRM_API3_Exception
1016 public static function failPayment($contributionID, $contactID, $message) {
1017 civicrm_api3('activity', 'create', array(
1018 'activity_type_id' => 'Failed Payment',
1019 'details' => $message,
1020 'subject' => ts('Payment failed at payment processor'),
1021 'source_record_id' => $contributionID,
1022 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1028 * Check if there is a contribution with the same trxn_id or invoice_id.
1030 * @param array $input
1031 * An assoc array of name/value pairs.
1032 * @param array $duplicates
1033 * (reference) store ids of duplicate contribs.
1037 * true if duplicate, false otherwise
1039 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
1041 $id = CRM_Utils_Array
::value('id', $input);
1043 $trxn_id = CRM_Utils_Array
::value('trxn_id', $input);
1044 $invoice_id = CRM_Utils_Array
::value('invoice_id', $input);
1050 $clause[] = "trxn_id = %1";
1051 $input[1] = array($trxn_id, 'String');
1055 $clause[] = "invoice_id = %2";
1056 $input[2] = array($invoice_id, 'String');
1059 if (empty($clause)) {
1063 $clause = implode(' OR ', $clause);
1065 $clause = "( $clause ) AND id != %3";
1066 $input[3] = array($id, 'Integer');
1069 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1070 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1072 while ($dao->fetch()) {
1073 $duplicates[] = $dao->id
;
1080 * Takes an associative array and creates a contribution_product object.
1082 * the function extract all the params it needs to initialize the create a
1083 * contribution_product object. the params array could contain additional unused name/value
1086 * @param array $params
1087 * (reference) an assoc array of name/value pairs.
1089 * @return CRM_Contribute_DAO_ContributionProduct
1091 public static function addPremium(&$params) {
1092 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1093 $contributionProduct->copyValues($params);
1094 return $contributionProduct->save();
1098 * Get list of contribution fields for profile.
1099 * For now we only allow custom contribution fields to be in
1102 * @param bool $addExtraFields
1103 * True if special fields needs to be added.
1106 * the list of contribution fields
1108 public static function getContributionFields($addExtraFields = TRUE) {
1109 $contributionFields = CRM_Contribute_DAO_Contribution
::export();
1110 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue
::getFields($mode = 'contribute'));
1112 if ($addExtraFields) {
1113 $contributionFields = array_merge($contributionFields, self
::getSpecialContributionFields());
1116 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType
::export());
1118 foreach ($contributionFields as $key => $var) {
1119 if ($key == 'contribution_contact_id') {
1122 elseif ($key == 'contribution_campaign_id') {
1123 $var['title'] = ts('Campaign');
1125 $fields[$key] = $var;
1128 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Contribution'));
1133 * Add extra fields specific to contribution.
1135 public static function getSpecialContributionFields() {
1136 $extraFields = array(
1137 'contribution_soft_credit_name' => array(
1138 'name' => 'contribution_soft_credit_name',
1139 'title' => 'Soft Credit Name',
1140 'headerPattern' => '/^soft_credit_name$/i',
1141 'where' => 'civicrm_contact_d.display_name',
1143 'contribution_soft_credit_email' => array(
1144 'name' => 'contribution_soft_credit_email',
1145 'title' => 'Soft Credit Email',
1146 'headerPattern' => '/^soft_credit_email$/i',
1147 'where' => 'soft_email.email',
1149 'contribution_soft_credit_phone' => array(
1150 'name' => 'contribution_soft_credit_phone',
1151 'title' => 'Soft Credit Phone',
1152 'headerPattern' => '/^soft_credit_phone$/i',
1153 'where' => 'soft_phone.phone',
1155 'contribution_soft_credit_contact_id' => array(
1156 'name' => 'contribution_soft_credit_contact_id',
1157 'title' => 'Soft Credit Contact ID',
1158 'headerPattern' => '/^soft_credit_contact_id$/i',
1159 'where' => 'civicrm_contribution_soft.contact_id',
1161 'contribution_pcp_title' => array(
1162 'name' => 'contribution_pcp_title',
1163 'title' => 'Personal Campaign Page Title',
1164 'headerPattern' => '/^contribution_pcp_title$/i',
1165 'where' => 'contribution_pcp.title',
1169 return $extraFields;
1173 * @param int $pageID
1177 public static function getCurrentandGoalAmount($pageID) {
1179 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1180 FROM civicrm_contribution_page p,
1181 civicrm_contribution c
1182 WHERE p.id = c.contribution_page_id
1184 AND c.cancel_date is null
1188 $config = CRM_Core_Config
::singleton();
1189 $params = array(1 => array($pageID, 'Integer'));
1190 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1192 if ($dao->fetch()) {
1193 return array($dao->goal
, $dao->total
);
1196 return array(NULL, NULL);
1201 * Get list of contribution In Honor of contact Ids.
1203 * @param int $honorId
1204 * In Honor of Contact ID.
1207 * list of contribution fields
1209 public static function getHonorContacts($honorId) {
1211 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1212 $honorDAO->contact_id
= $honorId;
1215 $type = CRM_Contribute_PseudoConstant
::financialType();
1217 while ($honorDAO->fetch()) {
1218 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1219 $contributionDAO->id
= $honorDAO->contribution_id
;
1221 if ($contributionDAO->find(TRUE)) {
1222 $params[$contributionDAO->id
]['honor_type'] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
);
1223 $params[$contributionDAO->id
]['honorId'] = $contributionDAO->contact_id
;
1224 $params[$contributionDAO->id
]['display_name'] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id
, 'display_name');
1225 $params[$contributionDAO->id
]['type'] = $type[$contributionDAO->financial_type_id
];
1226 $params[$contributionDAO->id
]['type_id'] = $contributionDAO->financial_type_id
;
1227 $params[$contributionDAO->id
]['amount'] = CRM_Utils_Money
::format($contributionDAO->total_amount
, $contributionDAO->currency
);
1228 $params[$contributionDAO->id
]['source'] = $contributionDAO->source
;
1229 $params[$contributionDAO->id
]['receive_date'] = $contributionDAO->receive_date
;
1230 $params[$contributionDAO->id
]['contribution_status'] = CRM_Contribute_PseudoConstant
::contributionStatus($contributionDAO->contribution_status_id
);
1238 * Get the sort name of a contact for a particular contribution.
1241 * Id of the contribution.
1243 * @return null|string
1244 * sort name of the contact if found
1246 public static function sortName($id) {
1247 $id = CRM_Utils_Type
::escape($id, 'Integer');
1250 SELECT civicrm_contact.sort_name
1251 FROM civicrm_contribution, civicrm_contact
1252 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1253 AND civicrm_contribution.id = {$id}
1255 return CRM_Core_DAO
::singleValueQuery($query);
1259 * @param int $contactID
1263 public static function annual($contactID) {
1264 if (is_array($contactID)) {
1265 $contactIDs = implode(',', $contactID);
1268 $contactIDs = $contactID;
1271 $config = CRM_Core_Config
::singleton();
1272 $startDate = $endDate = NULL;
1274 $currentMonth = date('m');
1275 $currentDay = date('d');
1276 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
1277 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
1278 (int ) $config->fiscalYearStart
['d'] > $currentDay
1281 $year = date('Y') - 1;
1286 $nextYear = $year +
1;
1288 if ($config->fiscalYearStart
) {
1289 $newFiscalYearStart = $config->fiscalYearStart
;
1290 if ($newFiscalYearStart['M'] < 10) {
1291 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
1293 if ($newFiscalYearStart['d'] < 10) {
1294 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
1296 $config->fiscalYearStart
= $newFiscalYearStart;
1297 $monthDay = $config->fiscalYearStart
['M'] . $config->fiscalYearStart
['d'];
1302 $startDate = "$year$monthDay";
1303 $endDate = "$nextYear$monthDay";
1304 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
1305 $additionalWhere = " AND b.financial_type_id IN (0)";
1306 $liWhere = " AND i.financial_type_id IN (0)";
1307 if (!empty($financialTypes)) {
1308 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1309 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
1312 SELECT count(*) as count,
1313 sum(total_amount) as amount,
1314 avg(total_amount) as average,
1316 FROM civicrm_contribution b
1317 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
1318 WHERE b.contact_id IN ( $contactIDs )
1319 AND b.contribution_status_id = 1
1321 AND b.receive_date >= $startDate
1322 AND b.receive_date < $endDate
1326 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1328 $amount = $average = array();
1329 while ($dao->fetch()) {
1330 if ($dao->count
> 0 && $dao->amount
> 0) {
1331 $count +
= $dao->count
;
1332 $amount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
1333 $average[] = CRM_Utils_Money
::format($dao->average
, $dao->currency
);
1339 implode(', ', $amount),
1340 implode(', ', $average),
1343 return array(0, 0, 0);
1347 * Check if there is a contribution with the params passed in.
1349 * Used for trxn_id,invoice_id and contribution_id
1351 * @param array $params
1352 * An assoc array of name/value pairs.
1355 * contribution id if success else NULL
1357 public static function checkDuplicateIds($params) {
1358 $dao = new CRM_Contribute_DAO_Contribution();
1362 foreach ($params as $k => $v) {
1364 $clause[] = "$k = '$v'";
1367 $clause = implode(' AND ', $clause);
1368 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1369 $dao = CRM_Core_DAO
::executeQuery($query, $input);
1371 while ($dao->fetch()) {
1379 * Get the contribution details for component export.
1381 * @param int $exportMode
1383 * @param string $componentIds
1389 public static function getContributionDetails($exportMode, $componentIds) {
1390 $paymentDetails = array();
1391 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1393 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
1394 $componentSelect = " civicrm_participant_payment.participant_id id";
1395 $additionalClause = "
1396 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1397 AND civicrm_participant_payment.participant_id {$componentClause} )
1400 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
1401 $componentSelect = " civicrm_membership_payment.membership_id id";
1402 $additionalClause = "
1403 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1404 AND civicrm_membership_payment.membership_id {$componentClause} )
1407 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
1408 $componentSelect = " civicrm_pledge_payment.id id";
1409 $additionalClause = "
1410 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1411 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1415 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1416 trxn_id, {$componentSelect}
1417 FROM civicrm_contribution
1418 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1419 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1420 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1421 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1422 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1423 AND option_group_contribution_status.id = contribution_status.option_group_id )
1427 $dao = CRM_Core_DAO
::executeQuery($query);
1429 while ($dao->fetch()) {
1430 $paymentDetails[$dao->id
] = array(
1431 'total_amount' => $dao->total_amount
,
1432 'contribution_status' => $dao->status
,
1433 'receive_date' => $dao->receive_date
,
1434 'pay_instru' => $dao->payment_instrument
,
1435 'trxn_id' => $dao->trxn_id
,
1439 return $paymentDetails;
1443 * Create address associated with contribution record.
1445 * As long as there is one or more billing field in the parameters we will create the address.
1447 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1450 * @param array $params
1451 * @param int $billingLocationTypeID
1456 public static function createAddress($params, $billingLocationTypeID) {
1457 list($hasBillingField, $addressParams) = self
::getBillingAddressParams($params, $billingLocationTypeID);
1458 if ($hasBillingField) {
1459 $address = CRM_Core_BAO_Address
::add($addressParams, FALSE);
1460 return $address->id
;
1467 * Delete billing address record related contribution.
1469 * @param int $contributionId
1470 * @param int $contactId
1472 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1474 $contactJoin = NULL;
1476 if ($contributionId) {
1477 $clauses[] = "cc.id = {$contributionId}";
1481 $clauses[] = "cco.id = {$contactId}";
1482 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1485 if (empty($clauses)) {
1486 CRM_Core_Error
::fatal();
1489 $condition = implode(' OR ', $clauses);
1493 FROM civicrm_address ca
1494 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1498 $dao = CRM_Core_DAO
::executeQuery($query);
1500 while ($dao->fetch()) {
1501 $params = array('id' => $dao->id
);
1502 CRM_Core_BAO_Block
::blockDelete('Address', $params);
1507 * This function check online pending contribution associated w/
1508 * Online Event Registration or Online Membership signup.
1510 * @param int $componentId
1511 * Participant/membership id.
1512 * @param string $componentName
1516 * pending contribution id.
1518 public static function checkOnlinePendingContribution($componentId, $componentName) {
1519 $contributionId = NULL;
1520 if (!$componentId ||
1521 !in_array($componentName, array('Event', 'Membership'))
1523 return $contributionId;
1526 if ($componentName == 'Event') {
1527 $idName = 'participant_id';
1528 $componentTable = 'civicrm_participant';
1529 $paymentTable = 'civicrm_participant_payment';
1530 $source = ts('Online Event Registration');
1533 if ($componentName == 'Membership') {
1534 $idName = 'membership_id';
1535 $componentTable = 'civicrm_membership';
1536 $paymentTable = 'civicrm_membership_payment';
1537 $source = ts('Online Contribution');
1540 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
1543 SELECT component.id as {$idName},
1544 componentPayment.contribution_id as contribution_id,
1545 contribution.source source,
1546 contribution.contribution_status_id as contribution_status_id,
1547 contribution.is_pay_later as is_pay_later
1548 FROM $componentTable component
1549 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1550 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1551 WHERE component.id = {$componentId}";
1553 $dao = CRM_Core_DAO
::executeQuery($query);
1555 while ($dao->fetch()) {
1556 if ($dao->contribution_id
&&
1557 $dao->is_pay_later
&&
1558 $dao->contribution_status_id
== $pendingStatusId &&
1559 strpos($dao->source
, $source) !== FALSE
1561 $contributionId = $dao->contribution_id
;
1566 return $contributionId;
1570 * Update contribution as well as related objects.
1572 * This function by-passes hooks - to address this - don't use this function.
1576 * Use api contribute.completetransaction
1577 * For failures use failPayment (preferably exposing by api in the process).
1579 * @param array $params
1580 * @param bool $processContributionObject
1583 * @throws \Exception
1585 public static function transitionComponents($params, $processContributionObject = FALSE) {
1586 // get minimum required values.
1587 $contactId = CRM_Utils_Array
::value('contact_id', $params);
1588 $componentId = CRM_Utils_Array
::value('component_id', $params);
1589 $componentName = CRM_Utils_Array
::value('componentName', $params);
1590 $contributionId = CRM_Utils_Array
::value('contribution_id', $params);
1591 $contributionStatusId = CRM_Utils_Array
::value('contribution_status_id', $params);
1593 // if we already processed contribution object pass previous status id.
1594 $previousContriStatusId = CRM_Utils_Array
::value('previous_contribution_status_id', $params);
1596 $updateResult = array();
1598 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1600 // we process only ( Completed, Cancelled, or Failed ) contributions.
1601 if (!$contributionId ||
1602 !in_array($contributionStatusId, array(
1603 array_search('Completed', $contributionStatuses),
1604 array_search('Cancelled', $contributionStatuses),
1605 array_search('Failed', $contributionStatuses),
1608 return $updateResult;
1611 if (!$componentName ||
!$componentId) {
1612 // get the related component details.
1613 $componentDetails = self
::getComponentDetails($contributionId);
1616 $componentDetails['contact_id'] = $contactId;
1617 $componentDetails['component'] = $componentName;
1619 if ($componentName == 'event') {
1620 $componentDetails['participant'] = $componentId;
1623 $componentDetails['membership'] = $componentId;
1627 if (!empty($componentDetails['contact_id'])) {
1628 $componentDetails['contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
1634 // do check for required ids.
1635 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) ||
empty($componentDetails['contact_id'])) {
1636 return $updateResult;
1639 //now we are ready w/ required ids, start processing.
1641 $baseIPN = new CRM_Core_Payment_BaseIPN();
1643 $input = $ids = $objects = array();
1645 $input['component'] = CRM_Utils_Array
::value('component', $componentDetails);
1646 $ids['contribution'] = $contributionId;
1647 $ids['contact'] = CRM_Utils_Array
::value('contact_id', $componentDetails);
1648 $ids['membership'] = CRM_Utils_Array
::value('membership', $componentDetails);
1649 $ids['participant'] = CRM_Utils_Array
::value('participant', $componentDetails);
1650 $ids['event'] = CRM_Utils_Array
::value('event', $componentDetails);
1651 $ids['pledge_payment'] = CRM_Utils_Array
::value('pledge_payment', $componentDetails);
1652 $ids['contributionRecur'] = NULL;
1653 $ids['contributionPage'] = NULL;
1655 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1656 CRM_Core_Error
::fatal();
1659 $memberships = &$objects['membership'];
1660 $participant = &$objects['participant'];
1661 $pledgePayment = &$objects['pledge_payment'];
1662 $contribution = &$objects['contribution'];
1664 if ($pledgePayment) {
1665 $pledgePaymentIDs = array();
1666 foreach ($pledgePayment as $key => $object) {
1667 $pledgePaymentIDs[] = $object->id
;
1669 $pledgeID = $pledgePayment[0]->pledge_id
;
1672 $membershipStatuses = CRM_Member_PseudoConstant
::membershipStatus();
1675 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
1676 $oldStatus = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant',
1681 // we might want to process contribution object.
1682 $processContribution = FALSE;
1683 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1684 if (is_array($memberships)) {
1685 foreach ($memberships as $membership) {
1687 $membership->status_id
= array_search('Cancelled', $membershipStatuses);
1688 $membership->save();
1690 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1691 if ($processContributionObject) {
1692 $processContribution = TRUE;
1699 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1700 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1702 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1703 if ($processContributionObject) {
1704 $processContribution = TRUE;
1708 if ($pledgePayment) {
1709 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1711 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1712 if ($processContributionObject) {
1713 $processContribution = TRUE;
1717 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1718 if (is_array($memberships)) {
1719 foreach ($memberships as $membership) {
1721 $membership->status_id
= array_search('Expired', $membershipStatuses);
1722 $membership->save();
1724 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1725 if ($processContributionObject) {
1726 $processContribution = TRUE;
1732 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1733 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1735 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1736 if ($processContributionObject) {
1737 $processContribution = TRUE;
1741 if ($pledgePayment) {
1742 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1744 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1745 if ($processContributionObject) {
1746 $processContribution = TRUE;
1750 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1752 // only pending contribution related object processed.
1753 if ($previousContriStatusId &&
1754 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1756 // this is case when we already processed contribution object.
1757 return $updateResult;
1759 elseif (!$previousContriStatusId &&
1760 $contribution->contribution_status_id
!= array_search('Pending', $contributionStatuses)
1762 // this is case when we are going to process contribution object later.
1763 return $updateResult;
1766 if (is_array($memberships)) {
1767 foreach ($memberships as $membership) {
1772 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membership->contact_id
,
1773 $membership->membership_type_id
,
1774 $membership->is_test
, $membership->id
1777 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1778 // this picks up membership type changes during renewals
1780 SELECT membership_type_id
1781 FROM civicrm_membership_log
1782 WHERE membership_id=$membership->id
1785 $dao = new CRM_Core_DAO();
1787 if ($dao->fetch()) {
1788 if (!empty($dao->membership_type_id
)) {
1789 $membership->membership_type_id
= $dao->membership_type_id
;
1790 $membership->save();
1793 // else fall back to using current membership type
1796 // Figure out number of terms
1798 $lineitems = CRM_Price_BAO_LineItem
::getLineItems($contributionId, 'contribution');
1799 foreach ($lineitems as $lineitem) {
1800 if ($membership->membership_type_id
== CRM_Utils_Array
::value('membership_type_id', $lineitem)) {
1801 $numterms = CRM_Utils_Array
::value('membership_num_terms', $lineitem);
1803 // in case membership_num_terms comes through as null or zero
1804 $numterms = $numterms >= 1 ?
$numterms : 1;
1809 // CRM-15735-to update the membership status as per the contribution receive date
1811 if (!empty($params['receive_date'])) {
1812 $joinDate = $params['receive_date'];
1813 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($membership->start_date
,
1814 $membership->end_date
,
1815 $membership->join_date
,
1816 $params['receive_date'],
1818 $membership->membership_type_id
,
1821 $membership->status_id
= CRM_Utils_Array
::value('id', $status, $membership->status_id
);
1822 $membership->save();
1825 if ($currentMembership) {
1826 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1827 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
, NULL, NULL, $numterms);
1828 $dates['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1831 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membership->membership_type_id
, $joinDate, NULL, NULL, $numterms);
1834 //get the status for membership.
1835 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
1837 $dates['join_date'],
1840 $membership->membership_type_id
,
1844 $formattedParams = array(
1845 'status_id' => CRM_Utils_Array
::value('id', $calcStatus,
1846 array_search('Current', $membershipStatuses)
1848 'join_date' => CRM_Utils_Date
::customFormat($dates['join_date'], $format),
1849 'start_date' => CRM_Utils_Date
::customFormat($dates['start_date'], $format),
1850 'end_date' => CRM_Utils_Date
::customFormat($dates['end_date'], $format),
1853 CRM_Utils_Hook
::pre('edit', 'Membership', $membership->id
, $formattedParams);
1855 $membership->copyValues($formattedParams);
1856 $membership->save();
1858 //updating the membership log
1859 $membershipLog = array();
1860 $membershipLog = $formattedParams;
1861 $logStartDate = CRM_Utils_Date
::customFormat(CRM_Utils_Array
::value('log_start_date', $dates), $format);
1862 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : $formattedParams['start_date'];
1864 $membershipLog['start_date'] = $logStartDate;
1865 $membershipLog['membership_id'] = $membership->id
;
1866 $membershipLog['modified_id'] = $membership->contact_id
;
1867 $membershipLog['modified_date'] = date('Ymd');
1868 $membershipLog['membership_type_id'] = $membership->membership_type_id
;
1870 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
1872 //update related Memberships.
1873 CRM_Member_BAO_Membership
::updateRelatedMemberships($membership->id
, $formattedParams);
1875 $updateResult['membership_end_date'] = CRM_Utils_Date
::customFormat($dates['end_date'],
1878 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id
;
1879 if ($processContributionObject) {
1880 $processContribution = TRUE;
1883 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
1889 $updatedStatusId = array_search('Registered', $participantStatuses);
1890 CRM_Event_BAO_Participant
::updateParticipantStatus($participant->id
, $oldStatus, $updatedStatusId, TRUE);
1892 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1893 if ($processContributionObject) {
1894 $processContribution = TRUE;
1898 if ($pledgePayment) {
1899 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1901 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1902 if ($processContributionObject) {
1903 $processContribution = TRUE;
1908 // process contribution object.
1909 if ($processContribution) {
1910 $contributionParams = array();
1917 'payment_instrument_id',
1920 'financial_type_id',
1921 'contribution_status_id',
1922 'non_deductible_amount',
1926 foreach ($fields as $field) {
1927 if (empty($params[$field])) {
1930 $contributionParams[$field] = $params[$field];
1933 $ids = array('contribution' => $contributionId);
1934 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
1937 return $updateResult;
1941 * Returns all contribution related object ids.
1943 * @param $contributionId
1947 public static function getComponentDetails($contributionId) {
1948 $componentDetails = $pledgePayment = array();
1949 if (!$contributionId) {
1950 return $componentDetails;
1954 SELECT c.id as contribution_id,
1955 c.contact_id as contact_id,
1956 c.contribution_recur_id,
1957 mp.membership_id as membership_id,
1958 m.membership_type_id as membership_type_id,
1959 pp.participant_id as participant_id,
1960 p.event_id as event_id,
1961 pgp.id as pledge_payment_id
1962 FROM civicrm_contribution c
1963 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1964 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1965 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1966 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1967 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1968 WHERE c.id = $contributionId";
1970 $dao = CRM_Core_DAO
::executeQuery($query);
1971 $componentDetails = array();
1973 while ($dao->fetch()) {
1974 $componentDetails['component'] = $dao->participant_id ?
'event' : 'contribute';
1975 $componentDetails['contact_id'] = $dao->contact_id
;
1976 if ($dao->event_id
) {
1977 $componentDetails['event'] = $dao->event_id
;
1979 if ($dao->participant_id
) {
1980 $componentDetails['participant'] = $dao->participant_id
;
1982 if ($dao->membership_id
) {
1983 if (!isset($componentDetails['membership'])) {
1984 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1986 $componentDetails['membership'][] = $dao->membership_id
;
1987 $componentDetails['membership_type'][] = $dao->membership_type_id
;
1989 if ($dao->pledge_payment_id
) {
1990 $pledgePayment[] = $dao->pledge_payment_id
;
1992 if ($dao->contribution_recur_id
) {
1993 $componentDetails['contributionRecur'] = $dao->contribution_recur_id
;
1997 if ($pledgePayment) {
1998 $componentDetails['pledge_payment'] = $pledgePayment;
2001 return $componentDetails;
2005 * @param int $contactId
2006 * @param bool $includeSoftCredit
2008 * @return null|string
2010 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2014 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes);
2015 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2016 $liWhere = " AND i.financial_type_id IN (0)";
2017 if (!empty($financialTypes)) {
2018 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2019 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2021 $contactContributionsSQL = "
2022 SELECT contribution.id AS id
2023 FROM civicrm_contribution contribution
2024 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2025 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2029 $contactSoftCreditContributionsSQL = "
2030 SELECT contribution.id
2031 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2032 ON ( contribution.id = softContribution.contribution_id )
2033 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2034 $query = "SELECT count( x.id ) count FROM ( ";
2035 $query .= $contactContributionsSQL;
2037 if ($includeSoftCredit) {
2038 $query .= " UNION ";
2039 $query .= $contactSoftCreditContributionsSQL;
2044 return CRM_Core_DAO
::singleValueQuery($query);
2048 * Repeat a transaction as part of a recurring series.
2050 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2051 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2052 * subsequent call to the contribution.completetransaction api.
2054 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2056 * @param CRM_Contribute_BAO_Contribution $contribution
2057 * @param array $input
2058 * @param array $contributionParams
2062 protected static function repeatTransaction(&$contribution, &$input, $contributionParams) {
2063 if (!empty($contribution->id
)) {
2066 if (empty($contribution->id
)) {
2067 // Unclear why this would only be set for repeats.
2068 if (!empty($input['amount'])) {
2069 $contribution->total_amount
= $contributionParams['total_amount'] = $input['amount'];
2071 $templateContribution = CRM_Contribute_BAO_ContributionRecur
::getTemplateContribution($contributionParams['contribution_recur_id']);
2072 if (!empty($contributionParams['contribution_recur_id'])) {
2073 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2074 'id' => $contributionParams['contribution_recur_id'],
2076 if (!empty($recurringContribution['campaign_id'])) {
2077 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2078 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2080 if (!empty($recurringContribution['financial_type_id'])) {
2081 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2082 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2085 $contributionParams['skipLineItem'] = TRUE;
2086 $contributionParams['status_id'] = 'Pending';
2087 if (isset($contributionParams['financial_type_id'])) {
2088 // Give precedence to passed in type.
2089 $contribution->financial_type_id
= $contributionParams['financial_type_id'];
2092 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2094 $contributionParams['contact_id'] = $templateContribution['contact_id'];
2095 $contributionParams['source'] = empty($templateContribution['source']) ?
ts('Recurring contribution') : $templateContribution['source'];
2096 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2097 $contribution->id
= $createContribution['id'];
2098 $input['line_item'] = CRM_Contribute_BAO_ContributionRecur
::addRecurLineItems($contribution->contribution_recur_id
, $contribution);
2099 CRM_Contribute_BAO_ContributionRecur
::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id
);
2105 * Get individual id for onbehalf contribution.
2107 * @param int $contributionId
2109 * @param int $contributorId
2113 * containing organization id and individual id
2115 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2119 if (!$contributionId) {
2123 // fetch contributor id if null
2124 if (!$contributorId) {
2125 $contributorId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution',
2126 $contributionId, 'contact_id'
2130 $activityTypeIds = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2131 $activityTypeId = array_search('Contribution', $activityTypeIds);
2133 if ($activityTypeId && $contributorId) {
2135 SELECT civicrm_activity_contact.contact_id
2136 FROM civicrm_activity_contact
2137 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2138 WHERE civicrm_activity.activity_type_id = %1
2139 AND civicrm_activity.source_record_id = %2
2140 AND civicrm_activity_contact.record_type_id = %3
2143 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2144 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2147 1 => array($activityTypeId, 'Integer'),
2148 2 => array($contributionId, 'Integer'),
2149 3 => array($sourceID, 'Integer'),
2152 $sourceContactId = CRM_Core_DAO
::singleValueQuery($activityQuery, $params);
2154 // for on behalf contribution source is individual and contributor is organization
2155 if ($sourceContactId && $sourceContactId != $contributorId) {
2156 $relationshipTypeIds = CRM_Core_PseudoConstant
::relationshipType('name');
2157 // get rel type id for employee of relation
2158 foreach ($relationshipTypeIds as $id => $typeVals) {
2159 if ($typeVals['name_a_b'] == 'Employee of') {
2160 $relationshipTypeId = $id;
2165 $rel = new CRM_Contact_DAO_Relationship();
2166 $rel->relationship_type_id
= $relationshipTypeId;
2167 $rel->contact_id_a
= $sourceContactId;
2168 $rel->contact_id_b
= $contributorId;
2169 if ($rel->find(TRUE)) {
2170 $ids['individual_id'] = $rel->contact_id_a
;
2171 $ids['organization_id'] = $rel->contact_id_b
;
2182 public static function getContributionDates() {
2183 $config = CRM_Core_Config
::singleton();
2184 $currentMonth = date('m');
2185 $currentDay = date('d');
2186 if ((int ) $config->fiscalYearStart
['M'] > $currentMonth ||
2187 ((int ) $config->fiscalYearStart
['M'] == $currentMonth &&
2188 (int ) $config->fiscalYearStart
['d'] > $currentDay
2191 $year = date('Y') - 1;
2196 $year = array('Y' => $year);
2197 $yearDate = $config->fiscalYearStart
;
2198 $yearDate = array_merge($year, $yearDate);
2199 $yearDate = CRM_Utils_Date
::format($yearDate);
2201 $monthDate = date('Ym') . '01';
2207 'yearDate' => $yearDate,
2208 'monthDate' => $monthDate,
2213 * Load objects relations to contribution object.
2214 * Objects are stored in the $_relatedObjects property
2215 * In the first instance we are just moving functionality from BASEIpn -
2216 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2218 * Note that the unit test for the BaseIPN class tests this function
2220 * @param array $input
2221 * Input as delivered from Payment Processor.
2223 * Ids as Loaded by Payment Processor.
2224 * @param bool $loadAll
2225 * Load all related objects - even where id not passed in? (allows API to call this).
2230 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
2232 $ids = array_merge($this->getComponentDetails($this->id
), $ids);
2233 if (empty($ids['contact']) && isset($this->contact_id
)) {
2234 $ids['contact'] = $this->contact_id
;
2237 if (empty($this->_component
)) {
2238 if (!empty($ids['event'])) {
2239 $this->_component
= 'event';
2242 $this->_component
= strtolower(CRM_Utils_Array
::value('component', $input, 'contribute'));
2246 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2247 // refactoring than anything else, and has unit test coverage.
2248 if (empty($this->financial_type_id
)) {
2252 $paymentProcessorID = CRM_Utils_Array
::value('payment_processor_id', $input, CRM_Utils_Array
::value(
2257 if (!$paymentProcessorID && $this->contribution_page_id
) {
2258 $paymentProcessorID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2259 $this->contribution_page_id
,
2262 if ($paymentProcessorID) {
2263 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2267 $ids['contributionType'] = $this->financial_type_id
;
2268 $ids['financialType'] = $this->financial_type_id
;
2271 'contact' => 'CRM_Contact_BAO_Contact',
2272 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
2273 'contributionType' => 'CRM_Financial_BAO_FinancialType',
2274 'financialType' => 'CRM_Financial_BAO_FinancialType',
2276 foreach ($entities as $entity => $bao) {
2277 if (!empty($ids[$entity])) {
2278 $this->_relatedObjects
[$entity] = new $bao();
2279 $this->_relatedObjects
[$entity]->id
= $ids[$entity];
2280 if (!$this->_relatedObjects
[$entity]->find(TRUE)) {
2281 throw new CRM_Core_Exception($entity . ' could not be loaded');
2286 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2287 $paymentProcessorID = $this->_relatedObjects
['contributionRecur']->payment_processor_id
;
2290 if (!empty($ids['pledge_payment'])) {
2291 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2292 if (empty($paymentID)) {
2295 $payment = new CRM_Pledge_BAO_PledgePayment();
2296 $payment->id
= $paymentID;
2297 if (!$payment->find(TRUE)) {
2298 throw new Exception("Could not find pledge payment record: " . $paymentID);
2300 $this->_relatedObjects
['pledge_payment'][] = $payment;
2304 $this->loadRelatedMembershipObjects($ids);
2306 if ($this->_component
!= 'contribute') {
2307 // we are in event mode
2308 // make sure event exists and is valid
2309 $event = new CRM_Event_BAO_Event();
2310 $event->id
= $ids['event'];
2311 if ($ids['event'] &&
2314 throw new Exception("Could not find event: " . $ids['event']);
2317 $this->_relatedObjects
['event'] = &$event;
2319 $participant = new CRM_Event_BAO_Participant();
2320 $participant->id
= $ids['participant'];
2321 if ($ids['participant'] &&
2322 !$participant->find(TRUE)
2324 throw new Exception("Could not find participant: " . $ids['participant']);
2326 $participant->register_date
= CRM_Utils_Date
::isoToMysql($participant->register_date
);
2328 $this->_relatedObjects
['participant'] = &$participant;
2330 // get the payment processor id from event - this is inaccurate see CRM-16923
2331 // in future we should look at throwing an exception here rather than an dubious guess.
2332 if (!$paymentProcessorID) {
2333 $paymentProcessorID = $this->_relatedObjects
['event']->payment_processor
;
2334 if ($paymentProcessorID) {
2335 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2340 if ($paymentProcessorID) {
2341 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID,
2342 $this->is_test ?
'test' : 'live'
2344 $ids['paymentProcessor'] = $paymentProcessorID;
2345 $this->_relatedObjects
['paymentProcessor'] = $paymentProcessor;
2351 * Create array of message information - ie. return html version, txt version, to field
2353 * @param array $input
2354 * Incoming information.
2355 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2356 * just check presence of recur object but maintaining legacy approach
2359 * IDs of related objects.
2360 * @param array $values
2361 * Any values that may have already been compiled by calling process.
2362 * This is augmented by values 'gathered' by gatherMessageValues
2363 * @param bool $recur
2364 * @param bool $returnMessageText
2365 * Distinguishes between whether to send message or return.
2366 * message text. We are working towards this function ALWAYS returning message text & calling
2367 * function doing emails / pdfs with it
2373 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2374 $this->loadRelatedObjects($input, $ids);
2376 if (empty($this->_component
)) {
2377 $this->_component
= CRM_Utils_Array
::value('component', $input);
2380 //not really sure what params might be passed in but lets merge em into values
2381 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2382 $template = CRM_Core_Smarty
::singleton();
2383 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2384 //what does recur 'mean here - to do with payment processor return functionality but
2385 // what is the importance
2386 if ($recur && !empty($this->_relatedObjects
['paymentProcessor'])) {
2387 $paymentObject = Civi\Payment\System
::singleton()->getByProcessor($this->_relatedObjects
['paymentProcessor']);
2389 $entityID = $entity = NULL;
2390 if (isset($ids['contribution'])) {
2391 $entity = 'contribution';
2392 $entityID = $ids['contribution'];
2394 if (!empty($ids['membership'])) {
2395 //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
2396 // 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
2397 // line having loaded an array
2398 $ids['membership'] = (array) $ids['membership'];
2399 $entity = 'membership';
2400 $entityID = $ids['membership'][0];
2403 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2404 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2405 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2407 if ($this->_relatedObjects
['paymentProcessor']['billing_mode'] & CRM_Core_Payment
::BILLING_MODE_FORM
) {
2408 //direct mode showing billing block, so use directIPN for temporary
2409 $template->assign('contributeMode', 'directIPN');
2412 // todo remove strtolower - check consistency
2413 if (strtolower($this->_component
) == 'event') {
2414 $eventParams = array('id' => $this->_relatedObjects
['participant']->event_id
);
2415 $values['event'] = array();
2417 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2419 //get location details
2420 $locationParams = array('entity_id' => $this->_relatedObjects
['participant']->event_id
, 'entity_table' => 'civicrm_event');
2421 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2423 $ufJoinParams = array(
2424 'entity_table' => 'civicrm_event',
2425 'entity_id' => $ids['event'],
2426 'module' => 'CiviEvent',
2429 list($custom_pre_id,
2431 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2433 $values['custom_pre_id'] = $custom_pre_id;
2434 $values['custom_post_id'] = $custom_post_ids;
2435 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
2436 //and cases involving status updation through ipn
2437 // whatever that means!
2438 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2439 // perhaps we should throw an e-notice if amount is set & force total_amount?
2440 if (!empty($input['amount'])) {
2441 $values['totalAmount'] = $input['amount'];
2444 if ($values['event']['is_email_confirm']) {
2445 $values['is_email_receipt'] = 1;
2447 return CRM_Event_BAO_Event
::sendMail($ids['contact'], $values,
2448 $this->_relatedObjects
['participant']->id
, $this->is_test
, $returnMessageText
2452 $values['contribution_id'] = $this->id
;
2453 if (!empty($ids['related_contact'])) {
2454 $values['related_contact'] = $ids['related_contact'];
2455 if (isset($ids['onbehalf_dupe_alert'])) {
2456 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2458 $entityBlock = array(
2459 'contact_id' => $ids['contact'],
2460 'location_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_LocationType',
2461 'Home', 'id', 'name'
2464 $address = CRM_Core_BAO_Address
::getValues($entityBlock);
2465 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2468 if ($this->is_test
) {
2471 if (!empty($this->_relatedObjects
['membership'])) {
2472 foreach ($this->_relatedObjects
['membership'] as $membership) {
2473 if ($membership->id
) {
2474 $values['isMembership'] = TRUE;
2475 $values['membership_assign'] = TRUE;
2477 // need to set the membership values here
2478 $template->assign('membership_name',
2479 CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
)
2481 $template->assign('mem_start_date', $membership->start_date
);
2482 $template->assign('mem_join_date', $membership->join_date
);
2483 $template->assign('mem_end_date', $membership->end_date
);
2484 $membership_status = CRM_Member_PseudoConstant
::membershipStatus($membership->status_id
, NULL, 'label');
2485 $template->assign('mem_status', $membership_status);
2486 if ($membership_status == 'Pending' && $membership->is_pay_later
== 1) {
2487 $template->assign('is_pay_later', 1);
2490 // if separate payment there are two contributions recorded and the
2491 // admin will need to send a receipt for each of them separately.
2492 // we dont link the two in the db (but can potentially infer it if needed)
2493 $template->assign('is_separate_payment', 0);
2495 if ($recur && $paymentObject) {
2496 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'cancel');
2497 $template->assign('cancelSubscriptionUrl', $url);
2498 $url = $paymentObject->subscriptionURL($membership->id
, 'membership', 'billing');
2499 $template->assign('updateSubscriptionBillingUrl', $url);
2500 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2501 $template->assign('updateSubscriptionUrl', $url);
2504 $result = CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2507 // otherwise if its about sending emails, continue sending without return, as we
2508 // don't want to exit the loop.
2513 return CRM_Contribute_BAO_ContributionPage
::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2519 * Gather values for contribution mail - this function has been created
2520 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2521 * Values related to the contribution in question are gathered
2523 * @param array $input
2524 * Input into function (probably from payment processor).
2525 * @param array $values
2527 * The set of ids related to the input.
2531 public function _gatherMessageValues($input, &$values, $ids = array()) {
2532 // set display address of contributor
2533 if ($this->address_id
) {
2534 $addressParams = array('id' => $this->address_id
);
2535 $addressDetails = CRM_Core_BAO_Address
::getValues($addressParams, FALSE, 'id');
2536 $addressDetails = array_values($addressDetails);
2537 $values['address'] = $addressDetails[0]['display'];
2539 if ($this->_component
== 'contribute') {
2540 //get soft contributions
2541 $softContributions = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
, TRUE);
2542 if (!empty($softContributions)) {
2543 $values['softContributions'] = $softContributions['soft_credit'];
2545 if (isset($this->contribution_page_id
)) {
2546 CRM_Contribute_BAO_ContributionPage
::setValues(
2547 $this->contribution_page_id
,
2550 if ($this->contribution_page_id
) {
2551 // CRM-8254 - override default currency if applicable
2552 $config = CRM_Core_Config
::singleton();
2553 $config->defaultCurrency
= CRM_Utils_Array
::value(
2556 $config->defaultCurrency
2560 // no contribution page -probably back office
2562 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2563 $values['is_email_receipt'] = 1;
2564 $values['title'] = 'Contribution';
2566 // set lineItem for contribution
2568 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->id
, 'contribution', 1);
2569 if (!empty($lineItem)) {
2570 $itemId = key($lineItem);
2571 foreach ($lineItem as &$eachItem) {
2572 if (is_array($this->_relatedObjects
['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects
['membership'])) {
2573 $eachItem['join_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->join_date
);
2574 $eachItem['start_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->start_date
);
2575 $eachItem['end_date'] = CRM_Utils_Date
::customFormat($this->_relatedObjects
['membership'][$eachItem['membership_type_id']]->end_date
);
2578 $values['lineItem'][0] = $lineItem;
2579 $values['priceSetID'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2583 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds(
2587 // if this is onbehalf of contribution then set related contact
2588 if (!empty($relatedContact['individual_id'])) {
2589 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2594 $eventParams = array(
2595 'id' => $this->_relatedObjects
['event']->id
,
2597 $values['event'] = array();
2599 CRM_Event_BAO_Event
::retrieve($eventParams, $values['event']);
2600 // add custom fields for event
2601 $eventGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Event', $this->_relatedObjects
['event'], $this->_relatedObjects
['event']->id
);
2603 $eventCustomGroup = array();
2604 foreach ($eventGroupTree as $key => $group) {
2605 if ($key === 'info') {
2609 foreach ($group['fields'] as $k => $customField) {
2610 $groupLabel = $group['title'];
2611 if (!empty($customField['customValue'])) {
2612 foreach ($customField['customValue'] as $customFieldValues) {
2613 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2618 $values['event']['customGroup'] = $eventCustomGroup;
2620 //get participant details
2621 $participantParams = array(
2622 'id' => $this->_relatedObjects
['participant']->id
,
2625 $values['participant'] = array();
2627 CRM_Event_BAO_Participant
::getValues($participantParams, $values['participant'], $participantIds);
2628 // add custom fields for event
2629 $participantGroupTree = CRM_Core_BAO_CustomGroup
::getTree('Participant', $this->_relatedObjects
['participant'], $this->_relatedObjects
['participant']->id
);
2630 $participantCustomGroup = array();
2631 foreach ($participantGroupTree as $key => $group) {
2632 if ($key === 'info') {
2636 foreach ($group['fields'] as $k => $customField) {
2637 $groupLabel = $group['title'];
2638 if (!empty($customField['customValue'])) {
2639 foreach ($customField['customValue'] as $customFieldValues) {
2640 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2645 $values['participant']['customGroup'] = $participantCustomGroup;
2647 //get location details
2648 $locationParams = array(
2649 'entity_id' => $this->_relatedObjects
['event']->id
,
2650 'entity_table' => 'civicrm_event',
2652 $values['location'] = CRM_Core_BAO_Location
::getValues($locationParams);
2654 $ufJoinParams = array(
2655 'entity_table' => 'civicrm_event',
2656 'entity_id' => $ids['event'],
2657 'module' => 'CiviEvent',
2660 list($custom_pre_id,
2662 ) = CRM_Core_BAO_UFJoin
::getUFGroupIds($ufJoinParams);
2664 $values['custom_pre_id'] = $custom_pre_id;
2665 $values['custom_post_id'] = $custom_post_ids;
2667 // set lineItem for event contribution
2669 $participantIds = CRM_Event_BAO_Participant
::getParticipantIds($this->id
);
2670 if (!empty($participantIds)) {
2671 foreach ($participantIds as $pIDs) {
2672 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($pIDs);
2673 if (!CRM_Utils_System
::isNull($lineItem)) {
2674 $values['lineItem'][] = $lineItem;
2681 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Contribution', $this, $this->id
);
2683 $customGroup = array();
2684 foreach ($groupTree as $key => $group) {
2685 if ($key === 'info') {
2689 foreach ($group['fields'] as $k => $customField) {
2690 $groupLabel = $group['title'];
2691 if (!empty($customField['customValue'])) {
2692 foreach ($customField['customValue'] as $customFieldValues) {
2693 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array
::value('data', $customFieldValues);
2698 $values['customGroup'] = $customGroup;
2704 * Assign message variables to template but try to break the habit.
2706 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2707 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2708 * multiple recurring payments for processors like IATS that use tokens.
2710 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2711 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2712 * Note we send directly from this function in some cases because it is only partly refactored.
2714 * Don't call this function directly as the signature will change.
2718 * @param CRM_Core_SMARTY $template
2719 * @param bool $recur
2720 * @param bool $returnMessageText
2724 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2725 $template->assign('first_name', $this->_relatedObjects
['contact']->first_name
);
2726 $template->assign('last_name', $this->_relatedObjects
['contact']->last_name
);
2727 $template->assign('displayName', $this->_relatedObjects
['contact']->display_name
);
2728 if (!empty($values['lineItem']) && !empty($this->_relatedObjects
['membership'])) {
2729 $values['useForMember'] = TRUE;
2731 //assign honor information to receipt message
2732 $softRecord = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($this->id
);
2734 if (isset($softRecord['soft_credit'])) {
2735 //if id of contribution page is present
2736 if (!empty($values['id'])) {
2737 $values['honor'] = array(
2738 'honor_profile_values' => array(),
2739 'honor_profile_id' => CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2740 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2742 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
2744 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2745 $template->assign('honor_block_is_active', CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2748 //offline contribution
2749 $softCreditTypes = $softCredits = array();
2750 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2751 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2752 $softCredits[$key] = array(
2753 'Name' => $softCredit['contact_name'],
2754 'Amount' => CRM_Utils_Money
::format($softCredit['amount'], $softCredit['currency']),
2757 $template->assign('softCreditTypes', $softCreditTypes);
2758 $template->assign('softCredits', $softCredits);
2762 $dao = new CRM_Contribute_DAO_ContributionProduct();
2763 $dao->contribution_id
= $this->id
;
2764 if ($dao->find(TRUE)) {
2765 $premiumId = $dao->product_id
;
2766 $template->assign('option', $dao->product_option
);
2768 $productDAO = new CRM_Contribute_DAO_Product();
2769 $productDAO->id
= $premiumId;
2770 $productDAO->find(TRUE);
2771 $template->assign('selectPremium', TRUE);
2772 $template->assign('product_name', $productDAO->name
);
2773 $template->assign('price', $productDAO->price
);
2774 $template->assign('sku', $productDAO->sku
);
2776 $template->assign('title', CRM_Utils_Array
::value('title', $values));
2777 $values['amount'] = CRM_Utils_Array
::value('total_amount', $input, (CRM_Utils_Array
::value('amount', $input)), NULL);
2778 if (!$values['amount'] && isset($this->total_amount
)) {
2779 $values['amount'] = $this->total_amount
;
2782 // add the new contribution values
2783 if (strtolower($this->_component
) == 'contribute') {
2785 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2786 $softDAO->contribution_id
= $this->id
;
2787 if ($softDAO->find(TRUE)) {
2788 $template->assign('pcpBlock', TRUE);
2789 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll
);
2790 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname
);
2791 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note
);
2793 //assign the pcp page title for email subject
2794 $pcpDAO = new CRM_PCP_DAO_PCP();
2795 $pcpDAO->id
= $softDAO->pcp_id
;
2796 if ($pcpDAO->find(TRUE)) {
2797 $template->assign('title', $pcpDAO->title
);
2802 if ($this->financial_type_id
) {
2803 $values['financial_type_id'] = $this->financial_type_id
;
2806 $template->assign('trxn_id', $this->trxn_id
);
2807 $template->assign('receive_date',
2808 CRM_Utils_Date
::mysqlToIso($this->receive_date
)
2810 $template->assign('contributeMode', 'notify');
2811 $template->assign('action', $this->is_test ?
1024 : 1);
2812 $template->assign('receipt_text',
2813 CRM_Utils_Array
::value('receipt_text',
2817 $template->assign('is_monetary', 1);
2818 $template->assign('is_recur', (bool) $recur);
2819 $template->assign('currency', $this->currency
);
2820 $template->assign('address', CRM_Utils_Address
::format($input));
2821 if (!empty($values['customGroup'])) {
2822 $template->assign('customGroup', $values['customGroup']);
2824 if (!empty($values['softContributions'])) {
2825 $template->assign('softContributions', $values['softContributions']);
2827 if ($this->_component
== 'event') {
2828 $template->assign('title', $values['event']['title']);
2829 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
2830 $viewRoles = array();
2831 foreach (explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_relatedObjects
['participant']->role_id
) as $k => $v) {
2832 $viewRoles[] = $participantRoles[$v];
2834 $values['event']['participant_role'] = implode(', ', $viewRoles);
2835 $template->assign('event', $values['event']);
2836 $template->assign('participant', $values['participant']);
2837 $template->assign('location', $values['location']);
2838 $template->assign('customPre', $values['custom_pre_id']);
2839 $template->assign('customPost', $values['custom_post_id']);
2842 if ($this->_relatedObjects
['participant']->is_test
) {
2846 $values['params'] = array();
2847 //to get email of primary participant.
2848 $primaryEmail = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects
['participant']->contact_id
, 'email', 'contact_id');
2849 $primaryAmount[] = array(
2850 'label' => $this->_relatedObjects
['participant']->fee_level
. ' - ' . $primaryEmail,
2851 'amount' => $this->_relatedObjects
['participant']->fee_amount
,
2853 //build an array of cId/pId of participants
2854 $additionalIDs = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, NULL, $this->_relatedObjects
['contact']->id
, $isTest, TRUE);
2855 unset($additionalIDs[$this->_relatedObjects
['participant']->id
]);
2856 //send receipt to additional participant if exists
2857 if (count($additionalIDs)) {
2858 $template->assign('isPrimary', 0);
2859 $template->assign('customProfile', NULL);
2860 //set additionalParticipant true
2861 $values['params']['additionalParticipant'] = TRUE;
2862 foreach ($additionalIDs as $pId => $cId) {
2864 //to change the status pending to completed
2865 $additional = new CRM_Event_DAO_Participant();
2866 $additional->id
= $pId;
2867 $additional->contact_id
= $cId;
2868 $additional->find(TRUE);
2869 $additional->register_date
= $this->_relatedObjects
['participant']->register_date
;
2870 $additional->status_id
= 1;
2871 $additionalParticipantInfo = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id
, 'email', 'contact_id');
2872 //if additional participant dont have email
2874 if (!$additionalParticipantInfo) {
2875 $additionalParticipantInfo = CRM_Contact_BAO_Contact
::displayName($additional->contact_id
);
2877 $amount[0] = array('label' => $additional->fee_level
, 'amount' => $additional->fee_amount
);
2878 $primaryAmount[] = array(
2879 'label' => $additional->fee_level
. ' - ' . $additionalParticipantInfo,
2880 'amount' => $additional->fee_amount
,
2882 $additional->save();
2883 $additional->free();
2884 $template->assign('amount', $amount);
2885 CRM_Event_BAO_Event
::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2889 //build an array of custom profile and assigning it to template
2890 $customProfile = CRM_Event_BAO_Event
::buildCustomProfile($this->_relatedObjects
['participant']->id
, $values, NULL, $isTest);
2892 if (count($customProfile)) {
2893 $template->assign('customProfile', $customProfile);
2896 // for primary contact
2897 $values['params']['additionalParticipant'] = FALSE;
2898 $template->assign('isPrimary', 1);
2899 $template->assign('amount', $primaryAmount);
2900 $template->assign('register_date', CRM_Utils_Date
::isoToMysql($this->_relatedObjects
['participant']->register_date
));
2901 if ($this->payment_instrument_id
) {
2902 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
2903 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id
]);
2905 // carry paylater, since we did not created billing,
2906 // so need to pull email from primary location, CRM-4395
2907 $values['params']['is_pay_later'] = $this->_relatedObjects
['participant']->is_pay_later
;
2913 * Check whether payment processor supports
2914 * cancellation of contribution subscription
2916 * @param int $contributionId
2919 * @param bool $isNotCancelled
2923 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2924 $cacheKeyString = "$contributionId";
2925 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2927 static $supportsCancel = array();
2929 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2930 $supportsCancel[$cacheKeyString] = FALSE;
2931 $isCancelled = FALSE;
2933 if ($isNotCancelled) {
2934 $isCancelled = self
::isSubscriptionCancelled($contributionId);
2937 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($contributionId, 'contribute', 'obj');
2938 if (!empty($paymentObject)) {
2939 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
2942 return $supportsCancel[$cacheKeyString];
2946 * Check whether subscription is already cancelled.
2948 * @param int $contributionId
2952 * contribution status
2954 public static function isSubscriptionCancelled($contributionId) {
2956 SELECT cr.contribution_status_id
2957 FROM civicrm_contribution_recur cr
2958 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2959 WHERE con.id = %1 LIMIT 1";
2960 $params = array(1 => array($contributionId, 'Integer'));
2961 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2962 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2963 if ($status == 'Cancelled') {
2970 * Create all financial accounts entry.
2972 * @param array $params
2973 * Contribution object, line item array and params for trxn.
2976 * @param array $financialTrxnValues
2978 * @return null|object
2980 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2981 $skipRecords = $update = $return = $isRelatedId = FALSE;
2983 $additionalParticipantId = array();
2984 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
2985 $contributionStatus = empty($params['contribution_status_id']) ?
NULL : $contributionStatuses[$params['contribution_status_id']];
2987 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'participant') {
2988 $entityId = $params['participant_id'];
2989 $entityTable = 'civicrm_participant';
2990 $additionalParticipantId = CRM_Event_BAO_Participant
::getAdditionalParticipantIds($entityId);
2992 elseif (!empty($params['membership_id'])) {
2993 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2994 // are created off one contribution should be handled elsewhere
2995 $entityId = $params['membership_id'];
2996 $entityTable = 'civicrm_membership';
2999 $entityId = $params['contribution']->id
;
3000 $entityTable = 'civicrm_contribution';
3003 if (CRM_Utils_Array
::value('contribution_mode', $params) == 'membership') {
3004 $isRelatedId = TRUE;
3007 $entityID[] = $entityId;
3008 if (!empty($additionalParticipantId)) {
3009 $entityID +
= $additionalParticipantId;
3011 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3012 if (empty($params['prevContribution'])) {
3019 $statusId = $params['contribution']->contribution_status_id
;
3020 // CRM-13964 partial payment
3021 if ($contributionStatus == 'Partially paid'
3022 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3024 $partialAmtPay = $params['partial_amount_pay'];
3025 $partialAmtTotal = $params['partial_payment_total'];
3027 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3028 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3029 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3030 $params['total_amount'] = $partialAmtPay;
3032 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($params['contribution']->id
, $params['financial_type_id']);
3033 if (empty($balanceTrxnInfo['trxn_id'])) {
3034 // create new balance transaction record
3035 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3036 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3038 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
3039 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3040 $balanceTrxnParams['contribution_id'] = $params['contribution']->id
;
3041 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis');
3042 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3043 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3044 $balanceTrxnParams['currency'] = $params['contribution']->currency
;
3045 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id
;
3046 $balanceTrxnParams['status_id'] = $statusId;
3047 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3048 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3049 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3050 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
3052 $balanceTrxnParams['is_payment'] = 1;
3054 if (!empty($params['payment_processor'])) {
3055 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3057 $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
3061 // build line item array if its not set in $params
3062 if (empty($params['line_item']) ||
$additionalParticipantId) {
3063 CRM_Price_BAO_LineItem
::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3066 if ($contributionStatus != 'Failed' &&
3067 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later
)
3069 $skipRecords = TRUE;
3070 $pendingStatus = array(
3074 if (in_array($contributionStatus, $pendingStatus)) {
3075 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3076 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $relationTypeId);
3078 elseif (!empty($params['payment_processor'])) {
3079 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
3081 elseif (!empty($params['payment_instrument_id'])) {
3082 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($params['payment_instrument_id']);
3085 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3086 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3087 $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);
3090 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
3091 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3092 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount
;
3095 //build financial transaction params
3096 $trxnParams = array(
3097 'contribution_id' => $params['contribution']->id
,
3098 'to_financial_account_id' => $params['to_financial_account_id'],
3099 'trxn_date' => !empty($params['contribution']->receive_date
) ?
$params['contribution']->receive_date
: date('YmdHis'),
3100 'total_amount' => $totalAmount,
3101 'fee_amount' => CRM_Utils_Array
::value('fee_amount', $params),
3102 'net_amount' => CRM_Utils_Array
::value('net_amount', $params, $totalAmount),
3103 'currency' => $params['contribution']->currency
,
3104 'trxn_id' => $params['contribution']->trxn_id
,
3105 'status_id' => $statusId,
3106 'payment_instrument_id' => $params['contribution']->payment_instrument_id
,
3107 'check_number' => CRM_Utils_Array
::value('check_number', $params),
3109 if ($contributionStatus == 'Refunded') {
3110 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date
) ?
$params['contribution']->cancel_date
: date('YmdHis');
3111 if (isset($params['refund_trxn_id'])) {
3112 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3113 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3116 //CRM-16259, set is_payment flag for non pending status
3117 if (!in_array($contributionStatus, $pendingStatus)) {
3118 $trxnParams['is_payment'] = 1;
3120 if (!empty($params['payment_processor'])) {
3121 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3124 if (isset($fromFinancialAccountId)) {
3125 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3128 // consider external values passed for recording transaction entry
3129 if (!empty($financialTrxnValues)) {
3130 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3133 $params['trxnParams'] = $trxnParams;
3135 if (!empty($params['prevContribution'])) {
3137 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount
;
3138 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount
;
3139 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount
;
3140 if (!isset($params['trxnParams']['trxn_id'])) {
3141 // Actually I have no idea why we are overwriting any values from the previous contribution.
3142 // (filling makes sense to me). However, only protecting this value as I really really know we
3143 // don't want this one overwritten.
3145 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id
;
3147 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id
;
3149 if (!(($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatuses)
3150 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatuses))
3151 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses))
3153 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3154 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3157 //if financial type is changed
3158 if (!empty($params['financial_type_id']) &&
3159 $params['contribution']->financial_type_id
!= $params['prevContribution']->financial_type_id
3161 $incomeTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
3162 $oldFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['prevContribution']->financial_type_id
, $incomeTypeId);
3163 $newFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($params['financial_type_id'], $incomeTypeId);
3164 if ($oldFinancialAccount != $newFinancialAccount) {
3165 $params['total_amount'] = 0;
3166 if (in_array($params['contribution']->contribution_status_id
, $pendingStatus)) {
3167 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType(
3168 $params['prevContribution']->financial_type_id
, $relationTypeId);
3171 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3172 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3173 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3176 self
::updateFinancialAccounts($params, 'changeFinancialType');
3177 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3178 $params['financial_account_id'] = $newFinancialAccount;
3179 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3180 self
::updateFinancialAccounts($params);
3181 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3186 //Update contribution status
3187 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id
;
3188 if (!isset($params['refund_trxn_id'])) {
3189 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3190 // gets preference over another so I am only 'protecting' a very specific tested flow
3191 // and letting natural justice take care of the rest.
3192 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3194 if (!empty($params['contribution_status_id']) &&
3195 $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3197 //Update Financial Records
3198 self
::updateFinancialAccounts($params, 'changedStatus');
3202 // change Payment Instrument for a Completed contribution
3203 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3204 // instrument is null and now new payment instrument is added along with the payment
3205 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3206 $params['trxnParams']['check_number'] = CRM_Utils_Array
::value('check_number', $params);
3207 if (array_key_exists('payment_instrument_id', $params)) {
3208 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
3209 if (CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
) &&
3210 !CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
)
3212 //check if status is changed from Pending to Completed
3213 // do not update payment instrument changes for Pending to Completed
3214 if (!($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatuses) &&
3215 in_array($params['prevContribution']->contribution_status_id
, $pendingStatus))
3217 // for all other statuses create new financial records
3218 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3219 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3220 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3224 elseif ((!CRM_Utils_System
::isNull($params['contribution']->payment_instrument_id
) ||
3225 !CRM_Utils_System
::isNull($params['prevContribution']->payment_instrument_id
)) &&
3226 $params['contribution']->payment_instrument_id
!= $params['prevContribution']->payment_instrument_id
3228 // for any other payment instrument changes create new financial records
3229 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3230 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3231 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3234 elseif (!CRM_Utils_System
::isNull($params['contribution']->check_number
) &&
3235 $params['contribution']->check_number
!= $params['prevContribution']->check_number
3237 // another special case when check number is changed, create new financial records
3238 // create financial trxn with negative amount
3239 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number
;
3240 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3241 // create financial trxn with positive amount
3242 $params['trxnParams']['check_number'] = $params['contribution']->check_number
;
3243 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3244 self
::updateFinancialAccounts($params, 'changePaymentInstrument');
3249 //if Change contribution amount
3250 $params['trxnParams']['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
3251 $params['trxnParams']['net_amount'] = CRM_Utils_Array
::value('net_amount', $params);
3252 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3253 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id
;
3254 if (isset($totalAmount) &&
3255 $totalAmount != $params['prevContribution']->total_amount
3257 //Update Financial Records
3258 $params['trxnParams']['from_financial_account_id'] = NULL;
3259 self
::updateFinancialAccounts($params, 'changedAmount');
3264 // Looks like we might have a data correction update.
3265 // This would be a case where a transaction id has been entered but it is incorrect &
3266 // the person goes back in & fixes it, as opposed to a new transaction.
3267 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3268 // the data fix scenario.
3270 if (isset($params['refund_trxn_id'])) {
3271 $refundIDs = CRM_Core_BAO_FinancialTrxn
::getRefundTransactionIDs($params['id']);
3272 if ($refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3273 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3280 // records finanical trxn and entity financial trxn
3281 // also make it available as return value
3282 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn
::create($trxnParams);
3283 $params['entity_id'] = $financialTxn->id
;
3286 // record line items and financial items
3287 if (empty($params['skipLineItem'])) {
3288 CRM_Price_BAO_LineItem
::processPriceSet($entityId, CRM_Utils_Array
::value('line_item', $params), $params['contribution'], $entityTable, $update);
3291 // create batch entry if batch_id is passed and
3292 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3293 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3294 $entityParams = array(
3295 'batch_id' => $params['batch_id'],
3296 'entity_table' => 'civicrm_financial_trxn',
3297 'entity_id' => $financialTxn->id
,
3299 CRM_Batch_BAO_Batch
::addBatchEntity($entityParams);
3302 // when a fee is charged
3303 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) ||
$params['contribution']->fee_amount
!= $params['prevContribution']->fee_amount
) && $skipRecords) {
3304 CRM_Core_BAO_FinancialTrxn
::recordFees($params);
3307 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3308 && $params['prevContribution']->contribution_status_id
!= $params['contribution']->contribution_status_id
3310 $eventID = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3311 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level
);
3312 CRM_Event_BAO_Participant
::createDiscountTrxn($eventID, $params, $feeLevel);
3314 unset($params['line_item']);
3320 * Update all financial accounts entry.
3322 * @param array $params
3323 * Contribution object, line item array and params for trxn.
3325 * @param string $context
3328 * @param null $skipTrxn
3331 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
3332 $itemAmount = $trxnID = NULL;
3333 //get all the statuses
3334 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3335 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3336 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3337 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3338 && $context == 'changePaymentInstrument'
3342 if (($params['prevContribution']->contribution_status_id
== array_search('Partially paid', $contributionStatus))
3343 && $params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3344 && $context == 'changedStatus'
3348 if ($context == 'changedAmount' ||
$context == 'changeFinancialType') {
3349 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount
;
3351 if ($context == 'changedStatus') {
3352 //get all the statuses
3353 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3354 $cancelledTaxAmount = 0;
3355 if ($params['prevContribution']->contribution_status_id
== array_search('Completed', $contributionStatus)
3356 && ($params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3357 ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus))
3359 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3360 $cancelledTaxAmount = CRM_Utils_Array
::value('tax_amount', $params, '0.00');
3361 if (empty($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3362 $creditNoteId = self
::createCreditNoteId();
3363 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3366 elseif (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3367 && $params['prevContribution']->is_pay_later
) ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus)
3369 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $params) ?
$params['financial_type_id'] : $params['prevContribution']->financial_type_id
;
3370 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3371 $arAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeID, $relationTypeId);
3373 if ($params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)) {
3374 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
3375 $params['trxnParams']['total_amount'] = -$params['total_amount'];
3376 if (is_null($params['contribution']->creditnote_id
) ||
$params['contribution']->creditnote_id
== "null") {
3377 $creditNoteId = self
::createCreditNoteId();
3378 CRM_Core_DAO
::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id
, 'creditnote_id', $creditNoteId);
3382 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3385 $itemAmount = $params['trxnParams']['total_amount'] +
$cancelledTaxAmount;
3387 elseif ($context == 'changePaymentInstrument') {
3388 if ($params['trxnParams']['total_amount'] < 0) {
3389 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($params['prevContribution']->id
, 'DESC');
3390 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3391 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3392 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id
;
3396 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3397 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id
;
3400 $trxn = CRM_Core_BAO_FinancialTrxn
::create($params['trxnParams']);
3401 $params['entity_id'] = $trxn->id
;
3403 if ($context == 'changedStatus') {
3404 if (($params['prevContribution']->contribution_status_id
== array_search('Pending', $contributionStatus)
3405 ||
$params['prevContribution']->contribution_status_id
== array_search('In Progress', $contributionStatus))
3406 && ($params['contribution']->contribution_status_id
== array_search('Completed', $contributionStatus))
3408 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3409 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3411 $entityParams = array(
3412 'entity_table' => 'civicrm_financial_item',
3413 'financial_trxn_id' => $trxn->id
,
3415 if (empty($params['line_item'])) {
3417 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3418 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3419 // & this can be removed
3422 foreach ($params['line_item'] as $fieldId => $fields) {
3423 foreach ($fields as $fieldValueId => $fieldValues) {
3425 1 => array(CRM_Core_OptionGroup
::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3426 2 => array($fieldValues['id'], 'Integer'),
3428 CRM_Core_DAO
::executeQuery($query, $fparams);
3430 1 => array($fieldValues['id'], 'Integer'),
3432 $financialItem = CRM_Core_DAO
::executeQuery($sql, $fparams);
3433 while ($financialItem->fetch()) {
3434 $entityParams['entity_id'] = $financialItem->id
;
3435 $entityParams['amount'] = $financialItem->amount
;
3436 CRM_Financial_BAO_FinancialItem
::createEntityTrxn($entityParams);
3443 if ($context != 'changePaymentInstrument') {
3444 $itemParams['entity_table'] = 'civicrm_line_item';
3445 $trxnIds['id'] = $params['entity_id'];
3446 foreach ($params['line_item'] as $fieldId => $fields) {
3447 foreach ($fields as $fieldValueId => $fieldValues) {
3448 $prevParams['entity_id'] = $fieldValues['id'];
3449 $prevfinancialItem = CRM_Financial_BAO_FinancialItem
::retrieve($prevParams, CRM_Core_DAO
::$_nullArray);
3451 $receiveDate = CRM_Utils_Date
::isoToMysql($params['prevContribution']->receive_date
);
3452 if ($params['contribution']->receive_date
) {
3453 $receiveDate = CRM_Utils_Date
::isoToMysql($params['contribution']->receive_date
);
3456 $financialAccount = $prevfinancialItem->financial_account_id
;
3457 if (!empty($params['financial_account_id'])) {
3458 $financialAccount = $params['financial_account_id'];
3461 $currency = $params['prevContribution']->currency
;
3462 if ($params['contribution']->currency
) {
3463 $currency = $params['contribution']->currency
;
3466 if ($context == 'changeFinancialType' ||
$params['contribution']->contribution_status_id
== array_search('Cancelled', $contributionStatus)
3467 ||
$params['contribution']->contribution_status_id
== array_search('Refunded', $contributionStatus)
3471 if (!empty($params['is_quick_config'])) {
3472 $amount = $itemAmount;
3474 $amount = $params['total_amount'];
3478 $amount = $diff * $fieldValues['line_total'];
3481 $itemParams = array(
3482 'transaction_date' => $receiveDate,
3483 'contact_id' => $params['prevContribution']->contact_id
,
3484 'currency' => $currency,
3485 'amount' => $amount,
3486 'description' => $prevfinancialItem->description
,
3487 'status_id' => $prevfinancialItem->status_id
,
3488 'financial_account_id' => $financialAccount,
3489 'entity_table' => 'civicrm_line_item',
3490 'entity_id' => $fieldValues['id'],
3492 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3494 if ($fieldValues['tax_amount']) {
3495 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
3496 $taxTerm = CRM_Utils_Array
::value('tax_term', $invoiceSettings);
3497 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3498 $itemParams['description'] = $taxTerm;
3499 if ($fieldValues['financial_type_id']) {
3500 $itemParams['financial_account_id'] = self
::getFinancialAccountId($fieldValues['financial_type_id']);
3502 CRM_Financial_BAO_FinancialItem
::create($itemParams, NULL, $trxnIds);
3507 if ($context == 'changeFinancialType') {
3508 $params['skipLineItem'] = FALSE;
3509 foreach ($params['line_item'] as &$lineItems) {
3510 foreach ($lineItems as &$line) {
3511 $line['financial_type_id'] = $params['financial_type_id'];
3518 * Check status validation on update of a contribution.
3520 * @param array $values
3521 * Previous form values before submit.
3523 * @param array $fields
3524 * The input form values.
3526 * @param array $errors
3531 public static function checkStatusValidation($values, &$fields, &$errors) {
3532 if (CRM_Utils_System
::isNull($values) && !empty($fields['id'])) {
3533 $values['contribution_status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3534 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3538 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
3539 $checkStatus = array(
3540 'Cancelled' => array('Completed', 'Refunded'),
3541 'Completed' => array('Cancelled', 'Refunded'),
3542 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3543 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3544 'Refunded' => array('Cancelled', 'Completed'),
3545 'Partially paid' => array('Completed'),
3548 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3549 CRM_Utils_Array
::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3551 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3552 1 => $contributionStatuses[$values['contribution_status_id']],
3553 2 => $contributionStatuses[$fields['contribution_status_id']],
3559 * Delete contribution of contact.
3563 * @param int $contactId
3567 public static function deleteContactContribution($contactId) {
3568 $contribution = new CRM_Contribute_DAO_Contribution();
3569 $contribution->contact_id
= $contactId;
3570 $contribution->find();
3571 while ($contribution->fetch()) {
3572 self
::deleteContribution($contribution->id
);
3577 * Get options for a given contribution field.
3578 * @see CRM_Core_DAO::buildOptions
3580 * @param string $fieldName
3581 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3582 * @param array $props whatever is known about this dao object.
3584 * @return array|bool
3586 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3587 $className = __CLASS__
;
3589 switch ($fieldName) {
3590 // This field is not part of this object but the api supports it
3591 case 'payment_processor':
3592 $className = 'CRM_Contribute_BAO_ContributionPage';
3593 // Filter results by contribution page
3594 if (!empty($props['contribution_page_id'])) {
3595 $page = civicrm_api('contribution_page', 'getsingle', array(
3597 'id' => ($props['contribution_page_id']),
3599 $types = (array) CRM_Utils_Array
::value('payment_processor', $page, 0);
3600 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3604 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3605 case 'honor_type_id':
3606 $className = 'CRM_Contribute_BAO_ContributionSoft';
3607 $fieldName = 'soft_credit_type_id';
3608 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3611 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3615 * Validate financial type.
3619 * @param int $financialTypeId
3620 * Financial Type id.
3622 * @param string $relationName
3624 * @return array|bool
3626 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3627 $expenseTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3628 $financialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $expenseTypeId);
3630 if (!$financialAccount) {
3631 return CRM_Contribute_PseudoConstant
::financialType($financialTypeId);
3638 * Function to record additional payment for partial and refund contributions.
3640 * @param int $contributionId
3641 * is the invoice contribution id (got created after processing participant payment).
3642 * @param array $trxnsData
3643 * to take user provided input of transaction details.
3644 * @param string $paymentType
3645 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3646 * @param int $participantId
3648 * @return null|object
3650 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
3651 $statusId = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
3652 $getInfoOf['id'] = $contributionId;
3653 $defaults = array();
3654 $contributionDAO = CRM_Contribute_BAO_Contribution
::retrieve($getInfoOf, $defaults, CRM_Core_DAO
::$_nullArray);
3655 if (!$participantId) {
3656 $participantId = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id');
3659 if ($paymentType == 'owed') {
3660 // build params for recording financial trxn entry
3661 $params['contribution'] = $contributionDAO;
3662 $params = array_merge($defaults, $params);
3663 $params['skipLineItem'] = TRUE;
3664 $params['partial_payment_total'] = $contributionDAO->total_amount
;
3665 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3666 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3667 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ?
$trxnsData['net_amount'] : $trxnsData['total_amount'];
3670 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3671 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3672 $toFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3674 $trxnId = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id
);
3675 if (!empty($trxnId)) {
3676 $trxnId = $trxnId['trxn_id'];
3678 elseif (!empty($contributionDAO->payment_instrument_id
)) {
3679 $trxnId = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id
);
3682 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3683 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3684 $trxnId = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3688 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3689 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
3690 FROM civicrm_financial_trxn ft
3691 LEFT JOIN civicrm_entity_financial_trxn eft
3692 ON (ft.id = eft.financial_trxn_id)
3693 WHERE eft.entity_table = 'civicrm_contribution'
3694 AND eft.entity_id = {$contributionId}
3695 AND ft.to_financial_account_id != {$toFinancialAccount}
3696 AND ft.status_id = {$statusId}
3698 $query = CRM_Core_DAO
::executeQuery($sql);
3700 $sumOfPayments = $query->sum_of_payments
;
3703 if ($contributionDAO->total_amount
== $sumOfPayments) {
3704 // update contribution status and
3705 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3706 $contributionDAO->contribution_status_id
= $statusId;
3707 $contributionDAO->cancel_date
= 'null';
3708 $contributionDAO->cancel_reason
= NULL;
3709 $netAmount = !empty($trxnsData['net_amount']) ?
NULL : $trxnsData['total_amount'];
3710 $contributionDAO->net_amount
= $query->net_amount_total +
$netAmount;
3711 $contributionDAO->fee_amount
= $contributionDAO->total_amount
- $contributionDAO->net_amount
;
3712 $contributionDAO->save();
3714 //Change status of financial record too
3715 $financialTrxn->status_id
= $statusId;
3716 $financialTrxn->save();
3718 // note : not using the self::add method,
3719 // the reason because it performs 'status change' related code execution for financial records
3720 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3721 // are coded below i.e. just updating financial_item status to 'Paid'
3723 if ($participantId) {
3724 // update participant status
3725 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3726 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3727 foreach ($ids as $val) {
3728 $participantUpdate['id'] = $val;
3729 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3730 CRM_Event_BAO_Participant
::add($participantUpdate);
3734 // update financial item statuses
3735 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3736 $paidStatus = array_search('Paid', $financialItemStatus);
3738 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3739 $sqlFinancialItemUpdate = "
3740 UPDATE civicrm_financial_item fi
3741 LEFT JOIN civicrm_entity_financial_trxn eft
3742 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3743 SET status_id = {$paidStatus}
3744 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3746 CRM_Core_DAO
::executeQuery($sqlFinancialItemUpdate);
3749 elseif ($paymentType == 'refund') {
3750 // build params for recording financial trxn entry
3751 $params['contribution'] = $contributionDAO;
3752 $params = array_merge($defaults, $params);
3753 $params['skipLineItem'] = TRUE;
3754 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ?
$trxnsData['trxn_date'] : date('YmdHis');
3755 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3757 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3758 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contributionDAO->financial_type_id
, $relationTypeId);
3759 $trxnsData['status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', 'Refunded', 'name');
3761 $financialTrxn = CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($params, $trxnsData);
3763 // note : not using the self::add method,
3764 // the reason because it performs 'status change' related code execution for financial records
3765 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3766 // are coded below i.e. just updating financial_item status to 'Paid'
3767 if ($updateStatus) {
3768 $contributionDetails = CRM_Core_DAO
::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3770 // add financial item entry
3771 $financialItemStatus = CRM_Core_PseudoConstant
::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3772 $getLine['entity_id'] = $contributionDAO->id
;
3773 $getLine['entity_table'] = 'civicrm_contribution';
3774 $lineItemId = CRM_Price_BAO_LineItem
::retrieve($getLine, CRM_Core_DAO
::$_nullArray);
3775 if (!empty($lineItemId->id
)) {
3776 $addFinancialEntry = array(
3777 'transaction_date' => $financialTrxn->trxn_date
,
3778 'contact_id' => $contributionDAO->contact_id
,
3779 'amount' => $financialTrxn->total_amount
,
3780 'status_id' => array_search('Paid', $financialItemStatus),
3781 'entity_id' => $lineItemId->id
,
3782 'entity_table' => 'civicrm_line_item',
3784 $trxnIds['id'] = $financialTrxn->id
;
3785 CRM_Financial_BAO_FinancialItem
::create($addFinancialEntry, NULL, $trxnIds);
3787 if ($participantId) {
3788 // update participant status
3789 $participantStatuses = CRM_Event_PseudoConstant
::participantStatus();
3790 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3791 foreach ($ids as $val) {
3792 $participantUpdate['id'] = $val;
3793 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3794 CRM_Event_BAO_Participant
::add($participantUpdate);
3799 // activity creation
3800 if (!empty($financialTrxn)) {
3801 if ($participantId) {
3802 $inputParams['id'] = $participantId;
3805 $component = 'event';
3806 $entityObj = CRM_Event_BAO_Participant
::getValues($inputParams, $values, $ids);
3807 $entityObj = $entityObj[$participantId];
3809 $activityType = ($paymentType == 'refund') ?
'Refund' : 'Payment';
3811 self
::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3813 return $financialTrxn;
3819 * @param $activityType
3821 * @param int $contributionId
3823 * @throws CRM_Core_Exception
3825 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3826 if ($component == 'event') {
3827 $date = CRM_Utils_Date
::isoToMysql($trxnObj->trxn_date
);
3828 $paymentAmount = CRM_Utils_Money
::format($trxnObj->total_amount
, $trxnObj->currency
);
3829 $eventTitle = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id
, 'title');
3830 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3831 $targetCid = $entityObj->contact_id
;
3832 // source record id would be the contribution id
3833 $srcRecId = $contributionId;
3837 $activityParams = array(
3838 'source_contact_id' => $targetCid,
3839 'source_record_id' => $srcRecId,
3840 'activity_type_id' => CRM_Core_OptionGroup
::getValue('activity_type',
3844 'subject' => $subject,
3845 'activity_date_time' => $date,
3846 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status',
3850 'skipRecentView' => TRUE,
3853 // create activity with target contacts
3854 $session = CRM_Core_Session
::singleton();
3855 $id = $session->get('userID');
3857 $activityParams['source_contact_id'] = $id;
3858 $activityParams['target_contact_id'][] = $targetCid;
3860 CRM_Activity_BAO_Activity
::create($activityParams);
3864 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3868 * @param bool $getTrxnInfo
3869 * @param bool $usingLineTotal
3873 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3874 if ($component == 'event') {
3875 $entity = 'participant';
3876 $entityTable = 'civicrm_participant';
3877 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3879 if (!$contributionId) {
3880 if ($primaryParticipantId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3881 $contributionId = CRM_Core_DAO
::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3882 $id = $primaryParticipantId;
3884 if (!$contributionId) {
3890 $contributionId = $id;
3891 $entity = 'contribution';
3892 $entityTable = 'civicrm_contribution';
3895 $total = CRM_Core_BAO_FinancialTrxn
::getBalanceTrxnAmt($contributionId);
3896 $baseTrxnId = !empty($total['trxn_id']) ?
$total['trxn_id'] : NULL;
3902 $baseTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contributionId);
3903 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3906 if (!CRM_Utils_Array
::value('total_amount', $total) ||
$usingLineTotal) {
3907 // for additional participants
3908 if ($entityTable == 'civicrm_participant') {
3909 $ids = CRM_Event_BAO_Participant
::getParticipantIds($contributionId);
3911 foreach ($ids as $val) {
3912 $total +
= CRM_Price_BAO_LineItem
::getLineTotal($val, $entityTable);
3916 $total = CRM_Price_BAO_LineItem
::getLineTotal($id, $entityTable);
3920 $baseTrxnId = $total['trxn_id'];
3921 $total = $total['total_amount'];
3924 $paymentBalance = CRM_Core_BAO_FinancialTrxn
::getPartialPaymentWithType($id, $entity, FALSE, $total);
3925 $contributionIsPayLater = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3927 $feeRelationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3928 $financialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3929 $feeFinancialAccount = CRM_Contribute_PseudoConstant
::financialAccountType($financialTypeId, $feeRelationTypeId);
3931 if ($paymentBalance == 0 && $contributionIsPayLater) {
3932 $paymentBalance = $total;
3935 $info['total'] = $total;
3936 $info['paid'] = $total - $paymentBalance;
3937 $info['balance'] = $paymentBalance;
3939 $info['component'] = $component;
3940 $info['payLater'] = $contributionIsPayLater;
3942 if ($getTrxnInfo && $baseTrxnId) {
3943 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3945 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3946 FROM civicrm_contribution con
3947 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3948 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3949 WHERE con.id = {$contributionId}
3952 // conditioned WHERE clause
3954 // if balance trxn exists don't include details of it in transaction info
3955 $sql .= " AND ft.id != {$baseTrxnId} ";
3957 $resultDAO = CRM_Core_DAO
::executeQuery($sql);
3959 $statuses = CRM_Contribute_PseudoConstant
::contributionStatus();
3960 $financialTypes = CRM_Contribute_PseudoConstant
::financialType();
3961 while ($resultDAO->fetch()) {
3962 $paidByLabel = CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3963 $paidByName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id
);
3965 'total_amount' => $resultDAO->total_amount
,
3966 'financial_type' => $financialTypes[$resultDAO->financial_type_id
],
3967 'payment_instrument' => $paidByLabel,
3968 'receive_date' => $resultDAO->trxn_date
,
3969 'trxn_id' => $resultDAO->trxn_id
,
3970 'status' => $statuses[$resultDAO->status_id
],
3972 if ($paidByName == 'Check') {
3973 $val['check_number'] = $resultDAO->check_number
;
3977 $info['transaction'] = $rows;
3983 * Get financial account id has 'Sales Tax Account is'
3984 * account relationship with financial type
3986 * @param int $financialTypeId
3988 * @return FinancialAccountId
3990 public static function getFinancialAccountId($financialTypeId) {
3991 $accountRel = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3992 $searchParams = array(
3993 'entity_table' => 'civicrm_financial_type',
3994 'entity_id' => $financialTypeId,
3995 'account_relationship' => $accountRel,
3998 CRM_Financial_BAO_FinancialTypeAccount
::retrieve($searchParams, $result);
4000 return CRM_Utils_Array
::value('financial_account_id', $result);
4006 * @param array $params
4007 * @param bool $isLineItem
4011 public static function checkTaxAmount($params, $isLineItem = FALSE) {
4012 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
4014 // Update contribution.
4015 if (!empty($params['id'])) {
4016 $id = $params['id'];
4017 $values = $ids = array();
4018 $contrbutionParams = array('id' => $id);
4019 $prevContributionValue = CRM_Contribute_BAO_Contribution
::getValues($contrbutionParams, $values, $ids);
4021 // To assign pervious finantial type on update of contribution
4022 if (!isset($params['financial_type_id'])) {
4023 $params['financial_type_id'] = $prevContributionValue->financial_type_id
;
4025 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
4026 // Assisn tax Amount on update of contrbution
4027 if (!empty($prevContributionValue->tax_amount
)) {
4028 $params['tax_amount'] = 'null';
4029 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4030 foreach ($params['line_item'] as $setID => $priceField) {
4031 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4032 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4039 // New Contrbution and update of contribution with tax rate financial type
4040 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4041 empty($params['skipLineItem']) && !$isLineItem
4043 $taxRateParams = $taxRates[$params['financial_type_id']];
4044 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['total_amount'], $taxRateParams);
4045 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4047 // Get Line Item on update of contribution
4048 if (isset($params['id'])) {
4049 CRM_Price_BAO_LineItem
::getLineItemArray($params, array($params['id']));
4052 CRM_Price_BAO_LineItem
::getLineItemArray($params);
4054 foreach ($params['line_item'] as $setID => $priceField) {
4055 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4056 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4059 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4061 elseif (isset($params['api.line_item.create'])) {
4062 // Update total amount of contribution using lineItem
4063 $taxAmountArray = array();
4064 foreach ($params['api.line_item.create'] as $key => $value) {
4065 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4066 $taxRate = $taxRates[$value['financial_type_id']];
4067 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($value['line_total'], $taxRate);
4068 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4071 $params['tax_amount'] = array_sum($taxAmountArray);
4072 $params['total_amount'] = $params['total_amount'] +
$params['tax_amount'];
4075 // update line item of contrbution
4076 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4077 $taxRate = $taxRates[$params['financial_type_id']];
4078 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($params['line_total'], $taxRate);
4079 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4086 * Check financial type validation on update of a contribution.
4088 * @param Integer $financialTypeId
4089 * Value of latest Financial Type.
4091 * @param Integer $contributionId
4094 * @param array $errors
4099 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4100 if (!empty($financialTypeId)) {
4101 $oldFinancialTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4102 if ($oldFinancialTypeId == $financialTypeId) {
4106 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4108 '1' => array($contributionId, 'Integer'),
4110 $result = CRM_Core_DAO
::executeQuery($sql, $params);
4111 if ($result->N
> 1) {
4112 $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.');
4117 * Update related pledge payment payments.
4119 * This function has been refactored out of the back office contribution form and may
4120 * still overlap with other functions.
4122 * @param string $action
4123 * @param int $pledgePaymentID
4124 * @param int $contributionID
4125 * @param bool $adjustTotalAmount
4126 * @param float $total_amount
4127 * @param float $original_total_amount
4128 * @param int $contribution_status_id
4129 * @param int $original_contribution_status_id
4131 public static function updateRelatedPledge(
4137 $original_total_amount,
4138 $contribution_status_id,
4139 $original_contribution_status_id
4141 if (!$pledgePaymentID && $action & CRM_Core_Action
::ADD
&& !$contributionID) {
4145 if ($pledgePaymentID) {
4146 //store contribution id in payment record.
4147 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4150 $pledgePaymentID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4157 if (!$pledgePaymentID) {
4160 $pledgeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4166 $updatePledgePaymentStatus = FALSE;
4168 // If either the status or the amount has changed we update the pledge status.
4169 if ($action & CRM_Core_Action
::ADD
) {
4170 $updatePledgePaymentStatus = TRUE;
4172 elseif ($action & CRM_Core_Action
::UPDATE
&& (($original_contribution_status_id != $contribution_status_id) ||
4173 ($original_total_amount != $total_amount))
4175 $updatePledgePaymentStatus = TRUE;
4178 if ($updatePledgePaymentStatus) {
4179 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID,
4180 array($pledgePaymentID),
4181 $contribution_status_id,
4190 * Compute the stats values
4192 * @param $stat either 'mode' or 'median'
4194 * @param $alias of civicrm_contribution
4196 public static function computeStats($stat, $sql, $alias = NULL) {
4197 $mode = $median = array();
4200 $modeDAO = CRM_Core_DAO
::executeQuery($sql);
4201 while ($modeDAO->fetch()) {
4202 if ($modeDAO->civicrm_contribution_total_amount_count
> 1) {
4203 $mode[] = CRM_Utils_Money
::format($modeDAO->amount
, $modeDAO->currency
);
4212 $currencies = CRM_Core_OptionGroup
::values('currencies_enabled');
4213 foreach ($currencies as $currency => $val) {
4215 $where = "AND {$alias}.currency = '{$currency}'";
4216 $rowCount = CRM_Core_DAO
::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4220 $medianRow = floor($rowCount / 2);
4221 if ($rowCount %
2 == 0 && !empty($medianRow)) {
4227 $medianValue = "SELECT {$alias}.total_amount as median
4229 ORDER BY median LIMIT {$medianRow},{$offset}";
4230 $medianValDAO = CRM_Core_DAO
::executeQuery($medianValue);
4231 while ($medianValDAO->fetch()) {
4233 $midValue = $midValue +
$medianValDAO->median
;
4236 $median[] = CRM_Utils_Money
::format($medianValDAO->median
, $currency);
4240 $midValue = $midValue / 2;
4241 $median[] = CRM_Utils_Money
::format($midValue, $currency);
4252 * Is there only one line item attached to the contribution.
4258 * @throws \CiviCRM_API3_Exception
4260 public static function isSingleLineItem($id) {
4261 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
4262 return ($lineItemCount == 1);
4266 * Complete an order.
4268 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4270 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4272 * Moving it out of the BaseIPN class is just the first step.
4274 * @param array $input
4276 * @param array $objects
4277 * @param CRM_Core_Transaction $transaction
4279 * @param CRM_Contribute_BAO_Contribution $contribution
4280 * @param bool $isRecurring
4281 * Duplication of param needs review. Only used by AuthorizeNetIPN
4282 * @param int $isFirstOrLastRecurringPayment
4283 * Deprecated param only used by AuthorizeNetIPN.
4285 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
4286 $primaryContributionID = isset($contribution->id
) ?
$contribution->id
: $objects['first_contribution']->id
;
4287 // The previous details are used when calculating line items so keep it before any code that 'does something'
4288 if (!empty($contribution->id
)) {
4289 $input['prevContribution'] = CRM_Contribute_BAO_Contribution
::getValues(array('id' => $contribution->id
),
4290 CRM_Core_DAO
::$_nullArray, CRM_Core_DAO
::$_nullArray);
4292 $inputContributionWhiteList = array(
4297 'payment_instrument_id',
4302 if (self
::isSingleLineItem($primaryContributionID)) {
4303 $inputContributionWhiteList[] = 'financial_type_id';
4306 $participant = CRM_Utils_Array
::value('participant', $objects);
4307 $memberships = CRM_Utils_Array
::value('membership', $objects);
4308 $recurContrib = CRM_Utils_Array
::value('contributionRecur', $objects);
4309 $event = CRM_Utils_Array
::value('event', $objects);
4311 $contributionParams = array_merge(array(
4312 'contribution_status_id' => 'Completed',
4313 'source' => self
::getRecurringContributionDescription($contribution, $event),
4314 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4317 if (!empty($recurContrib->id
)) {
4318 $contributionParams['contribution_recur_id'] = $recurContrib->id
;
4320 $changeDate = CRM_Utils_Array
::value('trxn_date', $input, date('YmdHis'));
4322 if (empty($contributionParams['receive_date']) && $changeDate) {
4323 $contributionParams['receive_date'] = $changeDate;
4326 self
::repeatTransaction($contribution, $input, $contributionParams);
4327 $contributionParams['financial_type_id'] = $contribution->financial_type_id
;
4329 if (is_numeric($memberships)) {
4330 $memberships = array($objects['membership']);
4334 if (isset($input['is_email_receipt'])) {
4335 $values['is_email_receipt'] = $input['is_email_receipt'];
4338 if ($input['component'] == 'contribute') {
4339 if ($contribution->contribution_page_id
) {
4340 // Figure out what we gain from this.
4341 CRM_Contribute_BAO_ContributionPage
::setValues($contribution->contribution_page_id
, $values);
4343 elseif ($recurContrib && $recurContrib->id
) {
4344 $values['amount'] = $recurContrib->amount
;
4345 $values['financial_type_id'] = $objects['contributionType']->id
;
4346 $values['title'] = $source = ts('Offline Recurring Contribution');
4347 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
4348 $values['receipt_from_name'] = $domainValues[0];
4349 $values['receipt_from_email'] = $domainValues[1];
4352 if ($recurContrib && $recurContrib->id
&& !isset($input['is_email_receipt'])) {
4353 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4354 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4355 $values['is_email_receipt'] = $recurContrib->is_email_receipt
;
4358 if (!empty($values['is_email_receipt'])) {
4359 $contributionParams['receipt_date'] = $changeDate;
4362 if (!empty($memberships)) {
4363 foreach ($memberships as $membershipTypeIdKey => $membership) {
4365 $membershipParams = array(
4366 'id' => $membership->id
,
4367 'contact_id' => $membership->contact_id
,
4368 'is_test' => $membership->is_test
,
4369 'membership_type_id' => $membership->membership_type_id
,
4372 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($membershipParams['contact_id'],
4373 $membershipParams['membership_type_id'],
4374 $membershipParams['is_test'],
4375 $membershipParams['id']
4378 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4379 // this picks up membership type changes during renewals
4381 SELECT membership_type_id
4382 FROM civicrm_membership_log
4383 WHERE membership_id={$membershipParams['id']}
4386 $dao = CRM_Core_DAO
::executeQuery($sql);
4387 if ($dao->fetch()) {
4388 if (!empty($dao->membership_type_id
)) {
4389 $membershipParams['membership_type_id'] = $dao->membership_type_id
;
4394 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4395 $membershipParams['membership_type_id'],
4396 $primaryContributionID
4398 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
4399 if ($currentMembership) {
4401 * Fixed FOR CRM-4433
4402 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4403 * when Contribution mode is notify and membership is for renewal )
4405 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4407 // @todo - we should pass membership_type_id instead of null here but not
4408 // adding as not sure of testing
4409 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membershipParams['id'],
4410 $changeDate, NULL, $membershipParams['num_terms']
4413 $dates['join_date'] = $currentMembership['join_date'];
4416 //get the status for membership.
4417 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($dates['start_date'],
4419 $dates['join_date'],
4422 $membershipParams['membership_type_id'],
4426 $membershipParams['status_id'] = CRM_Utils_Array
::value('id', $calcStatus, 'New');
4427 //we might be renewing membership,
4428 //so make status override false.
4429 $membershipParams['is_override'] = FALSE;
4430 //CRM-17723 - reset static $relatedContactIds array()
4432 CRM_Member_BAO_Membership
::createRelatedMemberships($var, $var, TRUE);
4433 civicrm_api3('Membership', 'create', $membershipParams);
4439 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4440 if ($event->is_email_confirm
) {
4441 // @todo this should be set by the function that sends the mail after sending.
4442 $contributionParams['receipt_date'] = $changeDate;
4444 $participantParams['id'] = $participant->id
;
4445 $participantParams['status_id'] = 'Registered';
4446 civicrm_api3('Participant', 'create', $participantParams);
4450 $contributionParams['id'] = $contribution->id
;
4452 civicrm_api3('Contribution', 'create', $contributionParams);
4454 // Add new soft credit against current $contribution.
4455 if (CRM_Utils_Array
::value('contributionRecur', $objects) && $objects['contributionRecur']->id
) {
4456 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($objects['contributionRecur']->id
, $contribution->id
);
4459 $paymentProcessorId = '';
4460 if (isset($objects['paymentProcessor'])) {
4461 if (is_array($objects['paymentProcessor'])) {
4462 $paymentProcessorId = $objects['paymentProcessor']['id'];
4465 $paymentProcessorId = $objects['paymentProcessor']->id
;
4469 $contributionStatuses = CRM_Core_PseudoConstant
::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4470 'labelColumn' => 'name',
4473 if ((empty($input['prevContribution']) && $paymentProcessorId) ||
(!$input['prevContribution']->is_pay_later
&& $input['prevContribution']->contribution_status_id
== $contributionStatuses['Pending'])) {
4474 $input['payment_processor'] = $paymentProcessorId;
4476 $input['contribution_status_id'] = $contributionStatuses['Completed'];
4477 $input['total_amount'] = $input['amount'];
4478 $input['contribution'] = $contribution;
4479 $input['financial_type_id'] = $contribution->financial_type_id
;
4481 if (!empty($contribution->_relatedObjects
['participant'])) {
4482 $input['contribution_mode'] = 'participant';
4483 $input['participant_id'] = $contribution->_relatedObjects
['participant']->id
;
4484 $input['skipLineItem'] = 1;
4486 elseif (!empty($contribution->_relatedObjects
['membership'])) {
4487 $input['skipLineItem'] = TRUE;
4488 $input['contribution_mode'] = 'membership';
4490 //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
4491 // and subsequent payments. In this case the line items are created at
4492 // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
4493 // and since the contribution is saved prior to this line there is always a contribution-id,
4494 // however there is never a prevContribution (which appears to mean original contribution not previous
4495 // contribution - or preUpdateContributionObject most accurately)
4496 // so, this is always called & only appears to succeed when prevContribution exists - which appears
4497 // to mean "are we updating an exisitng pending contribution"
4498 //I was able to make the unit test complete as fataling here doesn't prevent
4499 // the contribution being created - but activities would not be created or emails sent
4501 CRM_Contribute_BAO_Contribution
::recordFinancialAccounts($input, NULL);
4503 CRM_Core_Error
::debug_log_message("Contribution record updated successfully");
4504 $transaction->commit();
4506 CRM_Contribute_BAO_ContributionRecur
::updateRecurLinkedPledge($contribution);
4508 // create an activity record
4509 if ($input['component'] == 'contribute') {
4511 $targetContactID = NULL;
4512 if (!empty($ids['related_contact'])) {
4513 $targetContactID = $contribution->contact_id
;
4514 $contribution->contact_id
= $ids['related_contact'];
4516 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID);
4520 CRM_Activity_BAO_Activity
::addActivity($participant);
4523 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4524 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4525 if (!array_key_exists('is_email_receipt', $values) ||
4526 $values['is_email_receipt'] == 1
4528 self
::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
4529 CRM_Core_Error
::debug_log_message("Receipt sent");
4532 CRM_Core_Error
::debug_log_message("Success: Database updated");
4534 CRM_Contribute_BAO_ContributionRecur
::sendRecurringStartOrEndNotification($ids, $recur,
4535 $isFirstOrLastRecurringPayment);
4540 * Send receipt from contribution.
4542 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4544 * Note that the compose message part has been moved to contribution
4545 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4547 * @param array $input
4548 * Incoming data from Payment processor.
4550 * Related object IDs.
4551 * @param CRM_Contribute_BAO_Contribution $contribution
4552 * @param array $values
4553 * Values related to objects that have already been loaded.
4554 * @param bool $recur
4555 * Is it part of a recurring contribution.
4556 * @param bool $returnMessageText
4557 * Should text be returned instead of sent. This.
4558 * is because the function is also used to generate pdfs
4562 public static function sendMail(&$input, &$ids, $contribution, &$values, $recur = FALSE, $returnMessageText = FALSE) {
4563 $input['is_recur'] = $recur;
4564 // set receipt from e-mail and name in value
4565 if (!$returnMessageText) {
4566 $session = CRM_Core_Session
::singleton();
4567 $userID = $session->get('userID');
4568 if (!empty($userID)) {
4569 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
4570 $values['receipt_from_email'] = CRM_Utils_Array
::value('receipt_from_email', $input, $userEmail);
4571 $values['receipt_from_name'] = CRM_Utils_Array
::value('receipt_from_name', $input, $userName);
4574 return $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText);
4578 * Generate credit note id with next avaible number
4583 public static function createCreditNoteId() {
4584 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
4586 $creditNoteNum = CRM_Core_DAO
::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
4587 $creditNoteId = NULL;
4591 $creditNoteId = CRM_Utils_Array
::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4592 $result = civicrm_api3('Contribution', 'getcount', array(
4594 'creditnote_id' => $creditNoteId,
4596 } while ($result > 0);
4598 return $creditNoteId;
4602 * Load related memberships.
4604 * Note that in theory it should be possible to retrieve these from the line_item table
4605 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4606 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4607 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4608 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4610 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4616 public function loadRelatedMembershipObjects(&$ids) {
4618 SELECT membership_id
4619 FROM civicrm_membership_payment
4620 WHERE contribution_id = %1 ";
4621 $params = array(1 => array($this->id
, 'Integer'));
4623 $dao = CRM_Core_DAO
::executeQuery($query, $params);
4624 while ($dao->fetch()) {
4625 if ($dao->membership_id
) {
4626 if (!is_array($ids['membership'])) {
4627 $ids['membership'] = array();
4629 $ids['membership'][] = $dao->membership_id
;
4633 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4634 foreach ($ids['membership'] as $id) {
4636 $membership = new CRM_Member_BAO_Membership();
4637 $membership->id
= $id;
4638 if (!$membership->find(TRUE)) {
4639 throw new Exception("Could not find membership record: $id");
4641 $membership->join_date
= CRM_Utils_Date
::isoToMysql($membership->join_date
);
4642 $membership->start_date
= CRM_Utils_Date
::isoToMysql($membership->start_date
);
4643 $membership->end_date
= CRM_Utils_Date
::isoToMysql($membership->end_date
);
4644 $this->_relatedObjects
['membership'][$membership->membership_type_id
] = $membership;
4645 $membership->free();
4652 * This function is used to record partial payments for contribution
4654 * @param array $contribution
4656 * @param array $params
4660 public static function recordPartialPayment($contribution, $params) {
4661 $contributionStatuses = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
4662 $pendingStatus = array(
4663 array_search('Pending', $contributionStatuses),
4664 array_search('In Progress', $contributionStatuses),
4666 $statusId = array_search('Completed', $contributionStatuses);
4667 if (in_array(CRM_Utils_Array
::value('contribution_status_id', $contribution), $pendingStatus)) {
4668 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4669 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4671 elseif (!empty($params['payment_processor'])) {
4672 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4674 elseif (!empty($params['payment_instrument_id'])) {
4675 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4678 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4679 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4680 $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);
4682 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
4683 $fromFinancialAccountId = CRM_Contribute_PseudoConstant
::financialAccountType($contribution['financial_type_id'], $relationTypeId);
4684 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4685 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4686 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4687 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ?
$params['contribution_receive_date'] : date('YmdHis');
4688 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array
::value('fee_amount', $params);
4689 $balanceTrxnParams['net_amount'] = CRM_Utils_Array
::value('total_amount', $params);
4690 $balanceTrxnParams['currency'] = $contribution['currency'];
4691 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array
::value('contribution_trxn_id', $params, NULL);
4692 $balanceTrxnParams['status_id'] = $statusId;
4693 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array
::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4694 $balanceTrxnParams['check_number'] = CRM_Utils_Array
::value('check_number', $params);
4695 if ($fromFinancialAccountId != NULL &&
4696 ($statusId == array_search('Completed', $contributionStatuses) ||
$statusId == array_search('Partially paid', $contributionStatuses))
4698 $balanceTrxnParams['is_payment'] = 1;
4700 if (!empty($params['payment_processor'])) {
4701 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4703 return CRM_Core_BAO_FinancialTrxn
::create($balanceTrxnParams);
4707 * Get the description (source field) for the recurring contribution.
4709 * @param CRM_Contribute_BAO_Contribution $contribution
4710 * @param CRM_Event_DAO_Event|null $event
4713 * @throws \CiviCRM_API3_Exception
4715 protected static function getRecurringContributionDescription($contribution, $event) {
4716 if (!empty($contribution->contribution_page_id
)) {
4717 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4718 'id' => $contribution->contribution_page_id
,
4719 'return' => 'title',
4721 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4724 return ts('Online Event Registration') . ': ' . $event->title
;
4726 return 'recurring contribution';