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