Merge pull request #5058 from eileenmcnaughton/test-examples
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
36
37 /**
100fef9d 38 * Static field for all the contribution information that we can potentially import
6a488035
TO
39 *
40 * @var array
6a488035
TO
41 */
42 static $_importableFields = NULL;
43
44 /**
100fef9d 45 * Static field for all the contribution information that we can potentially export
6a488035
TO
46 *
47 * @var array
6a488035
TO
48 */
49 static $_exportableFields = NULL;
50
51 /**
100fef9d 52 * Field for all the objects related to this contribution
6a488035
TO
53 * @var array of objects (e.g membership object, participant object)
54 */
55 public $_relatedObjects = array();
56
57 /**
100fef9d 58 * Field for the component - either 'event' (participant) or 'contribute'
6a488035
TO
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
62 *
63 * @var string component or event
64 */
65 public $_component = NULL;
66
186c9c17 67 /**
100fef9d 68 * Class constructor
186c9c17 69 *
186c9c17
EM
70 * @return \CRM_Contribute_DAO_Contribution
71 */
72 /**
186c9c17 73 */
00be9182 74 public function __construct() {
6a488035
TO
75 parent::__construct();
76 }
77
78 /**
100fef9d 79 * Takes an associative array and creates a contribution object
6a488035
TO
80 *
81 * the function extract all the params it needs to initialize the create a
82 * contribution object. the params array could contain additional unused name/value
83 * pairs
84 *
014c4014
TO
85 * @param array $params
86 * (reference ) an assoc array of name/value pairs.
87 * @param array $ids
88 * The array that holds all the db ids.
6a488035 89 *
bed98343 90 * @return CRM_Contribute_BAO_Contribution|void
6a488035 91 */
00be9182 92 public static function add(&$params, $ids = array()) {
6a488035 93 if (empty($params)) {
bed98343 94 return NULL;
6a488035 95 }
504a78f6 96 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
97 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
6a488035 98 $duplicates = array();
504a78f6 99 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
6a488035
TO
100 $error = CRM_Core_Error::singleton();
101 $d = implode(', ', $duplicates);
102 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
103 'Fatal',
104 array($d),
105 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
106 );
107 return $error;
108 }
109
110 // first clean up all the money fields
111 $moneyFields = array(
112 'total_amount',
113 'net_amount',
114 'fee_amount',
115 'non_deductible_amount',
116 );
ae06c851 117
6a488035 118 //if priceset is used, no need to cleanup money
a7488080 119 if (!empty($params['skipCleanMoney'])) {
6a488035
TO
120 unset($moneyFields[0]);
121 }
122
123 foreach ($moneyFields as $field) {
124 if (isset($params[$field])) {
125 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
126 }
127 }
48ea0708 128
f2b2a3ff 129 //set defaults in create mode
44a2db2b 130 if (!$contributionID) {
64d24a64 131 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
44a2db2b 132 self::calculateMissingAmountParams($params);
d96cf288 133 }
6a488035 134
a7488080 135 if (!empty($params['payment_instrument_id'])) {
6a488035
TO
136 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
137 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
138 $params['check_number'] = 'null';
139 }
140 }
141
5e494d5c 142 $setPrevContribution = TRUE;
f8325309 143 // CRM-13964 partial payment
5e494d5c
PJ
144 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
145 $partialAmtTotal = $params['partial_payment_total'];
146 $partialAmtPay = $params['partial_amount_pay'];
147 $params['total_amount'] = $partialAmtTotal;
148 if ($partialAmtPay < $partialAmtTotal) {
ede1935f 149 $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name');
5e494d5c
PJ
150 $params['is_pay_later'] = 0;
151 $setPrevContribution = FALSE;
f8325309
PJ
152 }
153 }
ede1935f 154
504a78f6 155 if ($contributionID) {
156 CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
6a488035
TO
157 }
158 else {
159 CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
160 }
6a488035
TO
161 $contribution = new CRM_Contribute_BAO_Contribution();
162 $contribution->copyValues($params);
163
504a78f6 164 $contribution->id = $contributionID;
6a488035
TO
165
166 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
167 $config = CRM_Core_Config::singleton();
168 $contribution->currency = $config->defaultCurrency;
169 }
170
5e494d5c 171 if ($contributionID && $setPrevContribution) {
504a78f6 172 $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
6a488035
TO
173 }
174
175 $result = $contribution->save();
176
177 // Add financial_trxn details as part of fix for CRM-4724
178 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
179 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
180
181 //add Account details
182 $params['contribution'] = $contribution;
0aaf8fe9 183 self::recordFinancialAccounts($params);
6a488035 184
6a488035
TO
185 // reset the group contact cache for this group
186 CRM_Contact_BAO_GroupContactCache::remove();
187
504a78f6 188 if ($contributionID) {
6a488035
TO
189 CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
190 }
191 else {
192 CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
193 }
194
195 return $result;
196 }
197
44a2db2b
EM
198 /**
199 * Get defaults for new entity
200 * @return array
201 */
00be9182 202 public static function getDefaults() {
44a2db2b
EM
203 return array(
204 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
205 FALSE, FALSE, FALSE, 'AND is_default = 1')
206 ),
207 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'),
208 );
44a2db2b
EM
209 }
210
6a488035
TO
211 /**
212 * Given the list of params in the params array, fetch the object
213 * and store the values in the values array
214 *
014c4014
TO
215 * @param array $params
216 * Input parameters to find object.
217 * @param array $values
218 * Output values of the object.
219 * @param array $ids
220 * The array that holds all the db ids.
6a488035
TO
221 *
222 * @return CRM_Contribute_BAO_Contribution|null the found object or null
6a488035 223 */
00be9182 224 public static function &getValues($params, &$values, &$ids) {
6a488035
TO
225 if (empty($params)) {
226 return NULL;
227 }
228 $contribution = new CRM_Contribute_BAO_Contribution();
229
230 $contribution->copyValues($params);
231
232 if ($contribution->find(TRUE)) {
233 $ids['contribution'] = $contribution->id;
234
235 CRM_Core_DAO::storeValues($contribution, $values);
236
237 return $contribution;
238 }
7e5524d4
TO
239 $null = NULL; // return by reference
240 return $null;
6a488035
TO
241 }
242
44a2db2b 243 /**
c490a46a 244 * @param array $params
44a2db2b
EM
245 *
246 * @return mixed
247 */
248 public static function calculateMissingAmountParams(&$params) {
249 if (!isset($params['fee_amount'])) {
250 if (isset($params['total_amount']) && isset($params['net_amount'])) {
251 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
252 }
253 else {
254 $params['fee_amount'] = 0;
255 }
256 }
257 if (!isset($params['net_amount'])) {
258 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
259 }
260 }
261
2243fe93
EM
262 /**
263 * Get the number of terms for this contribution for a given membership type
264 * based on querying the line item table and relevant price field values
265 * Note that any one contribution should only be able to have one line item relating to a particular membership
266 * type
a284891b 267 *
2243fe93
EM
268 * @param int $membershipTypeID
269 *
a284891b
EM
270 * @param int $contributionID
271 *
2243fe93
EM
272 * @return int
273 */
a284891b 274 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
f2b2a3ff 275 $numTerms = CRM_Core_DAO::singleValueQuery("
2243fe93
EM
276 SELECT membership_num_terms FROM civicrm_line_item li
277 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
29347f3d 278 WHERE contribution_id = %1 AND membership_type_id = %2",
f2b2a3ff 279 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
2243fe93
EM
280 );
281 // default of 1 is precautionary
282 return empty($numTerms) ? 1 : $numTerms;
283 }
284
6a488035 285 /**
100fef9d 286 * Takes an associative array and creates a contribution object
6a488035 287 *
014c4014
TO
288 * @param array $params
289 * (reference ) an assoc array of name/value pairs.
290 * @param array $ids
291 * The array that holds all the db ids.
6a488035 292 *
16b10e64 293 * @return CRM_Contribute_BAO_Contribution
6a488035 294 */
00be9182 295 public static function create(&$params, $ids = array()) {
6a488035
TO
296 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
297 foreach ($dateFields as $df) {
298 if (isset($params[$df])) {
299 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
300 }
301 }
302
6a488035
TO
303 $transaction = new CRM_Core_Transaction();
304
6a488035
TO
305 $contribution = self::add($params, $ids);
306
307 if (is_a($contribution, 'CRM_Core_Error')) {
308 $transaction->rollback();
309 return $contribution;
310 }
311
312 $params['contribution_id'] = $contribution->id;
313
a7488080 314 if (!empty($params['custom']) &&
6a488035
TO
315 is_array($params['custom'])
316 ) {
317 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
318 }
319
320 $session = CRM_Core_Session::singleton();
321
a7488080 322 if (!empty($params['note'])) {
6a488035
TO
323 $noteParams = array(
324 'entity_table' => 'civicrm_contribution',
325 'note' => $params['note'],
326 'entity_id' => $contribution->id,
327 'contact_id' => $session->get('userID'),
328 'modified_date' => date('Ymd'),
329 );
330 if (!$noteParams['contact_id']) {
331 $noteParams['contact_id'] = $params['contact_id'];
332 }
504a78f6 333 CRM_Core_BAO_Note::add($noteParams);
6a488035
TO
334 }
335
336 // make entry in batch entity batch table
a7488080 337 if (!empty($params['batch_id'])) {
6a488035
TO
338 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
339 $titleFields = array(
340 'contact_id',
341 'total_amount',
342 'currency',
343 'financial_type_id',
344 );
d37ade2e 345 $retrieveRequired = 0;
6a488035 346 foreach ($titleFields as $titleField) {
f2b2a3ff 347 if (!isset($contribution->$titleField)) {
d37ade2e 348 $retrieveRequired = 1;
6a488035
TO
349 break;
350 }
351 }
d37ade2e 352 if ($retrieveRequired == 1) {
2cfc0f58 353 $contribution->find(TRUE);
6a488035
TO
354 }
355 }
356
357 // check if activity record exist for this contribution, if
358 // not add activity
359 $activity = new CRM_Activity_DAO_Activity();
360 $activity->source_record_id = $contribution->id;
361 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
362 'Contribution',
363 'name'
364 );
e3538d57 365 if (!$activity->find(TRUE)) {
6a488035
TO
366 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
367 }
e3538d57 368 else {
7910ff9c 369 // CRM-13237 : if activity record found, update it with campaign id of contribution
e3538d57
PJ
370 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
371 }
2cfc0f58 372
6a488035 373 // Handle soft credit and / or link to personal campaign page
b6545333 374 $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
1221efe9 375
376 //Delete PCP against this contribution and create new on submitted PCP information
377 $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE);
378 if ($pcpId) {
379 $deleteParams = array('id' => $pcpId);
380 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
381 }
2cfc0f58 382 if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
2cfc0f58 383 $softParams = array();
384 $softParams['contribution_id'] = $contribution->id;
385 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
386 $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
387 $pcp['pcp_made_through_id'], 'contact_id'
388 );
389 $softParams['currency'] = $contribution->currency;
390 $softParams['amount'] = $contribution->total_amount;
391 $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
392 $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
393 $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
51fa20cb 394 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
12f92dbd
N
395 $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($softParams);
396 //Send notification to owner for PCP
397 if ($contributionSoft->pcp_id) {
398 CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
399 }
2cfc0f58 400 }
b6545333 401 if (isset($params['soft_credit'])) {
2cfc0f58 402 $softParams = $params['soft_credit'];
7f880799 403
404 if (!empty($softIDs)) {
f2b2a3ff 405 foreach ($softIDs as $softID) {
7f880799 406 if (!in_array($softID, $params['soft_credit_ids'])) {
407 $deleteParams = array('id' => $softID);
408 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
409 }
ae06c851 410 }
6a488035 411 }
2cfc0f58 412
413 foreach ($softParams as $softParam) {
414 $softParam['contribution_id'] = $contribution->id;
415 $softParam['currency'] = $contribution->currency;
7305d3e6 416 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
417 if (empty($softParam['amount'])) {
418 $softParam['amount'] = $contribution->total_amount;
419 }
2cfc0f58 420 CRM_Contribute_BAO_ContributionSoft::add($softParam);
421 }
6a488035 422 }
2cfc0f58 423
6a488035
TO
424 $transaction->commit();
425
426 // do not add to recent items for import, CRM-4399
a7488080 427 if (empty($params['skipRecentView'])) {
6a488035
TO
428 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
429 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
430 );
431 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
432 $titleFields = array(
433 'contact_id',
434 'total_amount',
435 'currency',
436 'financial_type_id',
437 );
d37ade2e 438 $retrieveRequired = 0;
6a488035 439 foreach ($titleFields as $titleField) {
f2b2a3ff 440 if (!isset($contribution->$titleField)) {
d37ade2e 441 $retrieveRequired = 1;
6a488035
TO
442 break;
443 }
444 }
f2b2a3ff 445 if ($retrieveRequired == 1) {
2cfc0f58 446 $contribution->find(TRUE);
6a488035
TO
447 }
448 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
449 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
450
451 $recentOther = array();
452 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
453 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
454 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
455 );
456 }
457
458 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
459 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
460 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
461 );
462 }
463
464 // add the recently created Contribution
465 CRM_Utils_Recent::add($title,
466 $url,
467 $contribution->id,
468 'Contribution',
469 $contribution->contact_id,
470 NULL,
471 $recentOther
472 );
473 }
474
475 return $contribution;
476 }
477
478 /**
479 * Get the values for pseudoconstants for name->value and reverse.
480 *
014c4014
TO
481 * @param array $defaults
482 * (reference) the default values, some of which need to be resolved.
483 * @param bool $reverse
484 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035
TO
485 *
486 * @return void
6a488035 487 */
00be9182 488 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
6a488035
TO
489 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
490 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
491 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
492 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
493 }
494
495 /**
dc195289 496 * convert associative array names to values
6a488035
TO
497 * and vice-versa.
498 *
499 * This function is used by both the web form layer and the api. Note that
500 * the api needs the name => value conversion, also the view layer typically
501 * requires value => name conversion
502 */
00be9182 503 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
6a488035
TO
504 $id = $property . '_id';
505
506 $src = $reverse ? $property : $id;
507 $dst = $reverse ? $id : $property;
508
509 if (!array_key_exists($src, $defaults)) {
510 return FALSE;
511 }
512
513 $look = $reverse ? array_flip($lookup) : $lookup;
514
515 if (is_array($look)) {
516 if (!array_key_exists($defaults[$src], $look)) {
517 return FALSE;
518 }
519 }
520 $defaults[$dst] = $look[$defaults[$src]];
521 return TRUE;
522 }
523
524 /**
525 * Takes a bunch of params that are needed to match certain criteria and
526 * retrieves the relevant objects. We'll tweak this function to be more
527 * full featured over a period of time. This is the inverse function of
528 * create. It also stores all the retrieved values in the default array
529 *
014c4014
TO
530 * @param array $params
531 * (reference ) an assoc array of name/value pairs.
532 * @param array $defaults
533 * (reference ) an assoc array to hold the name / value pairs.
6a488035 534 * in a hierarchical manner
014c4014
TO
535 * @param array $ids
536 * (reference) the array that holds all the db ids.
6a488035 537 *
16b10e64 538 * @return CRM_Contribute_BAO_Contribution
6a488035 539 */
00be9182 540 public static function retrieve(&$params, &$defaults, &$ids) {
6a488035
TO
541 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
542 return $contribution;
543 }
544
545 /**
100fef9d 546 * Combine all the importable fields from the lower levels object
6a488035
TO
547 *
548 * The ordering is important, since currently we do not have a weight
549 * scheme. Adding weight is super important and should be done in the
550 * next week or so, before this can be called complete.
551 *
8efea814
EM
552 * @param string $contactType
553 * @param bool $status
554 *
a6c01b45
CW
555 * @return array
556 * array of importable Fields
6a488035 557 */
00be9182 558 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
6a488035
TO
559 if (!self::$_importableFields) {
560 if (!self::$_importableFields) {
561 self::$_importableFields = array();
562 }
563
564 if (!$status) {
565 $fields = array('' => array('title' => ts('- do not import -')));
566 }
567 else {
568 $fields = array('' => array('title' => ts('- Contribution Fields -')));
569 }
570
571 $note = CRM_Core_DAO_Note::import();
572 $tmpFields = CRM_Contribute_DAO_Contribution::import();
573 unset($tmpFields['option_value']);
574 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
c2585c5b 575 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
6a488035
TO
576
577 // Using new Dedupe rule.
578 $ruleParams = array(
c2585c5b 579 'contact_type' => $contactType,
f2b2a3ff 580 'used' => 'Unsupervised',
6a488035
TO
581 );
582 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
c2585c5b 583 $tmpContactField = array();
6a488035
TO
584 if (is_array($fieldsArray)) {
585 foreach ($fieldsArray as $value) {
586 //skip if there is no dupe rule
587 if ($value == 'none') {
588 continue;
589 }
590 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
591 $value,
592 'id',
593 'column_name'
594 );
595 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
c2585c5b 596 $tmpContactField[trim($value)] = $contactFields[trim($value)];
6a488035 597 if (!$status) {
c2585c5b 598 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
6a488035
TO
599 }
600 else {
c2585c5b 601 $title = $tmpContactField[trim($value)]['title'];
6a488035 602 }
c2585c5b 603 $tmpContactField[trim($value)]['title'] = $title;
6a488035
TO
604 }
605 }
606
c2585c5b 607 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
608 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
6a488035 609 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
c2585c5b 610 $fields = array_merge($fields, $tmpContactField);
6a488035
TO
611 $fields = array_merge($fields, $tmpFields);
612 $fields = array_merge($fields, $note);
613 $fields = array_merge($fields, $optionFields);
614 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
615 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
616 self::$_importableFields = $fields;
617 }
618 return self::$_importableFields;
619 }
620
186c9c17
EM
621 /**
622 * @return array
623 */
00be9182 624 public static function &exportableFields() {
6a488035
TO
625 if (!self::$_exportableFields) {
626 if (!self::$_exportableFields) {
627 self::$_exportableFields = array();
628 }
629
f2b2a3ff
TO
630 $impFields = CRM_Contribute_DAO_Contribution::export();
631 $expFieldProduct = CRM_Contribute_DAO_Product::export();
632 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
633 $typeField = CRM_Financial_DAO_FinancialType::export();
634 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
635 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
6a488035
TO
636 $contributionStatus = array(
637 'contribution_status' => array(
638 'title' => ts('Contribution Status'),
639 'name' => 'contribution_status',
21dfd5f5
TO
640 'data_type' => CRM_Utils_Type::T_STRING,
641 ),
f2b2a3ff 642 );
6a488035 643
3c151c70 644 $contributionPage = array(
645 'contribution_page' => array(
646 'title' => ts('Contribution Page'),
647 'name' => 'contribution_page',
648 'where' => 'civicrm_contribution_page.title',
a130e045 649 'data_type' => CRM_Utils_Type::T_STRING,
bed98343 650 ),
a130e045 651 );
3c151c70 652
6a488035 653 $contributionNote = array(
a130e045
DG
654 'contribution_note' => array(
655 'title' => ts('Contribution Note'),
656 'name' => 'contribution_note',
657 'data_type' => CRM_Utils_Type::T_TEXT,
658 ),
6a488035
TO
659 );
660
661 $contributionRecurId = array(
9d72cede 662 'contribution_recur_id' => array(
6a488035
TO
663 'title' => ts('Recurring Contributions ID'),
664 'name' => 'contribution_recur_id',
665 'where' => 'civicrm_contribution.contribution_recur_id',
21dfd5f5
TO
666 'data_type' => CRM_Utils_Type::T_INT,
667 ),
f2b2a3ff 668 );
6a488035
TO
669
670 $extraFields = array(
82a43d71 671 'contribution_batch' => array(
21dfd5f5
TO
672 'title' => ts('Batch Name'),
673 ),
6a488035
TO
674 );
675
81ec6180
DS
676 $softCreditFields = array(
677 'contribution_soft_credit_name' => array(
678 'name' => 'contribution_soft_credit_name',
679 'title' => 'Soft Credit For',
680 'where' => 'civicrm_contact_d.display_name',
21dfd5f5 681 'data_type' => CRM_Utils_Type::T_STRING,
81ec6180
DS
682 ),
683 'contribution_soft_credit_amount' => array(
684 'name' => 'contribution_soft_credit_amount',
685 'title' => 'Soft Credit Amount',
686 'where' => 'civicrm_contribution_soft.amount',
21dfd5f5 687 'data_type' => CRM_Utils_Type::T_MONEY,
81ec6180
DS
688 ),
689 'contribution_soft_credit_type' => array(
690 'name' => 'contribution_soft_credit_type',
691 'title' => 'Soft Credit Type',
692 'where' => 'contribution_softcredit_type.label',
21dfd5f5 693 'data_type' => CRM_Utils_Type::T_STRING,
81ec6180
DS
694 ),
695 'contribution_soft_credit_contribution_id' => array(
696 'name' => 'contribution_soft_credit_contribution_id',
697 'title' => 'Soft Credit For Contribution ID',
698 'where' => 'civicrm_contribution_soft.contribution_id',
21dfd5f5 699 'data_type' => CRM_Utils_Type::T_INT,
81ec6180
DS
700 ),
701 );
702
3c151c70 703 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
81ec6180 704 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
6a488035
TO
705 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')
706 );
707
708 self::$_exportableFields = $fields;
709 }
710
711 return self::$_exportableFields;
712 }
713
186c9c17
EM
714 /**
715 * @param null $status
716 * @param null $startDate
717 * @param null $endDate
718 *
719 * @return array|null
720 */
00be9182 721 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
6a488035
TO
722 $where = array();
723 switch ($status) {
724 case 'Valid':
725 $where[] = 'contribution_status_id = 1';
726 break;
727
728 case 'Cancelled':
729 $where[] = 'contribution_status_id = 3';
730 break;
731 }
732
733 if ($startDate) {
734 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
735 }
736 if ($endDate) {
737 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
738 }
739
740 $whereCond = implode(' AND ', $where);
741
742 $query = "
743 SELECT sum( total_amount ) as total_amount,
744 count( civicrm_contribution.id ) as total_count,
745 currency
746 FROM civicrm_contribution
747INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
748 WHERE $whereCond
749 AND ( is_test = 0 OR is_test IS NULL )
750 AND contact.is_deleted = 0
751 GROUP BY currency
752";
753
f2b2a3ff 754 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
6a488035 755 $amount = array();
f2b2a3ff 756 $count = 0;
6a488035
TO
757 while ($dao->fetch()) {
758 $count += $dao->total_count;
759 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
760 }
761 if ($count) {
f2b2a3ff
TO
762 return array(
763 'amount' => implode(', ', $amount),
6a488035
TO
764 'count' => $count,
765 );
766 }
767 return NULL;
768 }
769
770 /**
771 * Delete the indirect records associated with this contribution first
772 *
100fef9d 773 * @param int $id
8efea814 774 *
72b3a70c
CW
775 * @return mixed|null
776 * $results no of deleted Contribution on success, false otherwise
6a488035 777 */
00be9182 778 public static function deleteContribution($id) {
6a488035
TO
779 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
780
781 $transaction = new CRM_Core_Transaction();
782
783 $results = NULL;
784 //delete activity record
785 $params = array(
786 'source_record_id' => $id,
787 // activity type id for contribution
788 'activity_type_id' => 6,
789 );
790
791 CRM_Activity_BAO_Activity::deleteActivity($params);
792
793 //delete billing address if exists for this contribution.
794 self::deleteAddress($id);
795
796 //update pledge and pledge payment, CRM-3961
797 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
798
799 // remove entry from civicrm_price_set_entity, CRM-5095
9da8dc8c 800 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
801 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
6a488035
TO
802 }
803 // cleanup line items.
804 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
805
de1c25e1
PN
806 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
807 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
6a488035
TO
808
809 if ($participantId) {
810 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
811 }
812 else {
813 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
814 }
815
816 //delete note.
817 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
818 $noteId = key($note);
819 if ($noteId) {
820 CRM_Core_BAO_Note::del($noteId, FALSE);
821 }
822
823 $dao = new CRM_Contribute_DAO_Contribution();
824 $dao->id = $id;
825
826 $results = $dao->delete();
827
828 $transaction->commit();
829
830 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
831
832 // delete the recently created Contribution
833 $contributionRecent = array(
834 'id' => $id,
835 'type' => 'Contribution',
836 );
837 CRM_Utils_Recent::del($contributionRecent);
838
839 return $results;
840 }
841
842 /**
843 * Check if there is a contribution with the same trxn_id or invoice_id
844 *
014c4014
TO
845 * @param array $input
846 * An assoc array of name/value pairs.
847 * @param array $duplicates
16b10e64 848 * (reference) store ids of duplicate contribs.
100fef9d 849 * @param int $id
6a488035 850 *
a130e045 851 * @return bool
a6c01b45 852 * true if duplicate, false otherwise
6a488035 853 */
00be9182 854 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
6a488035
TO
855 if (!$id) {
856 $id = CRM_Utils_Array::value('id', $input);
857 }
858 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
859 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
860
861 $clause = array();
862 $input = array();
863
864 if ($trxn_id) {
865 $clause[] = "trxn_id = %1";
866 $input[1] = array($trxn_id, 'String');
867 }
868
869 if ($invoice_id) {
870 $clause[] = "invoice_id = %2";
871 $input[2] = array($invoice_id, 'String');
872 }
873
874 if (empty($clause)) {
875 return FALSE;
876 }
877
878 $clause = implode(' OR ', $clause);
879 if ($id) {
880 $clause = "( $clause ) AND id != %3";
881 $input[3] = array($id, 'Integer');
882 }
883
f2b2a3ff
TO
884 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
885 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
886 $result = FALSE;
887 while ($dao->fetch()) {
888 $duplicates[] = $dao->id;
889 $result = TRUE;
890 }
891 return $result;
892 }
893
894 /**
100fef9d 895 * Takes an associative array and creates a contribution_product object
6a488035
TO
896 *
897 * the function extract all the params it needs to initialize the create a
898 * contribution_product object. the params array could contain additional unused name/value
899 * pairs
900 *
014c4014 901 * @param array $params
16b10e64 902 * (reference) an assoc array of name/value pairs.
6a488035 903 *
16b10e64 904 * @return CRM_Contribute_DAO_ContributionProduct
6a488035 905 */
00be9182 906 public static function addPremium(&$params) {
6a488035
TO
907 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
908 $contributionProduct->copyValues($params);
909 return $contributionProduct->save();
910 }
911
912 /**
100fef9d 913 * Get list of contribution fields for profile
6a488035
TO
914 * For now we only allow custom contribution fields to be in
915 * profile
916 *
014c4014
TO
917 * @param bool $addExtraFields
918 * True if special fields needs to be added.
6a488035 919 *
a6c01b45
CW
920 * @return array
921 * the list of contribution fields
6a488035 922 */
00be9182 923 public static function getContributionFields($addExtraFields = TRUE) {
6a488035
TO
924 $contributionFields = CRM_Contribute_DAO_Contribution::export();
925 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
926
927 if ($addExtraFields) {
928 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
929 }
930
931 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
932
933 foreach ($contributionFields as $key => $var) {
934 if ($key == 'contribution_contact_id') {
935 continue;
936 }
937 elseif ($key == 'contribution_campaign_id') {
938 $var['title'] = ts('Campaign');
939 }
940 $fields[$key] = $var;
941 }
942
943 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
944 return $fields;
945 }
946
947 /**
100fef9d 948 * Add extra fields specific to contribtion
6a488035 949 *
6a488035 950 */
00be9182 951 public static function getSpecialContributionFields() {
6a488035 952 $extraFields = array(
81ec6180
DS
953 'contribution_soft_credit_name' => array(
954 'name' => 'contribution_soft_credit_name',
6a488035
TO
955 'title' => 'Soft Credit Name',
956 'headerPattern' => '/^soft_credit_name$/i',
957 'where' => 'civicrm_contact_d.display_name',
958 ),
81ec6180
DS
959 'contribution_soft_credit_email' => array(
960 'name' => 'contribution_soft_credit_email',
6a488035
TO
961 'title' => 'Soft Credit Email',
962 'headerPattern' => '/^soft_credit_email$/i',
963 'where' => 'soft_email.email',
964 ),
81ec6180
DS
965 'contribution_soft_credit_phone' => array(
966 'name' => 'contribution_soft_credit_phone',
6a488035
TO
967 'title' => 'Soft Credit Phone',
968 'headerPattern' => '/^soft_credit_phone$/i',
969 'where' => 'soft_phone.phone',
970 ),
81ec6180
DS
971 'contribution_soft_credit_contact_id' => array(
972 'name' => 'contribution_soft_credit_contact_id',
6a488035
TO
973 'title' => 'Soft Credit Contact ID',
974 'headerPattern' => '/^soft_credit_contact_id$/i',
975 'where' => 'civicrm_contribution_soft.contact_id',
976 ),
977 );
978
979 return $extraFields;
980 }
981
186c9c17 982 /**
100fef9d 983 * @param int $pageID
186c9c17
EM
984 *
985 * @return array
986 */
00be9182 987 public static function getCurrentandGoalAmount($pageID) {
6a488035
TO
988 $query = "
989SELECT p.goal_amount as goal, sum( c.total_amount ) as total
990 FROM civicrm_contribution_page p,
991 civicrm_contribution c
992 WHERE p.id = c.contribution_page_id
993 AND p.id = %1
994 AND c.cancel_date is null
995GROUP BY p.id
996";
997
998 $config = CRM_Core_Config::singleton();
999 $params = array(1 => array($pageID, 'Integer'));
f2b2a3ff 1000 $dao = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
1001
1002 if ($dao->fetch()) {
1003 return array($dao->goal, $dao->total);
1004 }
1005 else {
1006 return array(NULL, NULL);
1007 }
1008 }
1009
6a488035 1010 /**
100fef9d 1011 * Get list of contribution In Honor of contact Ids
6a488035 1012 *
014c4014
TO
1013 * @param int $honorId
1014 * In Honor of Contact ID.
6a488035 1015 *
72b3a70c
CW
1016 * @return array
1017 * list of contribution fields
6a488035 1018 *
6a488035 1019 */
00be9182 1020 public static function getHonorContacts($honorId) {
6a488035 1021 $params = array();
8381af80 1022 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1023 $honorDAO->contact_id = $honorId;
6a488035
TO
1024 $honorDAO->find();
1025
6a488035
TO
1026 $type = CRM_Contribute_PseudoConstant::financialType();
1027
1028 while ($honorDAO->fetch()) {
8381af80 1029 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1030 $contributionDAO->id = $honorDAO->contribution_id;
1031
1032 if ($contributionDAO->find(TRUE)) {
1033 $params[$contributionDAO->id]['honor_type'] = CRM_Core_OptionGroup::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id, 'value');
1034 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1035 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1036 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1037 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1038 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1039 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1040 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1041 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
1042 }
6a488035
TO
1043 }
1044
1045 return $params;
1046 }
1047
1048 /**
100fef9d 1049 * Get the sort name of a contact for a particular contribution
6a488035 1050 *
014c4014
TO
1051 * @param int $id
1052 * Id of the contribution.
6a488035 1053 *
72b3a70c
CW
1054 * @return null|string
1055 * sort name of the contact if found
6a488035 1056 */
00be9182 1057 public static function sortName($id) {
6a488035
TO
1058 $id = CRM_Utils_Type::escape($id, 'Integer');
1059
1060 $query = "
1061SELECT civicrm_contact.sort_name
1062FROM civicrm_contribution, civicrm_contact
1063WHERE civicrm_contribution.contact_id = civicrm_contact.id
1064 AND civicrm_contribution.id = {$id}
1065";
1066 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1067 }
1068
186c9c17 1069 /**
100fef9d 1070 * @param int $contactID
186c9c17
EM
1071 *
1072 * @return array
1073 */
00be9182 1074 public static function annual($contactID) {
6a488035
TO
1075 if (is_array($contactID)) {
1076 $contactIDs = implode(',', $contactID);
1077 }
1078 else {
1079 $contactIDs = $contactID;
1080 }
1081
1082 $config = CRM_Core_Config::singleton();
1083 $startDate = $endDate = NULL;
1084
1085 $currentMonth = date('m');
1086 $currentDay = date('d');
1087 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1088 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1089 (int ) $config->fiscalYearStart['d'] > $currentDay
1090 )
1091 ) {
1092 $year = date('Y') - 1;
1093 }
1094 else {
1095 $year = date('Y');
1096 }
1097 $nextYear = $year + 1;
1098
1099 if ($config->fiscalYearStart) {
1100 if ($config->fiscalYearStart['M'] < 10) {
1101 $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M'];
1102 }
1103 if ($config->fiscalYearStart['d'] < 10) {
1104 $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d'];
1105 }
1106 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1107 }
1108 else {
1109 $monthDay = '0101';
1110 }
1111 $startDate = "$year$monthDay";
1112 $endDate = "$nextYear$monthDay";
1113
1114 $query = "
1115 SELECT count(*) as count,
1116 sum(total_amount) as amount,
1117 avg(total_amount) as average,
1118 currency
1119 FROM civicrm_contribution b
1120 WHERE b.contact_id IN ( $contactIDs )
1121 AND b.contribution_status_id = 1
1122 AND b.is_test = 0
1123 AND b.receive_date >= $startDate
1124 AND b.receive_date < $endDate
1125 GROUP BY currency
1126 ";
f2b2a3ff
TO
1127 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1128 $count = 0;
6a488035
TO
1129 $amount = $average = array();
1130 while ($dao->fetch()) {
1131 if ($dao->count > 0 && $dao->amount > 0) {
1132 $count += $dao->count;
1133 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1134 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1135 }
1136 }
1137 if ($count > 0) {
1138 return array(
1139 $count,
1140 implode(',&nbsp;', $amount),
1141 implode(',&nbsp;', $average),
1142 );
1143 }
1144 return array(0, 0, 0);
1145 }
1146
1147 /**
1148 * Check if there is a contribution with the params passed in.
1149 * Used for trxn_id,invoice_id and contribution_id
1150 *
014c4014
TO
1151 * @param array $params
1152 * An assoc array of name/value pairs.
6a488035 1153 *
a6c01b45
CW
1154 * @return array
1155 * contribution id if success else NULL
6a488035 1156 */
00be9182 1157 public static function checkDuplicateIds($params) {
6a488035
TO
1158 $dao = new CRM_Contribute_DAO_Contribution();
1159
1160 $clause = array();
1161 $input = array();
1162 foreach ($params as $k => $v) {
1163 if ($v) {
1164 $clause[] = "$k = '$v'";
1165 }
1166 }
1167 $clause = implode(' AND ', $clause);
f2b2a3ff
TO
1168 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1169 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
1170
1171 while ($dao->fetch()) {
1172 $result = $dao->id;
1173 return $result;
1174 }
1175 return NULL;
1176 }
1177
1178 /**
100fef9d 1179 * Get the contribution details for component export
6a488035 1180 *
014c4014
TO
1181 * @param int $exportMode
1182 * Export mode.
1183 * @param string $componentIds
1184 * Component ids.
6a488035 1185 *
a6c01b45
CW
1186 * @return array
1187 * associated array
6a488035 1188 *
6a488035 1189 */
00be9182 1190 public static function getContributionDetails($exportMode, $componentIds) {
6a488035
TO
1191 $paymentDetails = array();
1192 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1193
1194 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1195 $componentSelect = " civicrm_participant_payment.participant_id id";
1196 $additionalClause = "
1197INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1198AND civicrm_participant_payment.participant_id {$componentClause} )
1199";
1200 }
1201 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1202 $componentSelect = " civicrm_membership_payment.membership_id id";
1203 $additionalClause = "
1204INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1205AND civicrm_membership_payment.membership_id {$componentClause} )
1206";
1207 }
1208 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1209 $componentSelect = " civicrm_pledge_payment.id id";
1210 $additionalClause = "
1211INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1212AND civicrm_pledge_payment.pledge_id {$componentClause} )
1213";
1214 }
1215
1216 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1217 trxn_id, {$componentSelect}
1218FROM civicrm_contribution
1219LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1220LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1221 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1222LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1223LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1224 AND option_group_contribution_status.id = contribution_status.option_group_id )
1225{$additionalClause}
1226";
1227
1228 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1229
1230 while ($dao->fetch()) {
1231 $paymentDetails[$dao->id] = array(
1232 'total_amount' => $dao->total_amount,
1233 'contribution_status' => $dao->status,
1234 'receive_date' => $dao->receive_date,
1235 'pay_instru' => $dao->payment_instrument,
1236 'trxn_id' => $dao->trxn_id,
1237 );
1238 }
1239
1240 return $paymentDetails;
1241 }
1242
1243 /**
c490a46a 1244 * Create address associated with contribution record.
6a488035 1245 *
014c4014 1246 * @param array $params
c490a46a 1247 * @param int $billingLocationTypeID
fd31fa4c 1248 *
72b3a70c
CW
1249 * @return int
1250 * address id
6a488035 1251 */
00be9182 1252 public static function createAddress(&$params, $billingLocationTypeID) {
6a488035
TO
1253 $billingFields = array(
1254 'street_address',
1255 'city',
1256 'state_province_id',
1257 'postal_code',
1258 'country_id',
1259 );
1260
1261 //build address array
1262 $addressParams = array();
1263 $addressParams['location_type_id'] = $billingLocationTypeID;
1264 $addressParams['is_billing'] = 1;
3fb990f4
RN
1265
1266 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
1267 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
1268 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
1269 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
6a488035
TO
1270
1271 foreach ($billingFields as $value) {
3fb990f4 1272 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
6a488035
TO
1273 }
1274
1275 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1276
1277 return $address->id;
1278 }
1279
6a488035
TO
1280 /**
1281 * Delete billing address record related contribution
1282 *
c490a46a
CW
1283 * @param int $contributionId
1284 * @param int $contactId
77b97be7 1285 *
6a488035 1286 */
00be9182 1287 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
6a488035
TO
1288 $clauses = array();
1289 $contactJoin = NULL;
1290
1291 if ($contributionId) {
1292 $clauses[] = "cc.id = {$contributionId}";
1293 }
1294
1295 if ($contactId) {
1296 $clauses[] = "cco.id = {$contactId}";
1297 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1298 }
1299
1300 if (empty($clauses)) {
1301 CRM_Core_Error::fatal();
1302 }
1303
1304 $condition = implode(' OR ', $clauses);
1305
1306 $query = "
1307SELECT ca.id
1308FROM civicrm_address ca
1309INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1310 $contactJoin
1311WHERE $condition
1312";
1313 $dao = CRM_Core_DAO::executeQuery($query);
1314
1315 while ($dao->fetch()) {
1316 $params = array('id' => $dao->id);
1317 CRM_Core_BAO_Block::blockDelete('Address', $params);
1318 }
1319 }
1320
1321 /**
1322 * This function check online pending contribution associated w/
1323 * Online Event Registration or Online Membership signup.
1324 *
014c4014
TO
1325 * @param int $componentId
1326 * Participant/membership id.
1327 * @param string $componentName
1328 * Event/Membership.
6a488035 1329 *
16b10e64
CW
1330 * @return int
1331 * pending contribution id.
6a488035 1332 */
00be9182 1333 public static function checkOnlinePendingContribution($componentId, $componentName) {
6a488035
TO
1334 $contributionId = NULL;
1335 if (!$componentId ||
1336 !in_array($componentName, array('Event', 'Membership'))
1337 ) {
1338 return $contributionId;
1339 }
1340
1341 if ($componentName == 'Event') {
f2b2a3ff 1342 $idName = 'participant_id';
6a488035 1343 $componentTable = 'civicrm_participant';
f2b2a3ff
TO
1344 $paymentTable = 'civicrm_participant_payment';
1345 $source = ts('Online Event Registration');
6a488035
TO
1346 }
1347
1348 if ($componentName == 'Membership') {
f2b2a3ff 1349 $idName = 'membership_id';
6a488035 1350 $componentTable = 'civicrm_membership';
f2b2a3ff
TO
1351 $paymentTable = 'civicrm_membership_payment';
1352 $source = ts('Online Contribution');
6a488035
TO
1353 }
1354
1355 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1356
1357 $query = "
1358 SELECT component.id as {$idName},
1359 componentPayment.contribution_id as contribution_id,
1360 contribution.source source,
1361 contribution.contribution_status_id as contribution_status_id,
1362 contribution.is_pay_later as is_pay_later
1363 FROM $componentTable component
1364LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1365LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1366 WHERE component.id = {$componentId}";
1367
1368 $dao = CRM_Core_DAO::executeQuery($query);
1369
1370 while ($dao->fetch()) {
1371 if ($dao->contribution_id &&
1372 $dao->is_pay_later &&
1373 $dao->contribution_status_id == $pendingStatusId &&
1374 strpos($dao->source, $source) !== FALSE
1375 ) {
1376 $contributionId = $dao->contribution_id;
1377 $dao->free();
1378 }
1379 }
1380
1381 return $contributionId;
1382 }
1383
1384 /**
16b10e64 1385 * Update contribution as well as related objects.
6a488035 1386 */
00be9182 1387 public static function transitionComponents($params, $processContributionObject = FALSE) {
6a488035
TO
1388 // get minimum required values.
1389 $contactId = CRM_Utils_Array::value('contact_id', $params);
1390 $componentId = CRM_Utils_Array::value('component_id', $params);
1391 $componentName = CRM_Utils_Array::value('componentName', $params);
1392 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1393 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1394
1395 // if we already processed contribution object pass previous status id.
1396 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1397
1398 $updateResult = array();
1399
1400 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1401
1402 // we process only ( Completed, Cancelled, or Failed ) contributions.
1403 if (!$contributionId ||
f2b2a3ff
TO
1404 !in_array($contributionStatusId, array(
1405 array_search('Completed', $contributionStatuses),
1406 array_search('Cancelled', $contributionStatuses),
1407 array_search('Failed', $contributionStatuses),
1408 ))
6a488035
TO
1409 ) {
1410 return $updateResult;
1411 }
1412
1413 if (!$componentName || !$componentId) {
1414 // get the related component details.
1415 $componentDetails = self::getComponentDetails($contributionId);
1416 }
1417 else {
1418 $componentDetails['contact_id'] = $contactId;
1419 $componentDetails['component'] = $componentName;
1420
1421 if ($componentName == 'event') {
1422 $componentDetails['participant'] = $componentId;
1423 }
1424 else {
1425 $componentDetails['membership'] = $componentId;
1426 }
1427 }
1428
a7488080 1429 if (!empty($componentDetails['contact_id'])) {
6a488035
TO
1430 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1431 $contributionId,
1432 'contact_id'
1433 );
1434 }
1435
1436 // do check for required ids.
8cc574cf 1437 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
6a488035
TO
1438 return $updateResult;
1439 }
1440
1441 //now we are ready w/ required ids, start processing.
1442
1443 $baseIPN = new CRM_Core_Payment_BaseIPN();
1444
1445 $input = $ids = $objects = array();
1446
1447 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1448 $ids['contribution'] = $contributionId;
1449 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1450 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1451 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1452 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1453 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1454 $ids['contributionRecur'] = NULL;
1455 $ids['contributionPage'] = NULL;
1456
1457 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1458 CRM_Core_Error::fatal();
1459 }
1460
f2b2a3ff
TO
1461 $memberships = &$objects['membership'];
1462 $participant = &$objects['participant'];
6a488035 1463 $pledgePayment = &$objects['pledge_payment'];
f2b2a3ff 1464 $contribution = &$objects['contribution'];
6a488035
TO
1465
1466 if ($pledgePayment) {
1467 $pledgePaymentIDs = array();
1468 foreach ($pledgePayment as $key => $object) {
1469 $pledgePaymentIDs[] = $object->id;
1470 }
1471 $pledgeID = $pledgePayment[0]->pledge_id;
1472 }
1473
6a488035
TO
1474 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1475
1476 if ($participant) {
1477 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1478 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1479 $participant->id,
1480 'status_id'
1481 );
1482 }
1483 // we might want to process contribution object.
1484 $processContribution = FALSE;
1485 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1486 if (is_array($memberships)) {
1487 foreach ($memberships as $membership) {
1488 if ($membership) {
1489 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1490 $membership->save();
1491
1492 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1493 if ($processContributionObject) {
1494 $processContribution = TRUE;
1495 }
1496 }
1497 }
1498 }
1499
1500 if ($participant) {
1501 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1502 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1503
1504 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1505 if ($processContributionObject) {
1506 $processContribution = TRUE;
1507 }
1508 }
1509
1510 if ($pledgePayment) {
1511 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1512
1513 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1514 if ($processContributionObject) {
1515 $processContribution = TRUE;
1516 }
1517 }
1518 }
1519 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1520 if (is_array($memberships)) {
1521 foreach ($memberships as $membership) {
1522 if ($membership) {
1523 $membership->status_id = array_search('Expired', $membershipStatuses);
1524 $membership->save();
1525
1526 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1527 if ($processContributionObject) {
1528 $processContribution = TRUE;
1529 }
1530 }
1531 }
1532 }
1533 if ($participant) {
1534 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1535 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1536
1537 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1538 if ($processContributionObject) {
1539 $processContribution = TRUE;
1540 }
1541 }
1542
1543 if ($pledgePayment) {
1544 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1545
1546 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1547 if ($processContributionObject) {
1548 $processContribution = TRUE;
1549 }
1550 }
1551 }
1552 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1553
1554 // only pending contribution related object processed.
1555 if ($previousContriStatusId &&
1556 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1557 ) {
1558 // this is case when we already processed contribution object.
1559 return $updateResult;
1560 }
1561 elseif (!$previousContriStatusId &&
1562 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1563 ) {
1564 // this is case when we are going to process contribution object later.
1565 return $updateResult;
1566 }
1567
1568 if (is_array($memberships)) {
1569 foreach ($memberships as $membership) {
1570 if ($membership) {
1571 $format = '%Y%m%d';
1572
1573 //CRM-4523
1574 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1575 $membership->membership_type_id,
1576 $membership->is_test, $membership->id
1577 );
1578
1579 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1580 // this picks up membership type changes during renewals
1581 $sql = "
1582 SELECT membership_type_id
1583 FROM civicrm_membership_log
1584 WHERE membership_id=$membership->id
1585 ORDER BY id DESC
1586 LIMIT 1;";
a130e045 1587 $dao = new CRM_Core_DAO();
6a488035
TO
1588 $dao->query($sql);
1589 if ($dao->fetch()) {
1590 if (!empty($dao->membership_type_id)) {
1591 $membership->membership_type_id = $dao->membership_type_id;
1592 $membership->save();
1593 }
1594 }
1595 // else fall back to using current membership type
1596 $dao->free();
1597
9c09f5b7
AH
1598 // Figure out number of terms
1599 $numterms = 1;
1600 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1601 foreach ($lineitems as $lineitem) {
1602 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1603 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
2d77a516 1604
9c09f5b7
AH
1605 // in case membership_num_terms comes through as null or zero
1606 $numterms = $numterms >= 1 ? $numterms : 1;
1607 break;
1608 }
1609 }
1610
e8c64fab 1611 // CRM-15735-to update the membership status as per the contribution receive date
1612 if (!empty($params['receive_date'])) {
1613 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1614 $membership->end_date,
1615 $membership->join_date,
1616 $params['receive_date'],
1617 FALSE,
1618 $membership->membership_type_id,
1619 (array) $membership
1620 );
1621 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1622 $membership->save();
1623 }
1624
6a488035 1625 if ($currentMembership) {
9c09f5b7
AH
1626 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1627 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
6a488035
TO
1628 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1629 }
1630 else {
c2585c5b 1631 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
6a488035
TO
1632 }
1633
1634 //get the status for membership.
1635 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1636 $dates['end_date'],
1637 $dates['join_date'],
1638 'today',
5f11bbcc
EM
1639 TRUE,
1640 $membership->membership_type_id,
1641 (array) $membership
6a488035
TO
1642 );
1643
c2585c5b 1644 $formattedParams = array(
6a488035
TO
1645 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1646 array_search('Current', $membershipStatuses)
1647 ),
1648 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1649 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1650 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1651 );
1652
c2585c5b 1653 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
6a488035 1654
c2585c5b 1655 $membership->copyValues($formattedParams);
6a488035
TO
1656 $membership->save();
1657
1658 //updating the membership log
1659 $membershipLog = array();
c2585c5b 1660 $membershipLog = $formattedParams;
f2b2a3ff
TO
1661 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1662 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
6a488035
TO
1663
1664 $membershipLog['start_date'] = $logStartDate;
1665 $membershipLog['membership_id'] = $membership->id;
1666 $membershipLog['modified_id'] = $membership->contact_id;
1667 $membershipLog['modified_date'] = date('Ymd');
1668 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1669
1670 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1671
1672 //update related Memberships.
c2585c5b 1673 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
6a488035
TO
1674
1675 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1676 '%B %E%f, %Y'
1677 );
1678 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1679 if ($processContributionObject) {
1680 $processContribution = TRUE;
1681 }
1682
1683 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1684 }
1685 }
1686 }
1687
1688 if ($participant) {
1689 $updatedStatusId = array_search('Registered', $participantStatuses);
1690 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1691
1692 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1693 if ($processContributionObject) {
1694 $processContribution = TRUE;
1695 }
1696 }
1697
1698 if ($pledgePayment) {
1699 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1700
1701 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1702 if ($processContributionObject) {
1703 $processContribution = TRUE;
1704 }
1705 }
1706 }
1707
1708 // process contribution object.
1709 if ($processContribution) {
1710 $contributionParams = array();
1711 $fields = array(
f2b2a3ff
TO
1712 'contact_id',
1713 'total_amount',
1714 'receive_date',
1715 'is_test',
1716 'campaign_id',
1717 'payment_instrument_id',
1718 'trxn_id',
1719 'invoice_id',
1720 'financial_type_id',
1721 'contribution_status_id',
1722 'non_deductible_amount',
1723 'receipt_date',
1724 'check_number',
6a488035
TO
1725 );
1726 foreach ($fields as $field) {
a7488080 1727 if (empty($params[$field])) {
6a488035
TO
1728 continue;
1729 }
1730 $contributionParams[$field] = $params[$field];
1731 }
1732
1733 $ids = array('contribution' => $contributionId);
1734 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1735 }
1736
1737 return $updateResult;
1738 }
1739
1740 /**
16b10e64 1741 * Returns all contribution related object ids.
7a9ab499
EM
1742 *
1743 * @param $contributionId
1744 *
1745 * @return array
6a488035 1746 */
291ca04f 1747 public static function getComponentDetails($contributionId) {
6a488035
TO
1748 $componentDetails = $pledgePayment = array();
1749 if (!$contributionId) {
1750 return $componentDetails;
1751 }
1752
1753 $query = "
1754 SELECT c.id as contribution_id,
1755 c.contact_id as contact_id,
1756 mp.membership_id as membership_id,
1757 m.membership_type_id as membership_type_id,
1758 pp.participant_id as participant_id,
1759 p.event_id as event_id,
1760 pgp.id as pledge_payment_id
1761 FROM civicrm_contribution c
1762 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1763 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1764 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1765 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1766 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1767 WHERE c.id = $contributionId";
1768
1769 $dao = CRM_Core_DAO::executeQuery($query);
1770 $componentDetails = array();
1771
1772 while ($dao->fetch()) {
1773 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1774 $componentDetails['contact_id'] = $dao->contact_id;
1775 if ($dao->event_id) {
1776 $componentDetails['event'] = $dao->event_id;
1777 }
1778 if ($dao->participant_id) {
1779 $componentDetails['participant'] = $dao->participant_id;
1780 }
1781 if ($dao->membership_id) {
1782 if (!isset($componentDetails['membership'])) {
1783 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1784 }
1785 $componentDetails['membership'][] = $dao->membership_id;
1786 $componentDetails['membership_type'][] = $dao->membership_type_id;
1787 }
1788 if ($dao->pledge_payment_id) {
1789 $pledgePayment[] = $dao->pledge_payment_id;
1790 }
1791 }
1792
1793 if ($pledgePayment) {
1794 $componentDetails['pledge_payment'] = $pledgePayment;
1795 }
1796
1797 return $componentDetails;
1798 }
1799
186c9c17 1800 /**
100fef9d 1801 * @param int $contactId
186c9c17
EM
1802 * @param bool $includeSoftCredit
1803 *
1804 * @return null|string
1805 */
00be9182 1806 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
6a488035
TO
1807 if (!$contactId) {
1808 return 0;
1809 }
1810
bbde790f
RN
1811 $contactContributionsSQL = "
1812 SELECT contribution.id AS id
1813 FROM civicrm_contribution contribution
1814 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1815
bbde790f
RN
1816 $contactSoftCreditContributionsSQL = "
1817 SELECT contribution.id
1818 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1819 ON ( contribution.id = softContribution.contribution_id )
1820 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1821 $query = "SELECT count( x.id ) count FROM ( ";
1822 $query .= $contactContributionsSQL;
1823
6a488035 1824 if ($includeSoftCredit) {
bbde790f
RN
1825 $query .= " UNION ";
1826 $query .= $contactSoftCreditContributionsSQL;
6a488035 1827 }
bbde790f 1828
bbde790f 1829 $query .= ") x";
6a488035
TO
1830
1831 return CRM_Core_DAO::singleValueQuery($query);
1832 }
1833
1834 /**
100fef9d 1835 * Get individual id for onbehalf contribution
6a488035 1836 *
014c4014
TO
1837 * @param int $contributionId
1838 * Contribution id.
1839 * @param int $contributorId
1840 * Contributor id.
6a488035 1841 *
a6c01b45
CW
1842 * @return array
1843 * containing organization id and individual id
6a488035 1844 */
00be9182 1845 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
6a488035
TO
1846
1847 $ids = array();
1848
1849 if (!$contributionId) {
1850 return $ids;
1851 }
1852
1853 // fetch contributor id if null
1854 if (!$contributorId) {
1855 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1856 $contributionId, 'contact_id'
1857 );
1858 }
1859
1860 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1861 $activityTypeId = array_search('Contribution', $activityTypeIds);
1862
1863 if ($activityTypeId && $contributorId) {
1864 $activityQuery = "
2d77a516
DL
1865SELECT civicrm_activity_contact.contact_id
1866 FROM civicrm_activity_contact
1867INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1868 WHERE civicrm_activity.activity_type_id = %1
1869 AND civicrm_activity.source_record_id = %2
1870 AND civicrm_activity_contact.record_type_id = %3
1871";
6a488035 1872
e7e657f0 1873 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2d77a516
DL
1874 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1875
1876 $params = array(
1877 1 => array($activityTypeId, 'Integer'),
6a488035 1878 2 => array($contributionId, 'Integer'),
2d77a516 1879 3 => array($sourceID, 'Integer'),
6a488035
TO
1880 );
1881
1882 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1883
1884 // for on behalf contribution source is individual and contributor is organization
1885 if ($sourceContactId && $sourceContactId != $contributorId) {
1886 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1887 // get rel type id for employee of relation
1888 foreach ($relationshipTypeIds as $id => $typeVals) {
1889 if ($typeVals['name_a_b'] == 'Employee of') {
1890 $relationshipTypeId = $id;
1891 break;
1892 }
1893 }
1894
1895 $rel = new CRM_Contact_DAO_Relationship();
1896 $rel->relationship_type_id = $relationshipTypeId;
1897 $rel->contact_id_a = $sourceContactId;
1898 $rel->contact_id_b = $contributorId;
1899 if ($rel->find(TRUE)) {
1900 $ids['individual_id'] = $rel->contact_id_a;
1901 $ids['organization_id'] = $rel->contact_id_b;
1902 }
1903 }
1904 }
1905
1906 return $ids;
1907 }
1908
1909 /**
1910 * @return array
6a488035 1911 */
00be9182 1912 public static function getContributionDates() {
f2b2a3ff 1913 $config = CRM_Core_Config::singleton();
6a488035 1914 $currentMonth = date('m');
f2b2a3ff 1915 $currentDay = date('d');
6a488035
TO
1916 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1917 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1918 (int ) $config->fiscalYearStart['d'] > $currentDay
1919 )
1920 ) {
1921 $year = date('Y') - 1;
1922 }
1923 else {
1924 $year = date('Y');
1925 }
f2b2a3ff 1926 $year = array('Y' => $year);
6a488035
TO
1927 $yearDate = $config->fiscalYearStart;
1928 $yearDate = array_merge($year, $yearDate);
1929 $yearDate = CRM_Utils_Date::format($yearDate);
1930
1931 $monthDate = date('Ym') . '01';
1932
1933 $now = date('Ymd');
1934
1935 return array(
1936 'now' => $now,
1937 'yearDate' => $yearDate,
1938 'monthDate' => $monthDate,
1939 );
1940 }
1941
16b10e64 1942 /**
6a488035
TO
1943 * Load objects relations to contribution object
1944 * Objects are stored in the $_relatedObjects property
1945 * In the first instance we are just moving functionality from BASEIpn -
16b10e64
CW
1946 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1947 *
1948 * Note that the unit test for the BaseIPN class tests this function
6a488035 1949 *
014c4014
TO
1950 * @param array $input
1951 * Input as delivered from Payment Processor.
1952 * @param array $ids
1953 * Ids as Loaded by Payment Processor.
1954 * @param bool $required
1955 * Is Payment processor / contribution page required.
1956 * @param bool $loadAll
1957 * Load all related objects - even where id not passed in? (allows API to call this).
186c9c17
EM
1958 *
1959 * @return bool
1960 * @throws Exception
1961 */
f2b2a3ff
TO
1962 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1963 if ($loadAll) {
1964 $ids = array_merge($this->getComponentDetails($this->id), $ids);
1965 if (empty($ids['contact']) && isset($this->contact_id)) {
6a488035
TO
1966 $ids['contact'] = $this->contact_id;
1967 }
1968 }
1969 if (empty($this->_component)) {
f2b2a3ff 1970 if (!empty($ids['event'])) {
6a488035
TO
1971 $this->_component = 'event';
1972 }
1973 else {
1974 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
1975 }
1976 }
1977 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
1978 $contributionType = new CRM_Financial_BAO_FinancialType();
1979 $contributionType->id = $this->financial_type_id;
1980 if (!$contributionType->find(TRUE)) {
1981 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
1982 }
1983 if (!empty($ids['contact'])) {
1984 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
1985 $this->_relatedObjects['contact']->id = $ids['contact'];
1986 $this->_relatedObjects['contact']->find(TRUE);
1987 }
1988 $this->_relatedObjects['contributionType'] = $contributionType;
1989
1990 if ($this->_component == 'contribute') {
1991 // retrieve the other optional objects first so
1992 // stuff down the line can use this info and do things
1993 // CRM-6056
1994 //in any case get the memberships associated with the contribution
1995 //because we now support multiple memberships w/ price set
f2b2a3ff
TO
1996 // see if there are any other memberships to be considered for same contribution.
1997 $query = "
6a488035
TO
1998 SELECT membership_id
1999 FROM civicrm_membership_payment
2000WHERE contribution_id = %1 ";
2001 $params = array(1 => array($this->id, 'Integer'));
2002
f2b2a3ff
TO
2003 $dao = CRM_Core_DAO::executeQuery($query, $params);
2004 while ($dao->fetch()) {
6a488035
TO
2005 if ($dao->membership_id) {
2006 if (!is_array($ids['membership'])) {
2007 $ids['membership'] = array();
2008 }
f2b2a3ff 2009 $ids['membership'][] = $dao->membership_id;
6a488035 2010 }
f2b2a3ff 2011 }
6a488035
TO
2012
2013 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
f2b2a3ff
TO
2014 foreach ($ids['membership'] as $id) {
2015 if (!empty($id)) {
2016 $membership = new CRM_Member_BAO_Membership();
2017 $membership->id = $id;
2018 if (!$membership->find(TRUE)) {
2019 throw new Exception("Could not find membership record: $id");
6a488035 2020 }
f2b2a3ff
TO
2021 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2022 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2023 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2024 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2025 $membership->free();
6a488035
TO
2026 }
2027 }
f2b2a3ff 2028 }
6a488035
TO
2029
2030 if (!empty($ids['pledge_payment'])) {
2031
2032 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2033 if (empty($paymentID)) {
2034 continue;
2035 }
2036 $payment = new CRM_Pledge_BAO_PledgePayment();
2037 $payment->id = $paymentID;
2038 if (!$payment->find(TRUE)) {
2039 throw new Exception("Could not find pledge payment record: " . $paymentID);
2040 }
2041 $this->_relatedObjects['pledge_payment'][] = $payment;
2042 }
2043 }
2044
2045 if (!empty($ids['contributionRecur'])) {
2046 $recur = new CRM_Contribute_BAO_ContributionRecur();
2047 $recur->id = $ids['contributionRecur'];
2048 if (!$recur->find(TRUE)) {
2049 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2050 }
2051 $this->_relatedObjects['contributionRecur'] = &$recur;
2052 //get payment processor id from recur object.
2053 $paymentProcessorID = $recur->payment_processor_id;
2054 }
2055 //for normal contribution get the payment processor id.
2056 if (!$paymentProcessorID) {
2057 if ($this->contribution_page_id) {
2058 // get the payment processor id from contribution page
2059 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2060 $this->contribution_page_id,
2061 'payment_processor'
2062 );
2063 }
2064 //fail to load payment processor id.
a7488080 2065 elseif (empty($ids['pledge_payment'])) {
6a488035
TO
2066 $loadObjectSuccess = TRUE;
2067 if ($required) {
2068 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
2069 }
2070 return $loadObjectSuccess;
2071 }
2072 }
2073 }
2074 else {
2075 // we are in event mode
2076 // make sure event exists and is valid
2077 $event = new CRM_Event_BAO_Event();
2078 $event->id = $ids['event'];
2079 if ($ids['event'] &&
2080 !$event->find(TRUE)
2081 ) {
2082 throw new Exception("Could not find event: " . $ids['event']);
2083 }
2084
2085 $this->_relatedObjects['event'] = &$event;
2086
2087 $participant = new CRM_Event_BAO_Participant();
2088 $participant->id = $ids['participant'];
2089 if ($ids['participant'] &&
2090 !$participant->find(TRUE)
2091 ) {
2092 throw new Exception("Could not find participant: " . $ids['participant']);
2093 }
2094 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2095
2096 $this->_relatedObjects['participant'] = &$participant;
2097
2098 if (!$paymentProcessorID) {
2099 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2100 }
2101 }
2102
6a488035
TO
2103 if ($paymentProcessorID) {
2104 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2105 $this->is_test ? 'test' : 'live'
2106 );
2107 $ids['paymentProcessor'] = $paymentProcessorID;
2108 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
2109 }
2110 elseif ($required) {
6a488035
TO
2111 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
2112 }
2113
5bfb071e 2114 return TRUE;
6a488035
TO
2115 }
2116
16b10e64 2117 /**
6a488035
TO
2118 * Create array of message information - ie. return html version, txt version, to field
2119 *
014c4014
TO
2120 * @param array $input
2121 * Incoming information.
16b10e64 2122 * - is_recur - should this be treated as recurring (not sure why you wouldn't
6a488035
TO
2123 * just check presence of recur object but maintaining legacy approach
2124 * to be careful)
014c4014
TO
2125 * @param array $ids
2126 * IDs of related objects.
2127 * @param array $values
2128 * Any values that may have already been compiled by calling process.
6a488035 2129 * This is augmented by values 'gathered' by gatherMessageValues
16b10e64 2130 * @param bool $recur
014c4014
TO
2131 * @param bool $returnMessageText
2132 * Distinguishes between whether to send message or return.
6a488035
TO
2133 * message text. We are working towards this function ALWAYS returning message text & calling
2134 * function doing emails / pdfs with it
16b10e64 2135 *
a6c01b45
CW
2136 * @return array
2137 * messages
186c9c17
EM
2138 * @throws Exception
2139 */
00be9182 2140 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
6a488035
TO
2141 if (empty($this->_relatedObjects)) {
2142 $this->loadRelatedObjects($input, $ids);
2143 }
2144 if (empty($this->_component)) {
2145 $this->_component = CRM_Utils_Array::value('component', $input);
2146 }
2147
2148 //not really sure what params might be passed in but lets merge em into values
2149 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2150 $template = CRM_Core_Smarty::singleton();
2151 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2152 //what does recur 'mean here - to do with payment processor return functionality but
2153 // what is the importance
2154 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2155 $paymentObject = &CRM_Core_Payment::singleton(
2156 $this->is_test ? 'test' : 'live',
2157 $this->_relatedObjects['paymentProcessor']
2158 );
2159
2160 $entityID = $entity = NULL;
2161 if (isset($ids['contribution'])) {
2162 $entity = 'contribution';
2163 $entityID = $ids['contribution'];
2164 }
dccb668e
EM
2165 if (!empty($ids['membership'])) {
2166 //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
2167 // 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
2168 // line having loaded an array
2169 $ids['membership'] = (array) $ids['membership'];
6a488035 2170 $entity = 'membership';
dccb668e 2171 $entityID = $ids['membership'][0];
6a488035
TO
2172 }
2173
2174 $url = $paymentObject->subscriptionURL($entityID, $entity);
2175 $template->assign('cancelSubscriptionUrl', $url);
2176
2177 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2178 $template->assign('updateSubscriptionBillingUrl', $url);
2179
2180 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2181 $template->assign('updateSubscriptionUrl', $url);
2182
2183 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2184 //direct mode showing billing block, so use directIPN for temporary
2185 $template->assign('contributeMode', 'directIPN');
2186 }
2187 }
2188 // todo remove strtolower - check consistency
2189 if (strtolower($this->_component) == 'event') {
2190 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2191 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2192 );
2193 }
2194 else {
2195 $values['contribution_id'] = $this->id;
a7488080 2196 if (!empty($ids['related_contact'])) {
6a488035
TO
2197 $values['related_contact'] = $ids['related_contact'];
2198 if (isset($ids['onbehalf_dupe_alert'])) {
2199 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2200 }
2201 $entityBlock = array(
2202 'contact_id' => $ids['contact'],
2203 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2204 'Home', 'id', 'name'
2205 ),
2206 );
2207 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2208 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2209 }
2210 $isTest = FALSE;
2211 if ($this->is_test) {
2212 $isTest = TRUE;
2213 }
2214 if (!empty($this->_relatedObjects['membership'])) {
2215 foreach ($this->_relatedObjects['membership'] as $membership) {
2216 if ($membership->id) {
85dea18b 2217 $values['isMembership'] = TRUE;
6a488035
TO
2218
2219 // need to set the membership values here
2220 $template->assign('membership_assign', 1);
2221 $template->assign('membership_name',
2222 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2223 );
2224 $template->assign('mem_start_date', $membership->start_date);
2225 $template->assign('mem_join_date', $membership->join_date);
2226 $template->assign('mem_end_date', $membership->end_date);
2227 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2228 $template->assign('mem_status', $membership_status);
2229 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2230 $template->assign('is_pay_later', 1);
2231 }
2232
2233 // if separate payment there are two contributions recorded and the
2234 // admin will need to send a receipt for each of them separately.
2235 // we dont link the two in the db (but can potentially infer it if needed)
2236 $template->assign('is_separate_payment', 0);
2237
2238 if ($recur && $paymentObject) {
2239 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2240 $template->assign('cancelSubscriptionUrl', $url);
2241 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2242 $template->assign('updateSubscriptionBillingUrl', $url);
2243 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2244 $template->assign('updateSubscriptionUrl', $url);
2245 }
2246
2247 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2248
2249 return $result;
2250 // otherwise if its about sending emails, continue sending without return, as we
2251 // don't want to exit the loop.
2252 }
2253 }
2254 }
2255 else {
2256 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2257 }
2258 }
2259 }
2260
16b10e64 2261 /**
6a488035
TO
2262 * Gather values for contribution mail - this function has been created
2263 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2264 * Values related to the contribution in question are gathered
2265 *
014c4014
TO
2266 * @param array $input
2267 * Input into function (probably from payment processor).
16b10e64 2268 * @param array $values
014c4014 2269 * @param array $ids
16b10e64 2270 * The set of ids related to the input.
6a488035 2271 *
a6c01b45 2272 * @return array
186c9c17 2273 */
00be9182 2274 public function _gatherMessageValues($input, &$values, $ids = array()) {
6a488035
TO
2275 // set display address of contributor
2276 if ($this->address_id) {
f2b2a3ff
TO
2277 $addressParams = array('id' => $this->address_id);
2278 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2279 $addressDetails = array_values($addressDetails);
6a488035
TO
2280 $values['address'] = $addressDetails[0]['display'];
2281 }
2282 if ($this->_component == 'contribute') {
2283 if (isset($this->contribution_page_id)) {
2284 CRM_Contribute_BAO_ContributionPage::setValues(
2285 $this->contribution_page_id,
2286 $values
2287 );
2288 if ($this->contribution_page_id) {
2289 // CRM-8254 - override default currency if applicable
2290 $config = CRM_Core_Config::singleton();
2291 $config->defaultCurrency = CRM_Utils_Array::value(
2292 'currency',
2293 $values,
2294 $config->defaultCurrency
2295 );
2296 }
2297 }
2298 // no contribution page -probably back office
2299 else {
2300 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2301 $values['is_email_receipt'] = 1;
2302 $values['title'] = 'Contribution';
2303 }
2304 // set lineItem for contribution
2305 if ($this->id) {
2306 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2307 if (!empty($lineItem)) {
f2b2a3ff 2308 $itemId = key($lineItem);
6a488035 2309 foreach ($lineItem as &$eachItem) {
f2b2a3ff 2310 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
6a488035
TO
2311 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2312 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2313 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2314 }
2315 }
2316 $values['lineItem'][0] = $lineItem;
f2b2a3ff
TO
2317 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2318 }
6a488035
TO
2319 }
2320
2321 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2322 $this->id,
2323 $this->contact_id
2324 );
2325 // if this is onbehalf of contribution then set related contact
a7488080 2326 if (!empty($relatedContact['individual_id'])) {
6a488035
TO
2327 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2328 }
2329 }
2330 else {
2331 // event
2332 $eventParams = array(
2333 'id' => $this->_relatedObjects['event']->id,
2334 );
2335 $values['event'] = array();
2336
2337 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2338
2339 //get location details
2340 $locationParams = array(
2341 'entity_id' => $this->_relatedObjects['event']->id,
2342 'entity_table' => 'civicrm_event',
2343 );
2344 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2345
2346 $ufJoinParams = array(
2347 'entity_table' => 'civicrm_event',
f2b2a3ff
TO
2348 'entity_id' => $ids['event'],
2349 'module' => 'CiviEvent',
6a488035
TO
2350 );
2351
2352 list($custom_pre_id,
f2b2a3ff
TO
2353 $custom_post_ids
2354 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
6a488035
TO
2355
2356 $values['custom_pre_id'] = $custom_pre_id;
2357 $values['custom_post_id'] = $custom_post_ids;
2358
2359 // set lineItem for event contribution
2360 if ($this->id) {
2361 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2362 if (!empty($participantIds)) {
2363 foreach ($participantIds as $pIDs) {
2364 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2365 if (!CRM_Utils_System::isNull($lineItem)) {
2366 $values['lineItem'][] = $lineItem;
2367 }
2368 }
2369 }
2370 }
2371 }
2372
2373 return $values;
2374 }
2375
2376 /**
2377 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2378 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2379 * Note we send directly from this function in some cases because it is only partly refactored
2380 * Don't call this function directly as the signature will change
02af3683
EM
2381 *
2382 * @param $values
2383 * @param $input
5a4f6742 2384 * @param CRM_Core_SMARTY $template
02af3683
EM
2385 * @param bool $recur
2386 * @param bool $returnMessageText
2387 *
2388 * @return mixed
6a488035 2389 */
f2b2a3ff 2390 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
6a488035
TO
2391 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2392 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2393 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2394 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
f2b2a3ff 2395 $template->assign('useForMember', TRUE);
6a488035 2396 }
02af3683 2397 //assign honor information to receipt message
8af73472 2398 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
6a488035 2399
8af73472 2400 if (isset($softRecord['soft_credit'])) {
7305d3e6 2401 //if id of contribution page is present
2402 if (!empty($values['id'])) {
2403 $values['honor'] = array(
2404 'honor_profile_values' => array(),
2405 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2406 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2407 );
2408 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
6a488035 2409
f2b2a3ff 2410 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
7305d3e6 2411 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2412 }
2413 else {
2414 //offline contribution
2415 $softCreditTypes = $softCredits = array();
2416 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2417 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2418 $softCredits[$key] = array(
2419 'Name' => $softCredit['contact_name'],
21dfd5f5 2420 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
7305d3e6 2421 );
2422 }
2423 $template->assign('softCreditTypes', $softCreditTypes);
2424 $template->assign('softCredits', $softCredits);
2425 }
6a488035
TO
2426 }
2427
2428 $dao = new CRM_Contribute_DAO_ContributionProduct();
2429 $dao->contribution_id = $this->id;
2430 if ($dao->find(TRUE)) {
2431 $premiumId = $dao->product_id;
2432 $template->assign('option', $dao->product_option);
2433
2434 $productDAO = new CRM_Contribute_DAO_Product();
2435 $productDAO->id = $premiumId;
2436 $productDAO->find(TRUE);
2437 $template->assign('selectPremium', TRUE);
2438 $template->assign('product_name', $productDAO->name);
2439 $template->assign('price', $productDAO->price);
2440 $template->assign('sku', $productDAO->sku);
2441 }
f2b2a3ff
TO
2442 $template->assign('title', CRM_Utils_Array::value('title', $values));
2443 $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2444 if (empty($amount) && isset($this->total_amount)) {
6a488035
TO
2445 $amount = $this->total_amount;
2446 }
2447 $template->assign('amount', $amount);
2448 // add the new contribution values
2449 if (strtolower($this->_component) == 'contribute') {
2450 //PCP Info
2451 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2452 $softDAO->contribution_id = $this->id;
2453 if ($softDAO->find(TRUE)) {
2454 $template->assign('pcpBlock', TRUE);
2455 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2456 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2457 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2458
2459 //assign the pcp page title for email subject
2460 $pcpDAO = new CRM_PCP_DAO_PCP();
2461 $pcpDAO->id = $softDAO->pcp_id;
2462 if ($pcpDAO->find(TRUE)) {
2463 $template->assign('title', $pcpDAO->title);
2464 }
2465 }
2466 }
2467
2468 if ($this->financial_type_id) {
2469 $values['financial_type_id'] = $this->financial_type_id;
2470 }
2471
6a488035
TO
2472 $template->assign('trxn_id', $this->trxn_id);
2473 $template->assign('receive_date',
2474 CRM_Utils_Date::mysqlToIso($this->receive_date)
2475 );
2476 $template->assign('contributeMode', 'notify');
2477 $template->assign('action', $this->is_test ? 1024 : 1);
2478 $template->assign('receipt_text',
2479 CRM_Utils_Array::value('receipt_text',
2480 $values
2481 )
2482 );
2483 $template->assign('is_monetary', 1);
2484 $template->assign('is_recur', (bool) $recur);
2485 $template->assign('currency', $this->currency);
2486 $template->assign('address', CRM_Utils_Address::format($input));
2487 if ($this->_component == 'event') {
2488 $template->assign('title', $values['event']['title']);
2489 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2490 $viewRoles = array();
2491 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2492 $viewRoles[] = $participantRoles[$v];
2493 }
2494 $values['event']['participant_role'] = implode(', ', $viewRoles);
2495 $template->assign('event', $values['event']);
2496 $template->assign('location', $values['location']);
2497 $template->assign('customPre', $values['custom_pre_id']);
2498 $template->assign('customPost', $values['custom_post_id']);
2499
2500 $isTest = FALSE;
2501 if ($this->_relatedObjects['participant']->is_test) {
2502 $isTest = TRUE;
2503 }
2504
2505 $values['params'] = array();
2506 //to get email of primary participant.
2507 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
f2b2a3ff
TO
2508 $primaryAmount[] = array(
2509 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
21dfd5f5 2510 'amount' => $this->_relatedObjects['participant']->fee_amount,
f2b2a3ff 2511 );
6a488035
TO
2512 //build an array of cId/pId of participants
2513 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2514 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2515 //send receipt to additional participant if exists
2516 if (count($additionalIDs)) {
2517 $template->assign('isPrimary', 0);
2518 $template->assign('customProfile', NULL);
2519 //set additionalParticipant true
2520 $values['params']['additionalParticipant'] = TRUE;
2521 foreach ($additionalIDs as $pId => $cId) {
2522 $amount = array();
2523 //to change the status pending to completed
2524 $additional = new CRM_Event_DAO_Participant();
2525 $additional->id = $pId;
2526 $additional->contact_id = $cId;
2527 $additional->find(TRUE);
2528 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2529 $additional->status_id = 1;
2530 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2531 //if additional participant dont have email
2532 //use display name.
2533 if (!$additionalParticipantInfo) {
2534 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2535 }
2536 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
f2b2a3ff
TO
2537 $primaryAmount[] = array(
2538 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
21dfd5f5 2539 'amount' => $additional->fee_amount,
f2b2a3ff 2540 );
6a488035
TO
2541 $additional->save();
2542 $additional->free();
2543 $template->assign('amount', $amount);
2544 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2545 }
2546 }
2547
2548 //build an array of custom profile and assigning it to template
2549 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2550
2551 if (count($customProfile)) {
2552 $template->assign('customProfile', $customProfile);
2553 }
2554
2555 // for primary contact
2556 $values['params']['additionalParticipant'] = FALSE;
2557 $template->assign('isPrimary', 1);
2558 $template->assign('amount', $primaryAmount);
2559 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2560 if ($this->payment_instrument_id) {
2561 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2562 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2563 }
2564 // carry paylater, since we did not created billing,
2565 // so need to pull email from primary location, CRM-4395
2566 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2567 }
2568 return $template;
2569 }
2570
2571 /**
100fef9d 2572 * Check whether payment processor supports
6a488035
TO
2573 * cancellation of contribution subscription
2574 *
014c4014
TO
2575 * @param int $contributionId
2576 * Contribution id.
6a488035 2577 *
77b97be7
EM
2578 * @param bool $isNotCancelled
2579 *
a130e045 2580 * @return bool
6a488035 2581 */
00be9182 2582 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
6a488035
TO
2583 $cacheKeyString = "$contributionId";
2584 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2585
2586 static $supportsCancel = array();
2587
2588 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2589 $supportsCancel[$cacheKeyString] = FALSE;
2590 $isCancelled = FALSE;
2591
2592 if ($isNotCancelled) {
2593 $isCancelled = self::isSubscriptionCancelled($contributionId);
2594 }
2595
2596 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2597 if (!empty($paymentObject)) {
2598 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2599 }
2600 }
2601 return $supportsCancel[$cacheKeyString];
2602 }
2603
2604 /**
100fef9d 2605 * Check whether subscription is already cancelled
6a488035 2606 *
014c4014
TO
2607 * @param int $contributionId
2608 * Contribution id.
6a488035 2609 *
a6c01b45
CW
2610 * @return string
2611 * contribution status
6a488035 2612 */
00be9182 2613 public static function isSubscriptionCancelled($contributionId) {
6a488035
TO
2614 $sql = "
2615 SELECT cr.contribution_status_id
2616 FROM civicrm_contribution_recur cr
2617 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2618 WHERE con.id = %1 LIMIT 1";
f2b2a3ff 2619 $params = array(1 => array($contributionId, 'Integer'));
6a488035 2620 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
f2b2a3ff 2621 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
6a488035
TO
2622 if ($status == 'Cancelled') {
2623 return TRUE;
2624 }
2625 return FALSE;
2626 }
2627
2628 /**
100fef9d 2629 * Create all financial accounts entry
6a488035 2630 *
014c4014
TO
2631 * @param array $params
2632 * Contribution object, line item array and params for trxn.
6a488035 2633 *
6a488035 2634 *
02af3683 2635 * @param array $financialTrxnValues
77b97be7
EM
2636 *
2637 * @return null|object
6a488035 2638 */
00be9182 2639 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
cb579c66 2640 $skipRecords = $update = $return = $isRelatedId = FALSE;
02af3683 2641
d37ade2e 2642 $additionalParticipantId = array();
6a488035
TO
2643 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2644
2645 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2646 $entityId = $params['participant_id'];
2647 $entityTable = 'civicrm_participant';
d37ade2e 2648 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
6a488035 2649 }
8aa7457a
EM
2650 elseif (!empty($params['membership_id'])) {
2651 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2652 // are created off one contribution should be handled elsewhere
2653 $entityId = $params['membership_id'];
2654 $entityTable = 'civicrm_membership';
2655 }
6a488035
TO
2656 else {
2657 $entityId = $params['contribution']->id;
2658 $entityTable = 'civicrm_contribution';
2659 }
4d34aefa 2660
cb579c66
PN
2661 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
2662 $isRelatedId = TRUE;
2663 }
85dea18b 2664
464bb009 2665 $entityID[] = $entityId;
d37ade2e 2666 if (!empty($additionalParticipantId)) {
2667 $entityID += $additionalParticipantId;
464bb009 2668 }
4d34aefa 2669 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
a7488080 2670 if (empty($params['prevContribution'])) {
6a488035
TO
2671 $entityID = NULL;
2672 }
e005ab6b
PN
2673 else {
2674 $update = TRUE;
2675 }
4d34aefa 2676
f8325309
PJ
2677 $statusId = $params['contribution']->contribution_status_id;
2678 // CRM-13964 partial payment
ede1935f 2679 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
f2b2a3ff
TO
2680 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2681 ) {
ede1935f
PJ
2682 $partialAmtPay = $params['partial_amount_pay'];
2683 $partialAmtTotal = $params['partial_payment_total'];
2684
0f602e3f
PJ
2685 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2686 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
f8325309 2687 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
ede1935f 2688 $params['total_amount'] = $partialAmtPay;
0f602e3f 2689
ede1935f 2690 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
0f602e3f 2691 if (empty($balanceTrxnInfo['trxn_id'])) {
ede1935f
PJ
2692 // create new balance transaction record
2693 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2694 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2695
0f602e3f 2696 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
ede1935f
PJ
2697 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2698 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
ede1935f
PJ
2699 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2700 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2701 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2702 $balanceTrxnParams['currency'] = $params['contribution']->currency;
2703 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
2704 $balanceTrxnParams['status_id'] = $statusId;
2705 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2706 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
a7488080 2707 if (!empty($params['payment_processor'])) {
ede1935f
PJ
2708 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2709 }
0f602e3f 2710 CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
ede1935f 2711 }
f8325309
PJ
2712 }
2713
6a488035 2714 // build line item array if its not set in $params
a7488080 2715 if (empty($params['line_item']) || $additionalParticipantId) {
cb579c66 2716 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
6a488035
TO
2717 }
2718
2719 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
f2b2a3ff
TO
2720 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)
2721 ) {
6a488035 2722 $skipRecords = TRUE;
f2b2a3ff
TO
2723 $pendingStatus = array(
2724 array_search('Pending', $contributionStatuses),
21dfd5f5 2725 array_search('In Progress', $contributionStatuses),
f2b2a3ff 2726 );
b81ee58c 2727 if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) {
f743a6eb 2728 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
6a488035
TO
2729 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2730 }
a7488080 2731 elseif (!empty($params['payment_processor'])) {
6a488035
TO
2732 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2733 }
a7488080 2734 elseif (!empty($params['payment_instrument_id'])) {
6a488035
TO
2735 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2736 }
2737 else {
ac7514c2
PN
2738 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2739 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2740 $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);
6a488035
TO
2741 }
2742
2743 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
8cc574cf 2744 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
6a488035
TO
2745 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2746 }
f8325309 2747
6a488035
TO
2748 //build financial transaction params
2749 $trxnParams = array(
2750 'contribution_id' => $params['contribution']->id,
2751 'to_financial_account_id' => $params['to_financial_account_id'],
2752 'trxn_date' => date('YmdHis'),
2753 'total_amount' => $totalAmount,
2754 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2755 'net_amount' => CRM_Utils_Array::value('net_amount', $params),
2756 'currency' => $params['contribution']->currency,
2757 'trxn_id' => $params['contribution']->trxn_id,
f8325309 2758 'status_id' => $statusId,
12921438 2759 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
6a488035
TO
2760 'check_number' => CRM_Utils_Array::value('check_number', $params),
2761 );
2762
a7488080 2763 if (!empty($params['payment_processor'])) {
8ef12e64 2764 $trxnParams['payment_processor_id'] = $params['payment_processor'];
6a488035 2765 }
0f602e3f
PJ
2766
2767 if (isset($fromFinancialAccountId)) {
2768 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2769 }
2770
2771 // consider external values passed for recording transaction entry
02af3683
EM
2772 if (!empty($financialTrxnValues)) {
2773 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
0f602e3f
PJ
2774 }
2775
6a488035
TO
2776 $params['trxnParams'] = $trxnParams;
2777
a7488080 2778 if (!empty($params['prevContribution'])) {
404f77c9
PN
2779 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
2780 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
2781 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
2782 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
2783 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
48ea0708 2784
182228d5 2785 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
f2b2a3ff
TO
2786 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
2787 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
2788 ) {
182228d5
PN
2789 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2790 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2791 }
85dea18b 2792
404f77c9 2793 //if financial type is changed
a7488080 2794 if (!empty($params['financial_type_id']) &&
f2b2a3ff
TO
2795 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
2796 ) {
404f77c9
PN
2797 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2798 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2799 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2800 if ($oldFinancialAccount != $newFinancialAccount) {
2801 $params['total_amount'] = 0;
b81ee58c 2802 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
404f77c9
PN
2803 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2804 $params['prevContribution']->financial_type_id, $relationTypeId);
2805 }
2806 else {
2807 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
a7488080 2808 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
404f77c9
PN
2809 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2810 }
2811 }
2812 self::updateFinancialAccounts($params, 'changeFinancialType');
2813 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2814 $params['financial_account_id'] = $newFinancialAccount;
2815 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2816 self::updateFinancialAccounts($params);
2817 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2818 }
6a488035 2819 }
48ea0708 2820
6a488035 2821 //Update contribution status
404f77c9 2822 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
a7488080 2823 if (!empty($params['contribution_status_id']) &&
f2b2a3ff
TO
2824 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2825 ) {
6a488035
TO
2826 //Update Financial Records
2827 self::updateFinancialAccounts($params, 'changedStatus');
2828 }
2829
2830 // change Payment Instrument for a Completed contribution
2831 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2832 // instrument is null and now new payment instrument is added along with the payment
404f77c9
PN
2833 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2834 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
6a488035 2835 if (array_key_exists('payment_instrument_id', $params)) {
f2b2a3ff 2836 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
6a488035 2837 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
f2b2a3ff
TO
2838 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
2839 ) {
6a488035
TO
2840 //check if status is changed from Pending to Completed
2841 // do not update payment instrument changes for Pending to Completed
2842 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
f2b2a3ff
TO
2843 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
2844 ) {
6a488035
TO
2845 // for all other statuses create new financial records
2846 self::updateFinancialAccounts($params, 'changePaymentInstrument');
d9814f68
PN
2847 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2848 self::updateFinancialAccounts($params, 'changePaymentInstrument');
6a488035
TO
2849 }
2850 }
4c9b6178 2851 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
f2b2a3ff
TO
2852 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2853 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
2854 ) {
6a488035
TO
2855 // for any other payment instrument changes create new financial records
2856 self::updateFinancialAccounts($params, 'changePaymentInstrument');
d9814f68
PN
2857 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2858 self::updateFinancialAccounts($params, 'changePaymentInstrument');
6a488035 2859 }
4c9b6178 2860 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
f2b2a3ff
TO
2861 $params['contribution']->check_number != $params['prevContribution']->check_number
2862 ) {
6a488035
TO
2863 // another special case when check number is changed, create new financial records
2864 // create financial trxn with negative amount
6a488035
TO
2865 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2866 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2867 // create financial trxn with positive amount
2868 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2869 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2870 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2871 }
2872 }
48ea0708 2873
404f77c9
PN
2874 //if Change contribution amount
2875 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2876 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
d9814f68 2877 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
404f77c9
PN
2878 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2879 if (isset($totalAmount) &&
f2b2a3ff
TO
2880 $totalAmount != $params['prevContribution']->total_amount
2881 ) {
404f77c9
PN
2882 //Update Financial Records
2883 $params['trxnParams']['from_financial_account_id'] = NULL;
404f77c9 2884 self::updateFinancialAccounts($params, 'changedAmount');
6a488035 2885 }
6a488035
TO
2886 }
2887
2888 if (!$update) {
1c19e0a3
PJ
2889 // records finanical trxn and entity financial trxn
2890 // also make it available as return value
2891 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
6a488035
TO
2892 $params['entity_id'] = $financialTxn->id;
2893 }
e005ab6b
PN
2894 }
2895 // record line items and finacial items
a7488080 2896 if (empty($params['skipLineItem'])) {
e005ab6b 2897 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
6a488035
TO
2898 }
2899
2900 // create batch entry if batch_id is passed
a7488080 2901 if (!empty($params['batch_id'])) {
6a488035
TO
2902 $entityParams = array(
2903 'batch_id' => $params['batch_id'],
2904 'entity_table' => 'civicrm_financial_trxn',
2905 'entity_id' => $financialTxn->id,
e005ab6b 2906 );
6a488035
TO
2907 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
2908 }
2909
2910 // when a fee is charged
8cc574cf 2911 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
6a488035
TO
2912 CRM_Core_BAO_FinancialTrxn::recordFees($params);
2913 }
2914
a7488080 2915 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
f2b2a3ff
TO
2916 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2917 ) {
6a488035
TO
2918 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2919 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
2920 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
2921 }
2922 unset($params['line_item']);
bd99f5fe 2923
1c19e0a3 2924 return $return;
6a488035
TO
2925 }
2926
2927 /**
100fef9d 2928 * Update all financial accounts entry
6a488035 2929 *
014c4014
TO
2930 * @param array $params
2931 * Contribution object, line item array and params for trxn.
6a488035 2932 *
014c4014
TO
2933 * @param string $context
2934 * Update scenarios.
6a488035 2935 *
77b97be7
EM
2936 * @param null $skipTrxn
2937 *
6a488035 2938 */
00be9182 2939 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
6a488035
TO
2940 $itemAmount = $trxnID = NULL;
2941 //get all the statuses
2942 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
8af73472 2943 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
f2b2a3ff 2944 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
b81ee58c 2945 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
f2b2a3ff
TO
2946 && $context == 'changePaymentInstrument'
2947 ) {
6a488035
TO
2948 return;
2949 }
2950 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2951 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2952 }
2953 if ($context == 'changedStatus') {
2954 //get all the statuses
2955 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2956
2957 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2958 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
f2b2a3ff
TO
2959 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))
2960 ) {
2961 $params['trxnParams']['total_amount'] = -$params['total_amount'];
6a488035 2962 }
b81ee58c 2963 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
f2b2a3ff
TO
2964 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)
2965 ) {
6a488035
TO
2966 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2967 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2968 $params['trxnParams']['to_financial_account_id'] = NULL;
f2b2a3ff 2969 $params['trxnParams']['total_amount'] = -$params['total_amount'];
6a488035 2970 }
8ef12e64 2971 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
6a488035
TO
2972 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2973 $financialTypeID, $relationTypeId);
2974 }
2975 $itemAmount = $params['trxnParams']['total_amount'];
2976 }
2977 elseif ($context == 'changePaymentInstrument') {
d9814f68
PN
2978 if ($params['trxnParams']['total_amount'] < 0) {
2979 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
a7488080 2980 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
d9814f68
PN
2981 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2982 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
48ea0708 2983 }
6a488035
TO
2984 }
2985 else {
d9814f68
PN
2986 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2987 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
6a488035
TO
2988 }
2989 }
6a488035
TO
2990 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
2991 $params['entity_id'] = $trxn->id;
2992
2993 if ($context == 'changedStatus') {
b81ee58c 2994 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
f2b2a3ff
TO
2995 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2996 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
2997 ) {
464bb009
PN
2998 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2999 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2d77a516 3000
464bb009
PN
3001 $entityParams = array(
3002 'entity_table' => 'civicrm_financial_item',
3003 'financial_trxn_id' => $trxn->id,
3004 );
3b624e58
EM
3005 if (empty($params['line_item'])) {
3006 //CRM-15296
3007 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3008 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3009 // & this can be removed
3010 return;
3011 }
6a488035
TO
3012 foreach ($params['line_item'] as $fieldId => $fields) {
3013 foreach ($fields as $fieldValueId => $fieldValues) {
3014 $fparams = array(
3015 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3016 2 => array($fieldValues['id'], 'Integer'),
3017 );
6a488035 3018 CRM_Core_DAO::executeQuery($query, $fparams);
464bb009
PN
3019 $fparams = array(
3020 1 => array($fieldValues['id'], 'Integer'),
3021 );
3022 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3023 while ($financialItem->fetch()) {
3024 $entityParams['entity_id'] = $financialItem->id;
3025 $entityParams['amount'] = $financialItem->amount;
3026 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3027 }
6a488035
TO
3028 }
3029 }
3030 return;
3031 }
3032 }
3033 if ($context != 'changePaymentInstrument') {
3034 $itemParams['entity_table'] = 'civicrm_line_item';
3035 $trxnIds['id'] = $params['entity_id'];
3036 foreach ($params['line_item'] as $fieldId => $fields) {
3037 foreach ($fields as $fieldValueId => $fieldValues) {
3038 $prevParams['entity_id'] = $fieldValues['id'];
3039 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
3040
3041 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3042 if ($params['contribution']->receive_date) {
3043 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3044 }
3045
3046 $financialAccount = $prevfinancialItem->financial_account_id;
a7488080 3047 if (!empty($params['financial_account_id'])) {
6a488035
TO
3048 $financialAccount = $params['financial_account_id'];
3049 }
3050
3051 $currency = $params['prevContribution']->currency;
3052 if ($params['contribution']->currency) {
3053 $currency = $params['contribution']->currency;
3054 }
05e92f54 3055 $diff = 1;
a7488080 3056 if (!empty($params['is_quick_config'])) {
6a488035
TO
3057 $amount = $itemAmount;
3058 if (!$amount) {
3059 $amount = $params['total_amount'];
3060 }
3061 }
3062 else {
e8d37d0a 3063 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
f2b2a3ff
TO
3064 || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3065 ) {
3066 $diff = -1;
6a488035
TO
3067 }
3068 $amount = $diff * $fieldValues['line_total'];
3069 }
3070
3071 $itemParams = array(
3072 'transaction_date' => $receiveDate,
3073 'contact_id' => $params['prevContribution']->contact_id,
3074 'currency' => $currency,
3075 'amount' => $amount,
3076 'description' => $prevfinancialItem->description,
3077 'status_id' => $prevfinancialItem->status_id,
3078 'financial_account_id' => $financialAccount,
3079 'entity_table' => 'civicrm_line_item',
21dfd5f5 3080 'entity_id' => $fieldValues['id'],
6a488035
TO
3081 );
3082 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
c40e1ff4 3083
3084 if ($fieldValues['tax_amount']) {
5a18a545 3085 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
3086 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
c40e1ff4 3087 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
5a18a545 3088 $itemParams['description'] = $taxTerm;
c40e1ff4 3089 if ($fieldValues['financial_type_id']) {
5a18a545 3090 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
c40e1ff4 3091 }
3092 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3093 }
6a488035
TO
3094 }
3095 }
3096 }
3097 }
3098
3099 /**
100fef9d 3100 * Check status validation on update of a contribution
6a488035 3101 *
014c4014
TO
3102 * @param array $values
3103 * Previous form values before submit.
6a488035 3104 *
014c4014
TO
3105 * @param array $fields
3106 * The input form values.
6a488035 3107 *
014c4014
TO
3108 * @param array $errors
3109 * List of errors.
6a488035 3110 *
77b97be7 3111 * @return bool
6a488035 3112 */
00be9182 3113 public static function checkStatusValidation($values, &$fields, &$errors) {
8cc574cf 3114 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
c71ae314
PN
3115 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3116 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3117 return FALSE;
3118 }
3119 }
6a488035
TO
3120 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3121 $checkStatus = array(
3122 'Cancelled' => array('Completed', 'Refunded'),
3123 'Completed' => array('Cancelled', 'Refunded'),
3124 'Pending' => array('Cancelled', 'Completed', 'Failed'),
f73acc78 3125 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
21dfd5f5 3126 'Refunded' => array('Cancelled', 'Completed'),
6a488035
TO
3127 );
3128
3129 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
f2b2a3ff 3130 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
353ffa53
TO
3131 1 => $contributionStatuses[$values['contribution_status_id']],
3132 2 => $contributionStatuses[$fields['contribution_status_id']],
3133 ));
6a488035
TO
3134 }
3135 }
c3d24ba7
PN
3136
3137 /**
100fef9d 3138 * Delete contribution of contact
c3d24ba7
PN
3139 *
3140 * CRM-12155
3141 *
014c4014
TO
3142 * @param int $contactId
3143 * Contact id.
c3d24ba7 3144 *
c3d24ba7 3145 */
00be9182 3146 public static function deleteContactContribution($contactId) {
c3d24ba7
PN
3147 $contribution = new CRM_Contribute_DAO_Contribution();
3148 $contribution->contact_id = $contactId;
3149 $contribution->find();
3150 while ($contribution->fetch()) {
3151 self::deleteContribution($contribution->id);
3152 }
3153 }
16c0ec8d
CW
3154
3155 /**
3156 * Get options for a given contribution field.
3157 * @see CRM_Core_DAO::buildOptions
3158 *
014c4014 3159 * @param string $fieldName
bed98343 3160 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3161 * @param array $props whatever is known about this dao object.
77b97be7 3162 *
a130e045 3163 * @return array|bool
16c0ec8d
CW
3164 */
3165 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3166 $className = __CLASS__;
3167 $params = array();
3168 switch ($fieldName) {
3169 // This field is not part of this object but the api supports it
3170 case 'payment_processor':
3171 $className = 'CRM_Contribute_BAO_ContributionPage';
3172 // Filter results by contribution page
3173 if (!empty($props['contribution_page_id'])) {
03a8c3dc 3174 $page = civicrm_api('contribution_page', 'getsingle', array(
3175 'version' => 3,
21dfd5f5 3176 'id' => ($props['contribution_page_id']),
03a8c3dc 3177 ));
16c0ec8d
CW
3178 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3179 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3180 }
33a429d4 3181 break;
ea100cb5 3182
33a429d4
CW
3183 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3184 case 'honor_type_id':
3185 $className = 'CRM_Contribute_BAO_ContributionSoft';
3186 $fieldName = 'soft_credit_type_id';
3187 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3188 break;
16c0ec8d
CW
3189 }
3190 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3191 }
03a8c3dc 3192
3b67ab13 3193 /**
100fef9d 3194 * Validate financial type
3b67ab13
PN
3195 *
3196 * CRM-13231
3197 *
014c4014
TO
3198 * @param int $financialTypeId
3199 * Financial Type id.
3b67ab13 3200 *
77b97be7
EM
3201 * @param string $relationName
3202 *
3203 * @return array|bool
3b67ab13 3204 */
00be9182 3205 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3b67ab13
PN
3206 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3207 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
3208
3209 if (!$financialAccount) {
3210 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3211 }
3212 return FALSE;
3213 }
16c0ec8d 3214
3d7de127 3215
d424ffde 3216 /**
3d7de127
PJ
3217 * Function to record additional payment for partial and refund contributions
3218 *
014c4014 3219 * @param int $contributionId
16b10e64 3220 * is the invoice contribution id (got created after processing participant payment).
d424ffde 3221 * @param array $trxnsData
16b10e64 3222 * to take user provided input of transaction details.
014c4014
TO
3223 * @param string $paymentType
3224 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
100fef9d 3225 * @param int $participantId
186c9c17
EM
3226 *
3227 * @return null|object
3228 */
00be9182 3229 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
0f602e3f 3230 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
e8cf3013
PJ
3231 $getInfoOf['id'] = $contributionId;
3232 $defaults = array();
3233 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3234
3235 if ($paymentType == 'owed') {
3236 // build params for recording financial trxn entry
3237 $params['contribution'] = $contributionDAO;
3238 $params = array_merge($defaults, $params);
3239 $params['skipLineItem'] = TRUE;
3240 $params['partial_payment_total'] = $contributionDAO->total_amount;
3241 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3242 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3243
3244 // record the entry
3245 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3246 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3247 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
0f602e3f 3248
e8cf3013 3249 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
921bca19
DG
3250 if (!empty($trxnId)) {
3251 $trxnId = $trxnId['trxn_id'];
3252 }
3253 elseif (!empty($contributionDAO->payment_instrument_id)) {
3254 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3255 }
3256 else {
3257 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3258 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3259 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3260 }
0f602e3f 3261
e8cf3013
PJ
3262 // update statuses
3263 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3264 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
0f602e3f 3265FROM civicrm_financial_trxn ft
a695703f
PJ
3266LEFT JOIN civicrm_entity_financial_trxn eft
3267 ON (ft.id = eft.financial_trxn_id)
3268WHERE eft.entity_table = 'civicrm_contribution'
3269 AND eft.entity_id = {$contributionId}
3270 AND ft.to_financial_account_id != {$toFinancialAccount}
3271 AND ft.status_id = {$statusId}
0f602e3f 3272";
e8cf3013
PJ
3273 $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
3274
3275 // update statuses
3276 if ($contributionDAO->total_amount == $sumOfPayments) {
921bca19
DG
3277 // update contribution status and
3278 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3279 $contributionDAO->contribution_status_id = $statusId;
3280 $contributionDAO->cancel_date = 'null';
3281 $contributionDAO->cancel_reason = NULL;
e59da3a9
DG
3282 $netAmount = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
3283 $contributionDAO->net_amount = $contributionDAO->net_amount + $netAmount;
921bca19
DG
3284 $contributionDAO->save();
3285
3286 //Change status of financial record too
3287 $financialTrxn->status_id = $statusId;
3288 $financialTrxn->save();
3289
e8cf3013
PJ
3290 // note : not using the self::add method,
3291 // the reason because it performs 'status change' related code execution for financial records
3292 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3293 // are coded below i.e. just updating financial_item status to 'Paid'
e8cf3013
PJ
3294
3295 if ($participantId) {
3296 // update participant status
e8cf3013 3297 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
28e4e707
PJ
3298 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3299 foreach ($ids as $val) {
3300 $participantUpdate['id'] = $val;
3301 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3302 CRM_Event_BAO_Participant::add($participantUpdate);
3303 }
e8cf3013
PJ
3304 }
3305
3306 // update financial item statuses
3307 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3308 $paidStatus = array_search('Paid', $financialItemStatus);
3309
5684b818 3310 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
e8cf3013
PJ
3311 $sqlFinancialItemUpdate = "
3312UPDATE civicrm_financial_item fi
3313 LEFT JOIN civicrm_entity_financial_trxn eft
3314 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3315SET status_id = {$paidStatus}
5684b818 3316WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
e8cf3013
PJ
3317";
3318 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3319 }
3320 }
3321 elseif ($paymentType == 'refund') {
3322 // build params for recording financial trxn entry
3323 $params['contribution'] = $contributionDAO;
3324 $params = array_merge($defaults, $params);
3325 $params['skipLineItem'] = TRUE;
3326 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
f2b2a3ff 3327 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
e8cf3013 3328
1010c4e1
PJ
3329 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3330 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
e8cf3013
PJ
3331 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3332 // record the entry
3333 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3334
aac57c29
PJ
3335 // note : not using the self::add method,
3336 // the reason because it performs 'status change' related code execution for financial records
e8cf3013 3337 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
aac57c29
PJ
3338 // are coded below i.e. just updating financial_item status to 'Paid'
3339 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
0f602e3f 3340
e8cf3013
PJ
3341 // add financial item entry
3342 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3343 $getLine['entity_id'] = $contributionDAO->id;
3344 $getLine['entity_table'] = 'civicrm_contribution';
3345 $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
615a1e0f
PJ
3346 if (!empty($lineItemId->id)) {
3347 $addFinancialEntry = array(
3348 'transaction_date' => $financialTrxn->trxn_date,
3349 'contact_id' => $contributionDAO->contact_id,
3350 'amount' => $financialTrxn->total_amount,
3351 'status_id' => array_search('Paid', $financialItemStatus),
3352 'entity_id' => $lineItemId->id,
21dfd5f5 3353 'entity_table' => 'civicrm_line_item',
615a1e0f 3354 );
f2b2a3ff 3355 $trxnIds['id'] = $financialTrxn->id;
615a1e0f
PJ
3356 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3357 }
0f602e3f
PJ
3358 if ($participantId) {
3359 // update participant status
0f602e3f 3360 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
28e4e707
PJ
3361 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3362 foreach ($ids as $val) {
3363 $participantUpdate['id'] = $val;
3364 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3365 CRM_Event_BAO_Participant::add($participantUpdate);
3366 }
0f602e3f 3367 }
0f602e3f 3368 }
bd99f5fe 3369
e8cf3013 3370 // activity creation
bd99f5fe
PJ
3371 if (!empty($financialTrxn)) {
3372 if ($participantId) {
3373 $inputParams['id'] = $participantId;
3374 $values = array();
3375 $ids = array();
3376 $component = 'event';
3377 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3378 $entityObj = $entityObj[$participantId];
3379 }
3380 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3381
66526669 3382 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
bd99f5fe
PJ
3383 }
3384 return $financialTrxn;
3385 }
3386
186c9c17
EM
3387 /**
3388 * @param $entityObj
3389 * @param $trxnObj
3390 * @param $activityType
3391 * @param $component
100fef9d 3392 * @param int $contributionId
186c9c17
EM
3393 *
3394 * @throws CRM_Core_Exception
3395 */
00be9182 3396 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
bd99f5fe
PJ
3397 if ($component == 'event') {
3398 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3399 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3400 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3401 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3402 $targetCid = $entityObj->contact_id;
66526669
PJ
3403 // source record id would be the contribution id
3404 $srcRecId = $contributionId;
bd99f5fe
PJ
3405 }
3406
3407 // activity params
3408 $activityParams = array(
3409 'source_contact_id' => $targetCid,
3410 'source_record_id' => $srcRecId,
3411 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3412 $activityType,
3413 'name'
3414 ),
3415 'subject' => $subject,
3416 'activity_date_time' => $date,
3417 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3418 'Completed',
3419 'name'
3420 ),
3421 'skipRecentView' => TRUE,
3422 );
3423
3424 // create activity with target contacts
3425 $session = CRM_Core_Session::singleton();
3426 $id = $session->get('userID');
3427 if ($id) {
3428 $activityParams['source_contact_id'] = $id;
3429 $activityParams['target_contact_id'][] = $targetCid;
3430 }
3431 CRM_Activity_BAO_Activity::create($activityParams);
0f602e3f 3432 }
16c0ec8d 3433
186c9c17 3434 /**
100fef9d 3435 * Get list of payments displayed by Contribute_Page_PaymentInfo
8cf01b22 3436 *
100fef9d 3437 * @param int $id
186c9c17
EM
3438 * @param $component
3439 * @param bool $getTrxnInfo
3440 * @param bool $usingLineTotal
3441 *
3442 * @return mixed
3443 */
00be9182 3444 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
29c61b58
PJ
3445 if ($component == 'event') {
3446 $entity = 'participant';
e8cf3013 3447 $entityTable = 'civicrm_participant';
29c61b58 3448 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
ae53df5f
PJ
3449
3450 if (!$contributionId) {
3451 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3452 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3453 $id = $primaryParticipantId;
3454 }
22825dfc 3455 if (!$contributionId) {
3456 return;
ae53df5f
PJ
3457 }
3458 }
29c61b58
PJ
3459 }
3460 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
1010c4e1 3461 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
5684b818
PJ
3462 $isBalance = NULL;
3463 if ($baseTrxnId) {
3464 $isBalance = TRUE;
3465 }
3466 else {
3467 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3468 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3469 $isBalance = FALSE;
3470 }
1010c4e1 3471 if (empty($total) || $usingLineTotal) {
ae53df5f
PJ
3472 // for additional participants
3473 if ($entityTable == 'civicrm_participant') {
f2b2a3ff
TO
3474 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3475 $total = 0;
3476 foreach ($ids as $val) {
3477 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
3478 }
ae53df5f
PJ
3479 }
3480 else {
3481 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
3482 }
bc2eeabb
PJ
3483 }
3484 else {
3485 $baseTrxnId = $total['trxn_id'];
3486 $total = $total['total_amount'];
3487 }
1010c4e1 3488
bc2eeabb 3489 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
356579e9 3490 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
8cf01b22
DG
3491
3492 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3493 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3494 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
3495
356579e9
PJ
3496 if ($paymentBalance == 0 && $contributionIsPayLater) {
3497 $paymentBalance = $total;
3498 }
3499
29c61b58
PJ
3500 $info['total'] = $total;
3501 $info['paid'] = $total - $paymentBalance;
3502 $info['balance'] = $paymentBalance;
3503 $info['id'] = $id;
3504 $info['component'] = $component;
356579e9 3505 $info['payLater'] = $contributionIsPayLater;
bc2eeabb
PJ
3506 $rows = array();
3507 if ($getTrxnInfo && $baseTrxnId) {
8cf01b22 3508 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
29c61b58 3509 $sql = "
536b8316 3510SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
29c61b58
PJ
3511FROM civicrm_contribution con
3512 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
74fdd414 3513 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
5684b818 3514WHERE con.id = {$contributionId}
29c61b58 3515";
5684b818
PJ
3516
3517 // conditioned WHERE clause
3518 if ($isBalance) {
3519 // if balance trxn exists don't include details of it in transaction info
3520 $sql .= " AND ft.id != {$baseTrxnId} ";
3521 }
29c61b58
PJ
3522 $resultDAO = CRM_Core_DAO::executeQuery($sql);
3523
536b8316
PJ
3524 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
3525 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
f2b2a3ff 3526 while ($resultDAO->fetch()) {
536b8316
PJ
3527 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3528 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3529 $val = array(
29c61b58
PJ
3530 'total_amount' => $resultDAO->total_amount,
3531 'financial_type' => $financialTypes[$resultDAO->financial_type_id],
536b8316 3532 'payment_instrument' => $paidByLabel,
29c61b58
PJ
3533 'receive_date' => $resultDAO->trxn_date,
3534 'trxn_id' => $resultDAO->trxn_id,
3535 'status' => $statuses[$resultDAO->status_id],
3536 );
536b8316
PJ
3537 if ($paidByName == 'Check') {
3538 $val['check_number'] = $resultDAO->check_number;
3539 }
3540 $rows[] = $val;
29c61b58
PJ
3541 }
3542 $info['transaction'] = $rows;
3543 }
3544 return $info;
3545 }
5a18a545 3546
3547 /**
100fef9d 3548 * Get financial account id has 'Sales Tax Account is'
5a18a545 3549 * account relationship with financial type
3550 *
100fef9d 3551 * @param int $financialTypeId
5a18a545 3552 *
3553 * @return FinancialAccountId
3554 */
00be9182 3555 public static function getFinancialAccountId($financialTypeId) {
5a18a545 3556 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3557 $searchParams = array(
3558 'entity_table' => 'civicrm_financial_type',
3559 'entity_id' => $financialTypeId,
3560 'account_relationship' => $accountRel,
3561 );
3562 $result = array();
f2b2a3ff 3563 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
5a18a545 3564
f2b2a3ff 3565 return CRM_Utils_Array::value('financial_account_id', $result);
5a18a545 3566 }
b5935203 3567
7a9ab499
EM
3568 /**
3569 * Check tax amount.
3570 *
3571 * @param array $params
3572 * @param bool $isLineItem
3573 *
3574 * @return mixed
3575 */
115fa278 3576 public static function checkTaxAmount($params, $isLineItem = FALSE) {
b5935203 3577 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
3578
7a9ab499 3579 // Update contribution.
b5935203 3580 if (!empty($params['id'])) {
3581 $id = $params['id'];
3582 $values = $ids = array();
3583 $contrbutionParams = array('id' => $id);
3584 $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
3585
3586 // To assign pervious finantial type on update of contribution
f2b2a3ff 3587 if (!isset($params['financial_type_id'])) {
b5935203 3588 $params['financial_type_id'] = $prevContributionValue->financial_type_id;
3589 }
4c9b6178 3590 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
b5935203 3591 // Assisn tax Amount on update of contrbution
3592 if (!empty($prevContributionValue->tax_amount)) {
3593 $params['tax_amount'] = 'null';
3594 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3595 foreach ($params['line_item'] as $setID => $priceField) {
3596 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3597 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3598 }
3599 }
3600 }
3601 }
3602 }
3603
3604 // New Contrbution and update of contribution with tax rate financial type
5525990d 3605 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
f2b2a3ff
TO
3606 empty($params['skipLineItem']) && !$isLineItem
3607 ) {
3608 $taxRateParams = $taxRates[$params['financial_type_id']];
3609 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams);
3610 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
b5935203 3611
f2b2a3ff
TO
3612 // Get Line Item on update of contribution
3613 if (isset($params['id'])) {
3614 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3615 }
3616 else {
3617 CRM_Price_BAO_LineItem::getLineItemArray($params);
3618 }
3619 foreach ($params['line_item'] as $setID => $priceField) {
3620 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3621 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
b5935203 3622 }
5525990d 3623 }
f2b2a3ff
TO
3624 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3625 }
4c9b6178 3626 elseif (isset($params['api.line_item.create'])) {
5525990d 3627 // Update total amount of contribution using lineItem
b5935203 3628 $taxAmountArray = array();
3629 foreach ($params['api.line_item.create'] as $key => $value) {
3630 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
f2b2a3ff 3631 $taxRate = $taxRates[$value['financial_type_id']];
5525990d 3632 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
b5935203 3633 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3634 }
3635 }
3636 $params['tax_amount'] = array_sum($taxAmountArray);
5525990d 3637 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
b5935203 3638 }
3639 else {
3640 // update line item of contrbution
3641 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3642 $taxRate = $taxRates[$params['financial_type_id']];
3643 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
3644 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3645 }
3646 }
3647 return $params;
3648 }
96025800 3649
5ce9cbe9 3650}