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