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