Merge pull request #10185 from eileenmcnaughton/master
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
34
35 /**
100fef9d 36 * Static field for all the contribution information that we can potentially import
6a488035
TO
37 *
38 * @var array
6a488035
TO
39 */
40 static $_importableFields = NULL;
41
42 /**
100fef9d 43 * Static field for all the contribution information that we can potentially export
6a488035
TO
44 *
45 * @var array
6a488035
TO
46 */
47 static $_exportableFields = NULL;
48
9c472292
PN
49 /**
50 * Static field to hold financial trxn id's.
51 *
52 * @var array
53 */
54 static $_trxnIDs = NULL;
55
6a488035 56 /**
100fef9d 57 * Field for all the objects related to this contribution
6a488035
TO
58 * @var array of objects (e.g membership object, participant object)
59 */
60 public $_relatedObjects = array();
61
62 /**
100fef9d 63 * Field for the component - either 'event' (participant) or 'contribute'
6a488035
TO
64 * (any item related to a contribution page e.g. membership, pledge, contribution)
65 * This is used for composing messages because they have dependency on the
66 * contribution_page or event page - although over time we may eliminate that
67 *
68 * @var string component or event
69 */
70 public $_component = NULL;
71
0be43473
EM
72 /**
73 * Possibly obsolete variable.
74 *
75 * If you use it please explain why it is set in the create function here.
76 *
77 * @var string
78 */
79 public $trxn_result_code;
80
186c9c17 81 /**
fe482240 82 * Class constructor.
186c9c17 83 */
00be9182 84 public function __construct() {
6a488035
TO
85 parent::__construct();
86 }
87
88 /**
fe482240 89 * Takes an associative array and creates a contribution object.
6a488035
TO
90 *
91 * the function extract all the params it needs to initialize the create a
92 * contribution object. the params array could contain additional unused name/value
93 * pairs
94 *
014c4014
TO
95 * @param array $params
96 * (reference ) an assoc array of name/value pairs.
97 * @param array $ids
98 * The array that holds all the db ids.
6a488035 99 *
bed98343 100 * @return CRM_Contribute_BAO_Contribution|void
6a488035 101 */
00be9182 102 public static function add(&$params, $ids = array()) {
6a488035 103 if (empty($params)) {
bed98343 104 return NULL;
6a488035 105 }
504a78f6 106 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
107 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
6a488035 108 $duplicates = array();
504a78f6 109 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
6a488035
TO
110 $error = CRM_Core_Error::singleton();
111 $d = implode(', ', $duplicates);
112 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
113 'Fatal',
114 array($d),
115 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
116 );
117 return $error;
118 }
119
120 // first clean up all the money fields
121 $moneyFields = array(
122 'total_amount',
123 'net_amount',
124 'fee_amount',
125 'non_deductible_amount',
126 );
ae06c851 127
6a488035 128 //if priceset is used, no need to cleanup money
a7488080 129 if (!empty($params['skipCleanMoney'])) {
6a488035
TO
130 unset($moneyFields[0]);
131 }
132
133 foreach ($moneyFields as $field) {
134 if (isset($params[$field])) {
135 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
136 }
137 }
48ea0708 138
16e268ad 139 //set defaults in create mode
140 if (!$contributionID) {
141 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
142 }
143
b929cdb4 144 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
4add5adb
GC
145 //if contribution is created with cancelled or refunded status, add credit note id
146 if (!empty($params['contribution_status_id'])) {
52da5b1e 147 // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id'])
4add5adb 148 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
16e268ad 149 || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
4add5adb 150 ) {
8d20d89c 151 if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
4add5adb
GC
152 $params['creditnote_id'] = self::createCreditNoteId();
153 }
154 }
155 }
76c28c8d
DG
156 else {
157 // Since the fee amount is expecting this (later on) ensure it is always set.
158 // It would only not be set for an update where it is unchanged.
16e268ad 159 $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id'));
76c28c8d 160 }
4add5adb 161
8cf6bd83
PN
162 if (!$contributionID
163 && CRM_Utils_Array::value('membership_id', $params)
164 && self::checkContributeSettings('deferred_revenue_enabled')
165 ) {
166 $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date');
167 if ($memberStartDate) {
168 $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate));
169 }
170 }
080a561b 171 self::calculateMissingAmountParams($params, $contributionID);
6a488035 172
a7488080 173 if (!empty($params['payment_instrument_id'])) {
6a488035
TO
174 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
175 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
176 $params['check_number'] = 'null';
177 }
178 }
179
5e494d5c 180 $setPrevContribution = TRUE;
f8325309 181 // CRM-13964 partial payment
5e494d5c
PJ
182 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
183 $partialAmtTotal = $params['partial_payment_total'];
184 $partialAmtPay = $params['partial_amount_pay'];
185 $params['total_amount'] = $partialAmtTotal;
186 if ($partialAmtPay < $partialAmtTotal) {
ede1935f 187 $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name');
5e494d5c
PJ
188 $params['is_pay_later'] = 0;
189 $setPrevContribution = FALSE;
f8325309
PJ
190 }
191 }
19393e51 192 if ($contributionID && $setPrevContribution) {
2912ed09 193 $params['prevContribution'] = self::getOriginalContribution($contributionID);
19393e51 194 }
ede1935f 195
0193c00f 196 if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution'])
e937b376 197 && !($contributionStatus[$params['prevContribution']->contribution_status_id] == 'Pending')
1a55f42e
PN
198 && !self::allowUpdateRevenueRecognitionDate($contributionID)
199 ) {
200 unset($params['revenue_recognition_date']);
201 }
96039749 202
bf4385cb
SL
203 if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) ||
204 isset($params['financial_type_id']))) {
1fca875f 205 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
2912ed09 206 }
207
504a78f6 208 if ($contributionID) {
209 CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
6a488035
TO
210 }
211 else {
212 CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
213 }
6a488035
TO
214 $contribution = new CRM_Contribute_BAO_Contribution();
215 $contribution->copyValues($params);
216
504a78f6 217 $contribution->id = $contributionID;
6a488035 218
10cd9458 219 if (empty($contribution->id)) {
220 // (only) on 'create', make sure that a valid currency is set (CRM-16845)
221 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
4e92d4f4 222 $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency;
10cd9458 223 }
6a488035
TO
224 }
225
6a488035
TO
226 $result = $contribution->save();
227
228 // Add financial_trxn details as part of fix for CRM-4724
229 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
230 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
231
232 //add Account details
233 $params['contribution'] = $contribution;
0aaf8fe9 234 self::recordFinancialAccounts($params);
6a488035 235
91259407 236 if (self::isUpdateToRecurringContribution($params)) {
237 CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment(
d4009c22 238 (!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id),
91259407 239 $contributionStatus[$params['contribution_status_id']]
240 );
241 }
242
2b68a50c 243 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035 244
504a78f6 245 if ($contributionID) {
6a488035
TO
246 CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
247 }
248 else {
249 CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
250 }
251
252 return $result;
253 }
254
91259407 255 /**
256 * Is this contribution updating an existing recurring contribution.
257 *
258 * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial
259 * pending payment is being confirmed (or failing).
260 *
261 * @param array $params
262 *
263 * @return bool
264 */
265 public static function isUpdateToRecurringContribution($params) {
266 if (!empty($params['contribution_recur_id']) && empty($params['id'])) {
267 return TRUE;
268 }
269 if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) {
270 return FALSE;
271 }
272 if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) {
273 return FALSE;
274 }
275 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
276 if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) {
277 return TRUE;
278 }
279 return FALSE;
280 }
281
44a2db2b 282 /**
fe482240 283 * Get defaults for new entity.
44a2db2b
EM
284 * @return array
285 */
00be9182 286 public static function getDefaults() {
44a2db2b
EM
287 return array(
288 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
289 FALSE, FALSE, FALSE, 'AND is_default = 1')
290 ),
291 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'),
292 );
44a2db2b
EM
293 }
294
6a488035 295 /**
9a7e53b0 296 * Fetch the object and store the values in the values array.
6a488035 297 *
014c4014
TO
298 * @param array $params
299 * Input parameters to find object.
300 * @param array $values
301 * Output values of the object.
302 * @param array $ids
303 * The array that holds all the db ids.
6a488035 304 *
a380f4a0
EM
305 * @return CRM_Contribute_BAO_Contribution|null
306 * The found object or null
6a488035 307 */
0816949d 308 public static function getValues($params, &$values, &$ids) {
6a488035
TO
309 if (empty($params)) {
310 return NULL;
311 }
312 $contribution = new CRM_Contribute_BAO_Contribution();
313
314 $contribution->copyValues($params);
315
316 if ($contribution->find(TRUE)) {
317 $ids['contribution'] = $contribution->id;
318
319 CRM_Core_DAO::storeValues($contribution, $values);
320
321 return $contribution;
322 }
7e5524d4
TO
323 $null = NULL; // return by reference
324 return $null;
6a488035
TO
325 }
326
99cdd94d 327 /**
328 * Get the values and resolve the most common mappings.
329 *
330 * Since contribution status is resolved in almost every function that calls getValues it makes
331 * sense to have an extra function to resolve it rather than repeat the code.
332 *
333 * Think carefully before adding more mappings to be resolved as there could be performance implications
334 * if this function starts to be called from more iterative functions.
335 *
336 * @param array $params
337 * Input parameters to find object.
338 *
339 * @return array
340 * Array of the found contribution.
341 * @throws CRM_Core_Exception
342 */
343 public static function getValuesWithMappings($params) {
344 $values = $ids = array();
345 $contribution = self::getValues($params, $values, $ids);
346 if (is_null($contribution)) {
347 throw new CRM_Core_Exception('No contribution found');
348 }
349 $values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']);
350 return $values;
351 }
352
44a2db2b 353 /**
0be43473 354 * Calculate net_amount & fee_amount if they are not set.
44a2db2b 355 *
0be43473
EM
356 * Net amount should be total - fee.
357 * This should only be called for new contributions.
358 *
359 * @param array $params
360 * Params for a new contribution before they are saved.
080a561b 361 * @param int|null $contributionID
362 * Contribution ID if we are dealing with an update.
363 *
364 * @throws \CiviCRM_API3_Exception
44a2db2b 365 */
080a561b 366 public static function calculateMissingAmountParams(&$params, $contributionID) {
367 if (!$contributionID && !isset($params['fee_amount'])) {
44a2db2b
EM
368 if (isset($params['total_amount']) && isset($params['net_amount'])) {
369 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
370 }
371 else {
372 $params['fee_amount'] = 0;
373 }
374 }
375 if (!isset($params['net_amount'])) {
080a561b 376 if (!$contributionID) {
377 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
378 }
379 else {
380 if (isset($params['fee_amount']) || isset($params['total_amount'])) {
381 // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount.
382 // net_amount may need adjusting.
383 $contribution = civicrm_api3('Contribution', 'getsingle', array(
384 'id' => $contributionID,
385 'return' => array('total_amount', 'net_amount'),
386 ));
387 $totalAmount = isset($params['total_amount']) ? $params['total_amount'] : CRM_Utils_Array::value('total_amount', $contribution);
388 $feeAmount = isset($params['fee_amount']) ? $params['fee_amount'] : CRM_Utils_Array::value('fee_amount', $contribution);
389 $params['net_amount'] = $totalAmount - $feeAmount;
390 }
391 }
44a2db2b
EM
392 }
393 }
394
0816949d
EM
395 /**
396 * @param $params
397 * @param $billingLocationTypeID
398 *
399 * @return array
400 */
401 protected static function getBillingAddressParams($params, $billingLocationTypeID) {
402 $hasBillingField = FALSE;
403 $billingFields = array(
404 'street_address',
405 'city',
406 'state_province_id',
407 'postal_code',
408 'country_id',
409 );
410
411 //build address array
412 $addressParams = array();
413 $addressParams['location_type_id'] = $billingLocationTypeID;
414 $addressParams['is_billing'] = 1;
415
416 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
417 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
418 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
419 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
420
421 foreach ($billingFields as $value) {
422 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
423 if (!empty($addressParams[$value])) {
424 $hasBillingField = TRUE;
425 }
426 }
427 return array($hasBillingField, $addressParams);
428 }
429
430 /**
431 * Get address params ready to be passed to the payment processor.
432 *
433 * We need address params in a couple of formats. For the payment processor we wan state_province_id-5.
434 * To create an address we need state_province_id.
435 *
436 * @param array $params
437 * @param int $billingLocationTypeID
438 *
439 * @return array
440 */
441 public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) {
442 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
443 foreach ($addressParams as $name => $field) {
444 if (substr($name, 0, 8) == 'billing_') {
445 $addressParams[substr($name, 9)] = $addressParams[$field];
446 }
447 }
448 return array($hasBillingField, $addressParams);
449 }
450
2243fe93
EM
451 /**
452 * Get the number of terms for this contribution for a given membership type
453 * based on querying the line item table and relevant price field values
454 * Note that any one contribution should only be able to have one line item relating to a particular membership
455 * type
a284891b 456 *
2243fe93
EM
457 * @param int $membershipTypeID
458 *
a284891b
EM
459 * @param int $contributionID
460 *
2243fe93
EM
461 * @return int
462 */
a284891b 463 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
f2b2a3ff 464 $numTerms = CRM_Core_DAO::singleValueQuery("
2243fe93
EM
465 SELECT membership_num_terms FROM civicrm_line_item li
466 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
29347f3d 467 WHERE contribution_id = %1 AND membership_type_id = %2",
f2b2a3ff 468 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
2243fe93
EM
469 );
470 // default of 1 is precautionary
471 return empty($numTerms) ? 1 : $numTerms;
472 }
473
6a488035 474 /**
fe482240 475 * Takes an associative array and creates a contribution object.
6a488035 476 *
014c4014
TO
477 * @param array $params
478 * (reference ) an assoc array of name/value pairs.
479 * @param array $ids
480 * The array that holds all the db ids.
6a488035 481 *
16b10e64 482 * @return CRM_Contribute_BAO_Contribution
6a488035 483 */
00be9182 484 public static function create(&$params, $ids = array()) {
46d173ef 485 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date');
6a488035
TO
486 foreach ($dateFields as $df) {
487 if (isset($params[$df])) {
488 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
489 }
490 }
491
4add5adb
GC
492 //if contribution is created with cancelled or refunded status, add credit note id
493 if (!empty($params['contribution_status_id'])) {
494 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
495
496 if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus)
497 || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus))
498 ) {
8d20d89c 499 if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
4add5adb
GC
500 $params['creditnote_id'] = self::createCreditNoteId();
501 }
502 }
503 }
504
6a488035
TO
505 $transaction = new CRM_Core_Transaction();
506
6a488035
TO
507 $contribution = self::add($params, $ids);
508
509 if (is_a($contribution, 'CRM_Core_Error')) {
510 $transaction->rollback();
511 return $contribution;
512 }
513
514 $params['contribution_id'] = $contribution->id;
515
a7488080 516 if (!empty($params['custom']) &&
6a488035
TO
517 is_array($params['custom'])
518 ) {
519 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
520 }
521
522 $session = CRM_Core_Session::singleton();
523
a7488080 524 if (!empty($params['note'])) {
6a488035
TO
525 $noteParams = array(
526 'entity_table' => 'civicrm_contribution',
527 'note' => $params['note'],
528 'entity_id' => $contribution->id,
529 'contact_id' => $session->get('userID'),
530 'modified_date' => date('Ymd'),
531 );
532 if (!$noteParams['contact_id']) {
533 $noteParams['contact_id'] = $params['contact_id'];
534 }
504a78f6 535 CRM_Core_BAO_Note::add($noteParams);
6a488035
TO
536 }
537
538 // make entry in batch entity batch table
a7488080 539 if (!empty($params['batch_id'])) {
6a488035
TO
540 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
541 $titleFields = array(
542 'contact_id',
543 'total_amount',
544 'currency',
545 'financial_type_id',
546 );
d37ade2e 547 $retrieveRequired = 0;
6a488035 548 foreach ($titleFields as $titleField) {
f2b2a3ff 549 if (!isset($contribution->$titleField)) {
d37ade2e 550 $retrieveRequired = 1;
6a488035
TO
551 break;
552 }
553 }
d37ade2e 554 if ($retrieveRequired == 1) {
2cfc0f58 555 $contribution->find(TRUE);
6a488035
TO
556 }
557 }
558
7a13735b 559 CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
2cfc0f58 560
6a488035
TO
561 $transaction->commit();
562
464ff9cc
EM
563 // check if activity record exist for this contribution, if
564 // not add activity
565 $activity = new CRM_Activity_DAO_Activity();
566 $activity->source_record_id = $contribution->id;
567 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
568 'Contribution',
569 'name'
570 );
6e143f06
WA
571
572 //CRM-18406: Update activity when edit contribution.
573 if ($activity->find(TRUE)) {
464ff9cc
EM
574 // CRM-13237 : if activity record found, update it with campaign id of contribution
575 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
6e143f06 576 $contribution->activity_id = $activity->id;
464ff9cc 577 }
3f160c1c 578 if (empty($contribution->contact_id)) {
579 $contribution->find(TRUE);
580 }
6e143f06 581 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
464ff9cc 582
6a488035 583 // do not add to recent items for import, CRM-4399
a7488080 584 if (empty($params['skipRecentView'])) {
6a488035
TO
585 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
586 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
587 );
588 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
589 $titleFields = array(
590 'contact_id',
591 'total_amount',
592 'currency',
593 'financial_type_id',
594 );
d37ade2e 595 $retrieveRequired = 0;
6a488035 596 foreach ($titleFields as $titleField) {
f2b2a3ff 597 if (!isset($contribution->$titleField)) {
d37ade2e 598 $retrieveRequired = 1;
6a488035
TO
599 break;
600 }
601 }
f2b2a3ff 602 if ($retrieveRequired == 1) {
2cfc0f58 603 $contribution->find(TRUE);
6a488035
TO
604 }
605 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
606 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
607
608 $recentOther = array();
609 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
610 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
611 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
612 );
613 }
614
615 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
616 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
617 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
618 );
619 }
620
621 // add the recently created Contribution
622 CRM_Utils_Recent::add($title,
623 $url,
624 $contribution->id,
625 'Contribution',
626 $contribution->contact_id,
627 NULL,
628 $recentOther
629 );
630 }
631
632 return $contribution;
633 }
634
635 /**
636 * Get the values for pseudoconstants for name->value and reverse.
637 *
014c4014
TO
638 * @param array $defaults
639 * (reference) the default values, some of which need to be resolved.
640 * @param bool $reverse
641 * True if we want to resolve the values in the reverse direction (value -> name).
6a488035 642 */
00be9182 643 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
6a488035
TO
644 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
645 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
646 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
647 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
648 }
649
650 /**
74ab7ba8 651 * Convert associative array names to values and vice-versa.
6a488035
TO
652 *
653 * This function is used by both the web form layer and the api. Note that
654 * the api needs the name => value conversion, also the view layer typically
655 * requires value => name conversion
74ab7ba8
EM
656 *
657 * @param array $defaults
658 * @param string $property
659 * @param array $lookup
660 * @param bool $reverse
661 *
662 * @return bool
6a488035 663 */
00be9182 664 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
6a488035
TO
665 $id = $property . '_id';
666
667 $src = $reverse ? $property : $id;
668 $dst = $reverse ? $id : $property;
669
670 if (!array_key_exists($src, $defaults)) {
671 return FALSE;
672 }
673
674 $look = $reverse ? array_flip($lookup) : $lookup;
675
676 if (is_array($look)) {
677 if (!array_key_exists($defaults[$src], $look)) {
678 return FALSE;
679 }
680 }
681 $defaults[$dst] = $look[$defaults[$src]];
682 return TRUE;
683 }
684
685 /**
fe482240
EM
686 * Retrieve DB object based on input parameters.
687 *
688 * It also stores all the retrieved values in the default array.
6a488035 689 *
014c4014
TO
690 * @param array $params
691 * (reference ) an assoc array of name/value pairs.
692 * @param array $defaults
693 * (reference ) an assoc array to hold the name / value pairs.
6a488035 694 * in a hierarchical manner
014c4014
TO
695 * @param array $ids
696 * (reference) the array that holds all the db ids.
6a488035 697 *
16b10e64 698 * @return CRM_Contribute_BAO_Contribution
6a488035 699 */
00be9182 700 public static function retrieve(&$params, &$defaults, &$ids) {
6a488035
TO
701 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
702 return $contribution;
703 }
704
705 /**
fe482240 706 * Combine all the importable fields from the lower levels object.
6a488035
TO
707 *
708 * The ordering is important, since currently we do not have a weight
709 * scheme. Adding weight is super important and should be done in the
710 * next week or so, before this can be called complete.
711 *
8efea814
EM
712 * @param string $contactType
713 * @param bool $status
714 *
a6c01b45
CW
715 * @return array
716 * array of importable Fields
6a488035 717 */
00be9182 718 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
6a488035
TO
719 if (!self::$_importableFields) {
720 if (!self::$_importableFields) {
721 self::$_importableFields = array();
722 }
723
724 if (!$status) {
725 $fields = array('' => array('title' => ts('- do not import -')));
726 }
727 else {
728 $fields = array('' => array('title' => ts('- Contribution Fields -')));
729 }
730
731 $note = CRM_Core_DAO_Note::import();
732 $tmpFields = CRM_Contribute_DAO_Contribution::import();
733 unset($tmpFields['option_value']);
734 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
c2585c5b 735 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
6a488035
TO
736
737 // Using new Dedupe rule.
738 $ruleParams = array(
c2585c5b 739 'contact_type' => $contactType,
f2b2a3ff 740 'used' => 'Unsupervised',
6a488035
TO
741 );
742 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
c2585c5b 743 $tmpContactField = array();
6a488035
TO
744 if (is_array($fieldsArray)) {
745 foreach ($fieldsArray as $value) {
746 //skip if there is no dupe rule
747 if ($value == 'none') {
748 continue;
749 }
750 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
751 $value,
752 'id',
753 'column_name'
754 );
755 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
c2585c5b 756 $tmpContactField[trim($value)] = $contactFields[trim($value)];
6a488035 757 if (!$status) {
c2585c5b 758 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
6a488035
TO
759 }
760 else {
c2585c5b 761 $title = $tmpContactField[trim($value)]['title'];
6a488035 762 }
c2585c5b 763 $tmpContactField[trim($value)]['title'] = $title;
6a488035
TO
764 }
765 }
766
c2585c5b 767 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
768 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
6a488035 769 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
c2585c5b 770 $fields = array_merge($fields, $tmpContactField);
6a488035
TO
771 $fields = array_merge($fields, $tmpFields);
772 $fields = array_merge($fields, $note);
773 $fields = array_merge($fields, $optionFields);
774 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
775 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
776 self::$_importableFields = $fields;
777 }
778 return self::$_importableFields;
779 }
780
9d5c7f14 781 /**
782 * Get exportable fields with pseudoconstants rendered as an extra field.
783 */
784 public static function getExportableFieldsWithPseudoConstants() {
785 $fields = self::exportableFields();
786 CRM_Core_DAO::appendPseudoConstantsToFields($fields);
787 return $fields;
788 }
789
186c9c17 790 /**
e9ff5391 791 * Combine all the exportable fields from the lower level objects.
792 *
793 * @param bool $checkPermission
794 *
186c9c17 795 * @return array
e9ff5391 796 * array of exportable Fields
186c9c17 797 */
5837835b 798 public static function &exportableFields($checkPermission = TRUE) {
6a488035
TO
799 if (!self::$_exportableFields) {
800 if (!self::$_exportableFields) {
801 self::$_exportableFields = array();
802 }
803
f2b2a3ff
TO
804 $impFields = CRM_Contribute_DAO_Contribution::export();
805 $expFieldProduct = CRM_Contribute_DAO_Product::export();
806 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
807 $typeField = CRM_Financial_DAO_FinancialType::export();
808 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
6a488035 809
3c151c70 810 $contributionPage = array(
811 'contribution_page' => array(
812 'title' => ts('Contribution Page'),
813 'name' => 'contribution_page',
814 'where' => 'civicrm_contribution_page.title',
a130e045 815 'data_type' => CRM_Utils_Type::T_STRING,
bed98343 816 ),
a130e045 817 );
3c151c70 818
6a488035 819 $contributionNote = array(
a130e045
DG
820 'contribution_note' => array(
821 'title' => ts('Contribution Note'),
822 'name' => 'contribution_note',
823 'data_type' => CRM_Utils_Type::T_TEXT,
824 ),
6a488035
TO
825 );
826
6a488035 827 $extraFields = array(
82a43d71 828 'contribution_batch' => array(
21dfd5f5
TO
829 'title' => ts('Batch Name'),
830 ),
6a488035
TO
831 );
832
124b978e
WA
833 // CRM-17787
834 $campaignTitle = array(
835 'contribution_campaign_title' => array(
836 'title' => ts('Campaign Title'),
837 'name' => 'campaign_title',
838 'where' => 'civicrm_campaign.title',
839 'data_type' => CRM_Utils_Type::T_STRING,
840 ),
841 );
81ec6180
DS
842 $softCreditFields = array(
843 'contribution_soft_credit_name' => array(
844 'name' => 'contribution_soft_credit_name',
e300cf31 845 'title' => ts('Soft Credit For'),
81ec6180 846 'where' => 'civicrm_contact_d.display_name',
21dfd5f5 847 'data_type' => CRM_Utils_Type::T_STRING,
81ec6180
DS
848 ),
849 'contribution_soft_credit_amount' => array(
850 'name' => 'contribution_soft_credit_amount',
e300cf31 851 'title' => ts('Soft Credit Amount'),
81ec6180 852 'where' => 'civicrm_contribution_soft.amount',
21dfd5f5 853 'data_type' => CRM_Utils_Type::T_MONEY,
81ec6180
DS
854 ),
855 'contribution_soft_credit_type' => array(
856 'name' => 'contribution_soft_credit_type',
e300cf31 857 'title' => ts('Soft Credit Type'),
81ec6180 858 'where' => 'contribution_softcredit_type.label',
21dfd5f5 859 'data_type' => CRM_Utils_Type::T_STRING,
81ec6180
DS
860 ),
861 'contribution_soft_credit_contribution_id' => array(
862 'name' => 'contribution_soft_credit_contribution_id',
e300cf31 863 'title' => ts('Soft Credit For Contribution ID'),
81ec6180 864 'where' => 'civicrm_contribution_soft.contribution_id',
21dfd5f5 865 'data_type' => CRM_Utils_Type::T_INT,
81ec6180 866 ),
5850d2e9 867 'contribution_soft_credit_contact_id' => array(
868 'name' => 'contribution_soft_credit_contact_id',
e300cf31 869 'title' => ts('Soft Credit For Contact ID'),
9a74243e 870 'where' => 'civicrm_contact_d.id',
5850d2e9 871 'data_type' => CRM_Utils_Type::T_INT,
872 ),
81ec6180
DS
873 );
874
6ffab5b7
WA
875 // CRM-16713 - contribution search by Premiums on 'Find Contribution' form.
876 $premiums = array(
877 'contribution_product_id' => array(
878 'title' => ts('Premium'),
879 'name' => 'contribution_product_id',
880 'where' => 'civicrm_product.id',
881 'data_type' => CRM_Utils_Type::T_INT,
882 ),
883 );
884
9d5c7f14 885 $fields = array_merge($impFields, $typeField, $contributionPage, $expFieldProduct,
3123273f 886 $expFieldsContrib, $contributionNote, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle,
5837835b 887 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission)
6a488035
TO
888 );
889
890 self::$_exportableFields = $fields;
891 }
892
893 return self::$_exportableFields;
894 }
895
186c9c17
EM
896 /**
897 * @param null $status
898 * @param null $startDate
899 * @param null $endDate
900 *
901 * @return array|null
902 */
00be9182 903 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
6a488035
TO
904 $where = array();
905 switch ($status) {
906 case 'Valid':
907 $where[] = 'contribution_status_id = 1';
908 break;
909
910 case 'Cancelled':
911 $where[] = 'contribution_status_id = 3';
912 break;
913 }
914
915 if ($startDate) {
916 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
917 }
918 if ($endDate) {
919 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
920 }
40c655aa 921 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
54d8de6b 922 if ($financialTypes) {
40c655aa
E
923 $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
924 $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
925 }
54d8de6b
E
926 else {
927 $where[] = "c.financial_type_id IN (0)";
928 }
6a488035
TO
929
930 $whereCond = implode(' AND ', $where);
931
932 $query = "
933 SELECT sum( total_amount ) as total_amount,
54d8de6b 934 count( c.id ) as total_count,
6a488035 935 currency
54d8de6b
E
936 FROM civicrm_contribution c
937INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id )
938LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' )
6a488035
TO
939 WHERE $whereCond
940 AND ( is_test = 0 OR is_test IS NULL )
941 AND contact.is_deleted = 0
942 GROUP BY currency
943";
944
9d2678f4 945 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 946 $amount = array();
f2b2a3ff 947 $count = 0;
6a488035
TO
948 while ($dao->fetch()) {
949 $count += $dao->total_count;
950 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
951 }
952 if ($count) {
f2b2a3ff
TO
953 return array(
954 'amount' => implode(', ', $amount),
6a488035
TO
955 'count' => $count,
956 );
957 }
958 return NULL;
959 }
960
961 /**
fe482240 962 * Delete the indirect records associated with this contribution first.
6a488035 963 *
100fef9d 964 * @param int $id
8efea814 965 *
72b3a70c
CW
966 * @return mixed|null
967 * $results no of deleted Contribution on success, false otherwise
6a488035 968 */
00be9182 969 public static function deleteContribution($id) {
6a488035
TO
970 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
971
972 $transaction = new CRM_Core_Transaction();
973
974 $results = NULL;
975 //delete activity record
976 $params = array(
977 'source_record_id' => $id,
978 // activity type id for contribution
979 'activity_type_id' => 6,
980 );
981
982 CRM_Activity_BAO_Activity::deleteActivity($params);
983
984 //delete billing address if exists for this contribution.
985 self::deleteAddress($id);
986
987 //update pledge and pledge payment, CRM-3961
988 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
989
990 // remove entry from civicrm_price_set_entity, CRM-5095
9da8dc8c 991 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
992 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
6a488035
TO
993 }
994 // cleanup line items.
995 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
996
de1c25e1
PN
997 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
998 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
6a488035
TO
999
1000 if ($participantId) {
1001 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
1002 }
1003 else {
1004 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
1005 }
1006
1007 //delete note.
1008 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
1009 $noteId = key($note);
1010 if ($noteId) {
1011 CRM_Core_BAO_Note::del($noteId, FALSE);
1012 }
1013
1014 $dao = new CRM_Contribute_DAO_Contribution();
1015 $dao->id = $id;
1016
1017 $results = $dao->delete();
1018
1019 $transaction->commit();
1020
1021 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
1022
1023 // delete the recently created Contribution
1024 $contributionRecent = array(
1025 'id' => $id,
1026 'type' => 'Contribution',
1027 );
1028 CRM_Utils_Recent::del($contributionRecent);
1029
1030 return $results;
1031 }
1032
7758bd2b
EM
1033 /**
1034 * React to a financial transaction (payment) failure.
1035 *
1036 * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted
1037 * payments is important for forensic and outreach reasons.
1038 *
06d062ce 1039 * @param int $contributionID
ad37ac8e 1040 * @param int $contactID
06d062ce 1041 * @param string $message
ad37ac8e 1042 *
1043 * @throws \CiviCRM_API3_Exception
7758bd2b 1044 */
06d062ce
EM
1045 public static function failPayment($contributionID, $contactID, $message) {
1046 civicrm_api3('activity', 'create', array(
1047 'activity_type_id' => 'Failed Payment',
1048 'details' => $message,
1049 'subject' => ts('Payment failed at payment processor'),
1050 'source_record_id' => $contributionID,
1051 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1052 $contactID,
1053 ));
ee165a1c
ML
1054
1055 // CRM-20336 Make sure that the contribution status is Failed, not Pending.
ee165a1c
ML
1056 civicrm_api3('contribution', 'create', array(
1057 'id' => $contributionID,
d7b226af 1058 'contribution_status_id' => 'Failed',
ee165a1c 1059 ));
7758bd2b
EM
1060 }
1061
6a488035 1062 /**
fe482240 1063 * Check if there is a contribution with the same trxn_id or invoice_id.
6a488035 1064 *
014c4014
TO
1065 * @param array $input
1066 * An assoc array of name/value pairs.
1067 * @param array $duplicates
16b10e64 1068 * (reference) store ids of duplicate contribs.
100fef9d 1069 * @param int $id
6a488035 1070 *
a130e045 1071 * @return bool
a6c01b45 1072 * true if duplicate, false otherwise
6a488035 1073 */
00be9182 1074 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
6a488035
TO
1075 if (!$id) {
1076 $id = CRM_Utils_Array::value('id', $input);
1077 }
1078 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
1079 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
1080
1081 $clause = array();
1082 $input = array();
1083
1084 if ($trxn_id) {
1085 $clause[] = "trxn_id = %1";
1086 $input[1] = array($trxn_id, 'String');
1087 }
1088
1089 if ($invoice_id) {
1090 $clause[] = "invoice_id = %2";
1091 $input[2] = array($invoice_id, 'String');
1092 }
1093
1094 if (empty($clause)) {
1095 return FALSE;
1096 }
1097
1098 $clause = implode(' OR ', $clause);
1099 if ($id) {
1100 $clause = "( $clause ) AND id != %3";
1101 $input[3] = array($id, 'Integer');
1102 }
1103
f2b2a3ff
TO
1104 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1105 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
1106 $result = FALSE;
1107 while ($dao->fetch()) {
1108 $duplicates[] = $dao->id;
1109 $result = TRUE;
1110 }
1111 return $result;
1112 }
1113
1114 /**
fe482240 1115 * Takes an associative array and creates a contribution_product object.
6a488035
TO
1116 *
1117 * the function extract all the params it needs to initialize the create a
1118 * contribution_product object. the params array could contain additional unused name/value
1119 * pairs
1120 *
014c4014 1121 * @param array $params
16b10e64 1122 * (reference) an assoc array of name/value pairs.
6a488035 1123 *
16b10e64 1124 * @return CRM_Contribute_DAO_ContributionProduct
6a488035 1125 */
00be9182 1126 public static function addPremium(&$params) {
6a488035
TO
1127 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
1128 $contributionProduct->copyValues($params);
1129 return $contributionProduct->save();
1130 }
1131
1132 /**
fe482240 1133 * Get list of contribution fields for profile.
6a488035
TO
1134 * For now we only allow custom contribution fields to be in
1135 * profile
1136 *
014c4014
TO
1137 * @param bool $addExtraFields
1138 * True if special fields needs to be added.
6a488035 1139 *
a6c01b45
CW
1140 * @return array
1141 * the list of contribution fields
6a488035 1142 */
00be9182 1143 public static function getContributionFields($addExtraFields = TRUE) {
6a488035 1144 $contributionFields = CRM_Contribute_DAO_Contribution::export();
9d5c7f14 1145 // @todo remove this - this line was added because payment_instrument_id was not
1146 // set to exportable - but now it is.
6a488035
TO
1147 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
1148
1149 if ($addExtraFields) {
1150 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
1151 }
1152
1153 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
1154
1155 foreach ($contributionFields as $key => $var) {
1156 if ($key == 'contribution_contact_id') {
1157 continue;
1158 }
1159 elseif ($key == 'contribution_campaign_id') {
1160 $var['title'] = ts('Campaign');
1161 }
1162 $fields[$key] = $var;
1163 }
1164
1165 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
1166 return $fields;
1167 }
1168
1169 /**
74ab7ba8 1170 * Add extra fields specific to contribution.
6a488035 1171 */
00be9182 1172 public static function getSpecialContributionFields() {
6a488035 1173 $extraFields = array(
81ec6180
DS
1174 'contribution_soft_credit_name' => array(
1175 'name' => 'contribution_soft_credit_name',
e300cf31 1176 'title' => ts('Soft Credit Name'),
6a488035
TO
1177 'headerPattern' => '/^soft_credit_name$/i',
1178 'where' => 'civicrm_contact_d.display_name',
1179 ),
81ec6180
DS
1180 'contribution_soft_credit_email' => array(
1181 'name' => 'contribution_soft_credit_email',
e300cf31 1182 'title' => ts('Soft Credit Email'),
6a488035
TO
1183 'headerPattern' => '/^soft_credit_email$/i',
1184 'where' => 'soft_email.email',
1185 ),
81ec6180
DS
1186 'contribution_soft_credit_phone' => array(
1187 'name' => 'contribution_soft_credit_phone',
e300cf31 1188 'title' => ts('Soft Credit Phone'),
6a488035
TO
1189 'headerPattern' => '/^soft_credit_phone$/i',
1190 'where' => 'soft_phone.phone',
1191 ),
81ec6180
DS
1192 'contribution_soft_credit_contact_id' => array(
1193 'name' => 'contribution_soft_credit_contact_id',
e300cf31 1194 'title' => ts('Soft Credit Contact ID'),
6a488035
TO
1195 'headerPattern' => '/^soft_credit_contact_id$/i',
1196 'where' => 'civicrm_contribution_soft.contact_id',
1197 ),
03ad81ae
AH
1198 'contribution_pcp_title' => array(
1199 'name' => 'contribution_pcp_title',
e300cf31 1200 'title' => ts('Personal Campaign Page Title'),
03ad81ae
AH
1201 'headerPattern' => '/^contribution_pcp_title$/i',
1202 'where' => 'contribution_pcp.title',
1203 ),
6a488035
TO
1204 );
1205
1206 return $extraFields;
1207 }
1208
186c9c17 1209 /**
100fef9d 1210 * @param int $pageID
186c9c17
EM
1211 *
1212 * @return array
1213 */
00be9182 1214 public static function getCurrentandGoalAmount($pageID) {
6a488035
TO
1215 $query = "
1216SELECT p.goal_amount as goal, sum( c.total_amount ) as total
1217 FROM civicrm_contribution_page p,
1218 civicrm_contribution c
1219 WHERE p.id = c.contribution_page_id
1220 AND p.id = %1
1221 AND c.cancel_date is null
1222GROUP BY p.id
1223";
1224
1225 $config = CRM_Core_Config::singleton();
1226 $params = array(1 => array($pageID, 'Integer'));
f2b2a3ff 1227 $dao = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
1228
1229 if ($dao->fetch()) {
1230 return array($dao->goal, $dao->total);
1231 }
1232 else {
1233 return array(NULL, NULL);
1234 }
1235 }
1236
6a488035 1237 /**
2449fe69 1238 * Get list of contributions which credit the passed in contact ID.
1239 *
1240 * The returned array provides details about the original contribution & donor.
1241 *
1242 * @todo - this is a confusing function called from one place. It has a test. It would be
1243 * nice to deprecate it.
6a488035 1244 *
014c4014
TO
1245 * @param int $honorId
1246 * In Honor of Contact ID.
6a488035 1247 *
72b3a70c
CW
1248 * @return array
1249 * list of contribution fields
6a488035 1250 */
00be9182 1251 public static function getHonorContacts($honorId) {
6a488035 1252 $params = array();
8381af80 1253 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1254 $honorDAO->contact_id = $honorId;
6a488035
TO
1255 $honorDAO->find();
1256
6a488035
TO
1257 $type = CRM_Contribute_PseudoConstant::financialType();
1258
1259 while ($honorDAO->fetch()) {
8381af80 1260 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1261 $contributionDAO->id = $honorDAO->contribution_id;
1262
1263 if ($contributionDAO->find(TRUE)) {
43321dd5 1264 $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id);
8381af80 1265 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1266 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1267 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1268 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1269 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1270 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1271 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1272 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
1273 }
6a488035
TO
1274 }
1275
1276 return $params;
1277 }
1278
1279 /**
fe482240 1280 * Get the sort name of a contact for a particular contribution.
6a488035 1281 *
014c4014
TO
1282 * @param int $id
1283 * Id of the contribution.
6a488035 1284 *
72b3a70c
CW
1285 * @return null|string
1286 * sort name of the contact if found
6a488035 1287 */
00be9182 1288 public static function sortName($id) {
6a488035
TO
1289 $id = CRM_Utils_Type::escape($id, 'Integer');
1290
1291 $query = "
1292SELECT civicrm_contact.sort_name
1293FROM civicrm_contribution, civicrm_contact
1294WHERE civicrm_contribution.contact_id = civicrm_contact.id
1295 AND civicrm_contribution.id = {$id}
1296";
9d2678f4 1297 return CRM_Core_DAO::singleValueQuery($query);
6a488035
TO
1298 }
1299
186c9c17 1300 /**
100fef9d 1301 * @param int $contactID
186c9c17
EM
1302 *
1303 * @return array
1304 */
00be9182 1305 public static function annual($contactID) {
6a488035
TO
1306 if (is_array($contactID)) {
1307 $contactIDs = implode(',', $contactID);
1308 }
1309 else {
1310 $contactIDs = $contactID;
1311 }
1312
1313 $config = CRM_Core_Config::singleton();
1314 $startDate = $endDate = NULL;
1315
1316 $currentMonth = date('m');
1317 $currentDay = date('d');
1318 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1319 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1320 (int ) $config->fiscalYearStart['d'] > $currentDay
1321 )
1322 ) {
1323 $year = date('Y') - 1;
1324 }
1325 else {
1326 $year = date('Y');
1327 }
1328 $nextYear = $year + 1;
1329
1330 if ($config->fiscalYearStart) {
4f25b5f5
TO
1331 $newFiscalYearStart = $config->fiscalYearStart;
1332 if ($newFiscalYearStart['M'] < 10) {
1333 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
6a488035 1334 }
4f25b5f5
TO
1335 if ($newFiscalYearStart['d'] < 10) {
1336 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
6a488035 1337 }
4f25b5f5 1338 $config->fiscalYearStart = $newFiscalYearStart;
6a488035
TO
1339 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1340 }
1341 else {
1342 $monthDay = '0101';
1343 }
1344 $startDate = "$year$monthDay";
1345 $endDate = "$nextYear$monthDay";
48069ca1 1346 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
40c655aa 1347 $additionalWhere = " AND b.financial_type_id IN (0)";
fb260b73 1348 $liWhere = " AND i.financial_type_id IN (0)";
7fb041e3 1349 if (!empty($financialTypes)) {
40c655aa
E
1350 $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL";
1351 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
7fb041e3 1352 }
6a488035
TO
1353 $query = "
1354 SELECT count(*) as count,
1355 sum(total_amount) as amount,
1356 avg(total_amount) as average,
1357 currency
1358 FROM civicrm_contribution b
b880a5ce 1359 LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere
6a488035
TO
1360 WHERE b.contact_id IN ( $contactIDs )
1361 AND b.contribution_status_id = 1
1362 AND b.is_test = 0
1363 AND b.receive_date >= $startDate
1364 AND b.receive_date < $endDate
ad37ac8e 1365 $additionalWhere
6a488035
TO
1366 GROUP BY currency
1367 ";
33621c4f 1368 $dao = CRM_Core_DAO::executeQuery($query);
f2b2a3ff 1369 $count = 0;
6a488035
TO
1370 $amount = $average = array();
1371 while ($dao->fetch()) {
1372 if ($dao->count > 0 && $dao->amount > 0) {
1373 $count += $dao->count;
1374 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1375 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1376 }
1377 }
1378 if ($count > 0) {
1379 return array(
1380 $count,
1381 implode(',&nbsp;', $amount),
1382 implode(',&nbsp;', $average),
1383 );
1384 }
1385 return array(0, 0, 0);
1386 }
1387
1388 /**
1389 * Check if there is a contribution with the params passed in.
a380f4a0 1390 *
6a488035
TO
1391 * Used for trxn_id,invoice_id and contribution_id
1392 *
014c4014
TO
1393 * @param array $params
1394 * An assoc array of name/value pairs.
6a488035 1395 *
a6c01b45
CW
1396 * @return array
1397 * contribution id if success else NULL
6a488035 1398 */
00be9182 1399 public static function checkDuplicateIds($params) {
6a488035
TO
1400 $dao = new CRM_Contribute_DAO_Contribution();
1401
1402 $clause = array();
1403 $input = array();
1404 foreach ($params as $k => $v) {
1405 if ($v) {
1406 $clause[] = "$k = '$v'";
1407 }
1408 }
1409 $clause = implode(' AND ', $clause);
f2b2a3ff
TO
1410 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1411 $dao = CRM_Core_DAO::executeQuery($query, $input);
6a488035
TO
1412
1413 while ($dao->fetch()) {
1414 $result = $dao->id;
1415 return $result;
1416 }
1417 return NULL;
1418 }
1419
1420 /**
fe482240 1421 * Get the contribution details for component export.
6a488035 1422 *
014c4014
TO
1423 * @param int $exportMode
1424 * Export mode.
1425 * @param string $componentIds
1426 * Component ids.
6a488035 1427 *
a6c01b45
CW
1428 * @return array
1429 * associated array
6a488035 1430 */
00be9182 1431 public static function getContributionDetails($exportMode, $componentIds) {
6a488035
TO
1432 $paymentDetails = array();
1433 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1434
1435 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1436 $componentSelect = " civicrm_participant_payment.participant_id id";
1437 $additionalClause = "
1438INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1439AND civicrm_participant_payment.participant_id {$componentClause} )
1440";
1441 }
1442 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1443 $componentSelect = " civicrm_membership_payment.membership_id id";
1444 $additionalClause = "
1445INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1446AND civicrm_membership_payment.membership_id {$componentClause} )
1447";
1448 }
1449 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1450 $componentSelect = " civicrm_pledge_payment.id id";
1451 $additionalClause = "
1452INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1453AND civicrm_pledge_payment.pledge_id {$componentClause} )
1454";
1455 }
1456
1457 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1458 trxn_id, {$componentSelect}
1459FROM civicrm_contribution
1460LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1461LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1462 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1463LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1464LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1465 AND option_group_contribution_status.id = contribution_status.option_group_id )
1466{$additionalClause}
1467";
1468
c7940124 1469 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
1470
1471 while ($dao->fetch()) {
1472 $paymentDetails[$dao->id] = array(
1473 'total_amount' => $dao->total_amount,
1474 'contribution_status' => $dao->status,
1475 'receive_date' => $dao->receive_date,
1476 'pay_instru' => $dao->payment_instrument,
1477 'trxn_id' => $dao->trxn_id,
1478 );
1479 }
1480
1481 return $paymentDetails;
1482 }
1483
1484 /**
c490a46a 1485 * Create address associated with contribution record.
6a488035 1486 *
4914efff
EM
1487 * As long as there is one or more billing field in the parameters we will create the address.
1488 *
1489 * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once
1490 * thought).
1491 *
014c4014 1492 * @param array $params
c490a46a 1493 * @param int $billingLocationTypeID
fd31fa4c 1494 *
72b3a70c
CW
1495 * @return int
1496 * address id
6a488035 1497 */
4914efff 1498 public static function createAddress($params, $billingLocationTypeID) {
0816949d 1499 list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID);
4914efff
EM
1500 if ($hasBillingField) {
1501 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
739a8336 1502 return $address->id;
6a488035 1503 }
739a8336 1504 return NULL;
6a488035 1505
6a488035
TO
1506 }
1507
6a488035 1508 /**
fe482240 1509 * Delete billing address record related contribution.
6a488035 1510 *
c490a46a
CW
1511 * @param int $contributionId
1512 * @param int $contactId
6a488035 1513 */
00be9182 1514 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
6a488035
TO
1515 $clauses = array();
1516 $contactJoin = NULL;
1517
1518 if ($contributionId) {
1519 $clauses[] = "cc.id = {$contributionId}";
1520 }
1521
1522 if ($contactId) {
1523 $clauses[] = "cco.id = {$contactId}";
1524 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1525 }
1526
1527 if (empty($clauses)) {
1528 CRM_Core_Error::fatal();
1529 }
1530
1531 $condition = implode(' OR ', $clauses);
1532
1533 $query = "
1534SELECT ca.id
1535FROM civicrm_address ca
1536INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1537 $contactJoin
1538WHERE $condition
1539";
1540 $dao = CRM_Core_DAO::executeQuery($query);
1541
1542 while ($dao->fetch()) {
1543 $params = array('id' => $dao->id);
1544 CRM_Core_BAO_Block::blockDelete('Address', $params);
1545 }
1546 }
1547
1548 /**
1549 * This function check online pending contribution associated w/
1550 * Online Event Registration or Online Membership signup.
1551 *
014c4014
TO
1552 * @param int $componentId
1553 * Participant/membership id.
1554 * @param string $componentName
1555 * Event/Membership.
6a488035 1556 *
16b10e64
CW
1557 * @return int
1558 * pending contribution id.
6a488035 1559 */
00be9182 1560 public static function checkOnlinePendingContribution($componentId, $componentName) {
6a488035
TO
1561 $contributionId = NULL;
1562 if (!$componentId ||
1563 !in_array($componentName, array('Event', 'Membership'))
1564 ) {
1565 return $contributionId;
1566 }
1567
1568 if ($componentName == 'Event') {
f2b2a3ff 1569 $idName = 'participant_id';
6a488035 1570 $componentTable = 'civicrm_participant';
f2b2a3ff
TO
1571 $paymentTable = 'civicrm_participant_payment';
1572 $source = ts('Online Event Registration');
6a488035
TO
1573 }
1574
1575 if ($componentName == 'Membership') {
f2b2a3ff 1576 $idName = 'membership_id';
6a488035 1577 $componentTable = 'civicrm_membership';
f2b2a3ff
TO
1578 $paymentTable = 'civicrm_membership_payment';
1579 $source = ts('Online Contribution');
6a488035
TO
1580 }
1581
1582 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1583
1584 $query = "
1585 SELECT component.id as {$idName},
1586 componentPayment.contribution_id as contribution_id,
1587 contribution.source source,
1588 contribution.contribution_status_id as contribution_status_id,
1589 contribution.is_pay_later as is_pay_later
1590 FROM $componentTable component
1591LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1592LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1593 WHERE component.id = {$componentId}";
1594
1595 $dao = CRM_Core_DAO::executeQuery($query);
1596
1597 while ($dao->fetch()) {
1598 if ($dao->contribution_id &&
1599 $dao->is_pay_later &&
1600 $dao->contribution_status_id == $pendingStatusId &&
1601 strpos($dao->source, $source) !== FALSE
1602 ) {
1603 $contributionId = $dao->contribution_id;
1604 $dao->free();
1605 }
1606 }
1607
1608 return $contributionId;
1609 }
1610
1611 /**
16b10e64 1612 * Update contribution as well as related objects.
74ab7ba8 1613 *
f8c94f00 1614 * This function by-passes hooks - to address this - don't use this function.
1615 *
1f7c01e4 1616 * @deprecated
1617 *
1618 * Use api contribute.completetransaction
1619 * For failures use failPayment (preferably exposing by api in the process).
1620 *
74ab7ba8
EM
1621 * @param array $params
1622 * @param bool $processContributionObject
1623 *
1624 * @return array
1625 * @throws \Exception
6a488035 1626 */
00be9182 1627 public static function transitionComponents($params, $processContributionObject = FALSE) {
6a488035
TO
1628 // get minimum required values.
1629 $contactId = CRM_Utils_Array::value('contact_id', $params);
1630 $componentId = CRM_Utils_Array::value('component_id', $params);
1631 $componentName = CRM_Utils_Array::value('componentName', $params);
1632 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1633 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1634
1635 // if we already processed contribution object pass previous status id.
1636 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1637
1638 $updateResult = array();
1639
1640 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1641
1642 // we process only ( Completed, Cancelled, or Failed ) contributions.
1643 if (!$contributionId ||
f2b2a3ff
TO
1644 !in_array($contributionStatusId, array(
1645 array_search('Completed', $contributionStatuses),
1646 array_search('Cancelled', $contributionStatuses),
1647 array_search('Failed', $contributionStatuses),
1648 ))
6a488035
TO
1649 ) {
1650 return $updateResult;
1651 }
1652
1653 if (!$componentName || !$componentId) {
1654 // get the related component details.
1655 $componentDetails = self::getComponentDetails($contributionId);
1656 }
1657 else {
1658 $componentDetails['contact_id'] = $contactId;
1659 $componentDetails['component'] = $componentName;
1660
1661 if ($componentName == 'event') {
1662 $componentDetails['participant'] = $componentId;
1663 }
1664 else {
1665 $componentDetails['membership'] = $componentId;
1666 }
1667 }
1668
a7488080 1669 if (!empty($componentDetails['contact_id'])) {
6a488035
TO
1670 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1671 $contributionId,
1672 'contact_id'
1673 );
1674 }
1675
1676 // do check for required ids.
8cc574cf 1677 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
6a488035
TO
1678 return $updateResult;
1679 }
1680
1681 //now we are ready w/ required ids, start processing.
1682
1683 $baseIPN = new CRM_Core_Payment_BaseIPN();
1684
1685 $input = $ids = $objects = array();
1686
1687 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1688 $ids['contribution'] = $contributionId;
1689 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1690 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1691 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1692 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1693 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1694 $ids['contributionRecur'] = NULL;
1695 $ids['contributionPage'] = NULL;
1696
1697 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1698 CRM_Core_Error::fatal();
1699 }
1700
f2b2a3ff
TO
1701 $memberships = &$objects['membership'];
1702 $participant = &$objects['participant'];
6a488035 1703 $pledgePayment = &$objects['pledge_payment'];
f2b2a3ff 1704 $contribution = &$objects['contribution'];
6a488035
TO
1705
1706 if ($pledgePayment) {
1707 $pledgePaymentIDs = array();
1708 foreach ($pledgePayment as $key => $object) {
1709 $pledgePaymentIDs[] = $object->id;
1710 }
1711 $pledgeID = $pledgePayment[0]->pledge_id;
1712 }
1713
6a488035
TO
1714 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1715
1716 if ($participant) {
1717 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1718 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1719 $participant->id,
1720 'status_id'
1721 );
1722 }
1723 // we might want to process contribution object.
1724 $processContribution = FALSE;
1725 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1726 if (is_array($memberships)) {
1727 foreach ($memberships as $membership) {
1728 if ($membership) {
57e6913a
SD
1729 $newStatus = array_search('Cancelled', $membershipStatuses);
1730
1731 // Create activity
1732 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
1733 $activityParam = array(
1734 'subject' => "Status changed from {$allStatus[$membership->status_id]} to {$allStatus[$newStatus]}",
1735 'source_contact_id' => CRM_Core_Session::singleton()->get('userID'),
1736 'target_contact_id' => $membership->contact_id,
1737 'source_record_id' => $membership->id,
d0266acb 1738 'activity_type_id' => 'Change Membership Status',
006960ef
SD
1739 'status_id' => 'Completed',
1740 'priority_id' => 'Normal',
1741 'activity_date_time' => 'now',
57e6913a
SD
1742 );
1743
1744 $membership->status_id = $newStatus;
6a488035 1745 $membership->save();
57e6913a 1746 civicrm_api3('activity', 'create', $activityParam);
6a488035
TO
1747
1748 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1749 if ($processContributionObject) {
1750 $processContribution = TRUE;
1751 }
1752 }
1753 }
1754 }
1755
1756 if ($participant) {
1757 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1758 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1759
1760 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1761 if ($processContributionObject) {
1762 $processContribution = TRUE;
1763 }
1764 }
1765
1766 if ($pledgePayment) {
1767 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1768
1769 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1770 if ($processContributionObject) {
1771 $processContribution = TRUE;
1772 }
1773 }
1774 }
1775 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1776 if (is_array($memberships)) {
1777 foreach ($memberships as $membership) {
1778 if ($membership) {
1779 $membership->status_id = array_search('Expired', $membershipStatuses);
1780 $membership->save();
1781
1782 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1783 if ($processContributionObject) {
1784 $processContribution = TRUE;
1785 }
1786 }
1787 }
1788 }
1789 if ($participant) {
1790 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1791 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1792
1793 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1794 if ($processContributionObject) {
1795 $processContribution = TRUE;
1796 }
1797 }
1798
1799 if ($pledgePayment) {
1800 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1801
1802 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1803 if ($processContributionObject) {
1804 $processContribution = TRUE;
1805 }
1806 }
1807 }
1808 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1809
1810 // only pending contribution related object processed.
1811 if ($previousContriStatusId &&
1812 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1813 ) {
1814 // this is case when we already processed contribution object.
1815 return $updateResult;
1816 }
1817 elseif (!$previousContriStatusId &&
1818 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1819 ) {
1820 // this is case when we are going to process contribution object later.
1821 return $updateResult;
1822 }
1823
1824 if (is_array($memberships)) {
1825 foreach ($memberships as $membership) {
1826 if ($membership) {
1827 $format = '%Y%m%d';
1828
1829 //CRM-4523
1830 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1831 $membership->membership_type_id,
1832 $membership->is_test, $membership->id
1833 );
1834
1835 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1836 // this picks up membership type changes during renewals
1837 $sql = "
1838 SELECT membership_type_id
1839 FROM civicrm_membership_log
1840 WHERE membership_id=$membership->id
1841 ORDER BY id DESC
1842 LIMIT 1;";
a130e045 1843 $dao = new CRM_Core_DAO();
6a488035
TO
1844 $dao->query($sql);
1845 if ($dao->fetch()) {
1846 if (!empty($dao->membership_type_id)) {
1847 $membership->membership_type_id = $dao->membership_type_id;
1848 $membership->save();
1849 }
1850 }
1851 // else fall back to using current membership type
1852 $dao->free();
1853
9c09f5b7
AH
1854 // Figure out number of terms
1855 $numterms = 1;
77dbdcbc 1856 $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
9c09f5b7
AH
1857 foreach ($lineitems as $lineitem) {
1858 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1859 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
2d77a516 1860
9c09f5b7
AH
1861 // in case membership_num_terms comes through as null or zero
1862 $numterms = $numterms >= 1 ? $numterms : 1;
1863 break;
1864 }
1865 }
1866
e8c64fab 1867 // CRM-15735-to update the membership status as per the contribution receive date
35874a67 1868 $joinDate = NULL;
e8c64fab 1869 if (!empty($params['receive_date'])) {
35874a67 1870 $joinDate = $params['receive_date'];
e8c64fab 1871 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1872 $membership->end_date,
1873 $membership->join_date,
1874 $params['receive_date'],
1875 FALSE,
1876 $membership->membership_type_id,
1877 (array) $membership
1878 );
1879 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1880 $membership->save();
1881 }
1882
6a488035 1883 if ($currentMembership) {
9c09f5b7
AH
1884 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1885 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
6a488035
TO
1886 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1887 }
1888 else {
35874a67 1889 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
6a488035
TO
1890 }
1891
1892 //get the status for membership.
1893 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1894 $dates['end_date'],
1895 $dates['join_date'],
1896 'today',
5f11bbcc
EM
1897 TRUE,
1898 $membership->membership_type_id,
1899 (array) $membership
6a488035
TO
1900 );
1901
c2585c5b 1902 $formattedParams = array(
6a488035
TO
1903 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1904 array_search('Current', $membershipStatuses)
1905 ),
1906 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1907 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1908 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1909 );
1910
c2585c5b 1911 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
6a488035 1912
c2585c5b 1913 $membership->copyValues($formattedParams);
6a488035
TO
1914 $membership->save();
1915
1916 //updating the membership log
1917 $membershipLog = array();
c2585c5b 1918 $membershipLog = $formattedParams;
f2b2a3ff
TO
1919 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1920 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
6a488035
TO
1921
1922 $membershipLog['start_date'] = $logStartDate;
1923 $membershipLog['membership_id'] = $membership->id;
1924 $membershipLog['modified_id'] = $membership->contact_id;
1925 $membershipLog['modified_date'] = date('Ymd');
1926 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1927
1928 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1929
1930 //update related Memberships.
c2585c5b 1931 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
6a488035 1932
0f07bb06 1933 //CRM-19678: No Membership Renewal Activity is created when a Pay Later is set to Completed
1934 CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Renewal', $membership->contact_id);
1935
6a488035
TO
1936 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1937 '%B %E%f, %Y'
1938 );
1939 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1940 if ($processContributionObject) {
1941 $processContribution = TRUE;
1942 }
1943
1944 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1945 }
1946 }
1947 }
1948
1949 if ($participant) {
1950 $updatedStatusId = array_search('Registered', $participantStatuses);
1951 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1952
1953 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1954 if ($processContributionObject) {
1955 $processContribution = TRUE;
1956 }
1957 }
1958
1959 if ($pledgePayment) {
1960 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1961
1962 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1963 if ($processContributionObject) {
1964 $processContribution = TRUE;
1965 }
1966 }
1967 }
1968
1969 // process contribution object.
1970 if ($processContribution) {
1971 $contributionParams = array();
1972 $fields = array(
f2b2a3ff
TO
1973 'contact_id',
1974 'total_amount',
1975 'receive_date',
1976 'is_test',
1977 'campaign_id',
1978 'payment_instrument_id',
1979 'trxn_id',
1980 'invoice_id',
1981 'financial_type_id',
1982 'contribution_status_id',
1983 'non_deductible_amount',
1984 'receipt_date',
1985 'check_number',
6a488035
TO
1986 );
1987 foreach ($fields as $field) {
a7488080 1988 if (empty($params[$field])) {
6a488035
TO
1989 continue;
1990 }
1991 $contributionParams[$field] = $params[$field];
1992 }
1993
1994 $ids = array('contribution' => $contributionId);
1995 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1996 }
1997
1998 return $updateResult;
1999 }
2000
2001 /**
16b10e64 2002 * Returns all contribution related object ids.
7a9ab499
EM
2003 *
2004 * @param $contributionId
2005 *
2006 * @return array
6a488035 2007 */
291ca04f 2008 public static function getComponentDetails($contributionId) {
6a488035
TO
2009 $componentDetails = $pledgePayment = array();
2010 if (!$contributionId) {
2011 return $componentDetails;
2012 }
2013
2014 $query = "
2015 SELECT c.id as contribution_id,
2016 c.contact_id as contact_id,
d97c96dc 2017 c.contribution_recur_id,
6a488035
TO
2018 mp.membership_id as membership_id,
2019 m.membership_type_id as membership_type_id,
2020 pp.participant_id as participant_id,
2021 p.event_id as event_id,
2022 pgp.id as pledge_payment_id
2023 FROM civicrm_contribution c
2024 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2025 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2026 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2027 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2028 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2029 WHERE c.id = $contributionId";
2030
2031 $dao = CRM_Core_DAO::executeQuery($query);
2032 $componentDetails = array();
2033
2034 while ($dao->fetch()) {
2035 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
2036 $componentDetails['contact_id'] = $dao->contact_id;
2037 if ($dao->event_id) {
2038 $componentDetails['event'] = $dao->event_id;
2039 }
2040 if ($dao->participant_id) {
2041 $componentDetails['participant'] = $dao->participant_id;
2042 }
2043 if ($dao->membership_id) {
2044 if (!isset($componentDetails['membership'])) {
2045 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
2046 }
2047 $componentDetails['membership'][] = $dao->membership_id;
2048 $componentDetails['membership_type'][] = $dao->membership_type_id;
2049 }
2050 if ($dao->pledge_payment_id) {
2051 $pledgePayment[] = $dao->pledge_payment_id;
2052 }
d97c96dc
EM
2053 if ($dao->contribution_recur_id) {
2054 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
2055 }
6a488035
TO
2056 }
2057
2058 if ($pledgePayment) {
2059 $componentDetails['pledge_payment'] = $pledgePayment;
2060 }
2061
2062 return $componentDetails;
2063 }
2064
186c9c17 2065 /**
100fef9d 2066 * @param int $contactId
186c9c17
EM
2067 * @param bool $includeSoftCredit
2068 *
2069 * @return null|string
2070 */
00be9182 2071 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
6a488035
TO
2072 if (!$contactId) {
2073 return 0;
2074 }
d3426391 2075 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
7fb041e3 2076 $additionalWhere = " AND contribution.financial_type_id IN (0)";
9cec2e9f 2077 $liWhere = " AND i.financial_type_id IN (0)";
7fb041e3 2078 if (!empty($financialTypes)) {
40c655aa
E
2079 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2080 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
7fb041e3 2081 }
bbde790f
RN
2082 $contactContributionsSQL = "
2083 SELECT contribution.id AS id
2084 FROM civicrm_contribution contribution
ad37ac8e 2085 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2086 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2087 $additionalWhere
9cec2e9f 2088 AND i.id IS NULL";
bbde790f 2089
bbde790f
RN
2090 $contactSoftCreditContributionsSQL = "
2091 SELECT contribution.id
2092 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2093 ON ( contribution.id = softContribution.contribution_id )
2094 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2095 $query = "SELECT count( x.id ) count FROM ( ";
2096 $query .= $contactContributionsSQL;
2097
6a488035 2098 if ($includeSoftCredit) {
bbde790f
RN
2099 $query .= " UNION ";
2100 $query .= $contactSoftCreditContributionsSQL;
6a488035 2101 }
bbde790f 2102
bbde790f 2103 $query .= ") x";
6a488035
TO
2104
2105 return CRM_Core_DAO::singleValueQuery($query);
2106 }
2107
b3b7f4c5 2108 /**
2109 * Repeat a transaction as part of a recurring series.
2110 *
2111 * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function
2112 * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a
2113 * subsequent call to the contribution.completetransaction api.
2114 *
2115 * The completeTransaction functionality has historically been overloaded to both complete and repeat payments.
2116 *
2117 * @param CRM_Contribute_BAO_Contribution $contribution
2118 * @param array $input
2119 * @param array $contributionParams
43c8d1dd 2120 * @param int $paymentProcessorID
b3b7f4c5 2121 *
2122 * @return array
43c8d1dd 2123 * @throws CiviCRM_API3_Exception
b3b7f4c5 2124 */
43c8d1dd 2125 protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) {
b3b7f4c5 2126 if (!empty($contribution->id)) {
2127 return FALSE;
2128 }
2129 if (empty($contribution->id)) {
2130 // Unclear why this would only be set for repeats.
2131 if (!empty($input['amount'])) {
2132 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
2133 }
43c8d1dd 2134
c02c17df 2135 if (!empty($contributionParams['contribution_recur_id'])) {
2136 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array(
2137 'id' => $contributionParams['contribution_recur_id'],
2138 ));
2139 if (!empty($recurringContribution['campaign_id'])) {
2140 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2141 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2142 }
7f4ef731 2143 if (!empty($recurringContribution['financial_type_id'])) {
2144 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2145 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2146 }
c02c17df 2147 }
43c8d1dd 2148 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution(
2149 $contributionParams['contribution_recur_id'],
2150 array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE))
2151 );
2152 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2153
f8c94f00 2154 $contributionParams['status_id'] = 'Pending';
3c49d90c 2155 if (isset($contributionParams['financial_type_id'])) {
2156 // Give precedence to passed in type.
2157 $contribution->financial_type_id = $contributionParams['financial_type_id'];
2158 }
2159 else {
2160 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2161 }
b3b7f4c5 2162 $contributionParams['contact_id'] = $templateContribution['contact_id'];
f8c94f00 2163 $contributionParams['source'] = empty($templateContribution['source']) ? ts('Recurring contribution') : $templateContribution['source'];
43c8d1dd 2164
44fec73b
BS
2165 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2166 //do not create CC or BCC emails or profile notifications.
2167 //The if is just to be safe. Not sure if we can ever arrive with this unset
8536e5a0 2168 // but per CRM-19478 it seems it can be 'null'
2169 if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
4194dd55 2170 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id;
a4facb5c 2171 }
44fec73b 2172
b3b7f4c5 2173 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2174 $contribution->id = $createContribution['id'];
f8c94f00 2175 CRM_Contribute_BAO_ContributionRecur::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id);
b3b7f4c5 2176 return TRUE;
2177 }
2178 }
2179
6a488035 2180 /**
fe482240 2181 * Get individual id for onbehalf contribution.
6a488035 2182 *
014c4014
TO
2183 * @param int $contributionId
2184 * Contribution id.
2185 * @param int $contributorId
2186 * Contributor id.
6a488035 2187 *
a6c01b45
CW
2188 * @return array
2189 * containing organization id and individual id
6a488035 2190 */
00be9182 2191 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
6a488035
TO
2192
2193 $ids = array();
2194
2195 if (!$contributionId) {
2196 return $ids;
2197 }
2198
2199 // fetch contributor id if null
2200 if (!$contributorId) {
2201 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2202 $contributionId, 'contact_id'
2203 );
2204 }
2205
2206 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2207 $activityTypeId = array_search('Contribution', $activityTypeIds);
2208
2209 if ($activityTypeId && $contributorId) {
2210 $activityQuery = "
2d77a516
DL
2211SELECT civicrm_activity_contact.contact_id
2212 FROM civicrm_activity_contact
2213INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2214 WHERE civicrm_activity.activity_type_id = %1
2215 AND civicrm_activity.source_record_id = %2
2216 AND civicrm_activity_contact.record_type_id = %3
2217";
6a488035 2218
e7e657f0 2219 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2d77a516
DL
2220 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2221
2222 $params = array(
2223 1 => array($activityTypeId, 'Integer'),
6a488035 2224 2 => array($contributionId, 'Integer'),
2d77a516 2225 3 => array($sourceID, 'Integer'),
6a488035
TO
2226 );
2227
2228 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2229
2230 // for on behalf contribution source is individual and contributor is organization
2231 if ($sourceContactId && $sourceContactId != $contributorId) {
2232 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2233 // get rel type id for employee of relation
2234 foreach ($relationshipTypeIds as $id => $typeVals) {
2235 if ($typeVals['name_a_b'] == 'Employee of') {
2236 $relationshipTypeId = $id;
2237 break;
2238 }
2239 }
2240
2241 $rel = new CRM_Contact_DAO_Relationship();
2242 $rel->relationship_type_id = $relationshipTypeId;
2243 $rel->contact_id_a = $sourceContactId;
2244 $rel->contact_id_b = $contributorId;
2245 if ($rel->find(TRUE)) {
2246 $ids['individual_id'] = $rel->contact_id_a;
2247 $ids['organization_id'] = $rel->contact_id_b;
2248 }
2249 }
2250 }
2251
2252 return $ids;
2253 }
2254
2255 /**
2256 * @return array
6a488035 2257 */
00be9182 2258 public static function getContributionDates() {
f2b2a3ff 2259 $config = CRM_Core_Config::singleton();
6a488035 2260 $currentMonth = date('m');
f2b2a3ff 2261 $currentDay = date('d');
6a488035
TO
2262 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2263 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2264 (int ) $config->fiscalYearStart['d'] > $currentDay
2265 )
2266 ) {
2267 $year = date('Y') - 1;
2268 }
2269 else {
2270 $year = date('Y');
2271 }
f2b2a3ff 2272 $year = array('Y' => $year);
6a488035
TO
2273 $yearDate = $config->fiscalYearStart;
2274 $yearDate = array_merge($year, $yearDate);
2275 $yearDate = CRM_Utils_Date::format($yearDate);
2276
2277 $monthDate = date('Ym') . '01';
2278
2279 $now = date('Ymd');
2280
2281 return array(
2282 'now' => $now,
2283 'yearDate' => $yearDate,
2284 'monthDate' => $monthDate,
2285 );
2286 }
2287
16b10e64 2288 /**
fe482240 2289 * Load objects relations to contribution object.
6a488035
TO
2290 * Objects are stored in the $_relatedObjects property
2291 * In the first instance we are just moving functionality from BASEIpn -
16b10e64
CW
2292 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2293 *
2294 * Note that the unit test for the BaseIPN class tests this function
6a488035 2295 *
014c4014
TO
2296 * @param array $input
2297 * Input as delivered from Payment Processor.
2298 * @param array $ids
2299 * Ids as Loaded by Payment Processor.
014c4014
TO
2300 * @param bool $loadAll
2301 * Load all related objects - even where id not passed in? (allows API to call this).
186c9c17
EM
2302 *
2303 * @return bool
2304 * @throws Exception
2305 */
276e3ec6 2306 public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) {
f2b2a3ff
TO
2307 if ($loadAll) {
2308 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2309 if (empty($ids['contact']) && isset($this->contact_id)) {
6a488035
TO
2310 $ids['contact'] = $this->contact_id;
2311 }
2312 }
2313 if (empty($this->_component)) {
f2b2a3ff 2314 if (!empty($ids['event'])) {
6a488035
TO
2315 $this->_component = 'event';
2316 }
2317 else {
2318 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2319 }
2320 }
474ebab9 2321
2b57dd9f 2322 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2323 // refactoring than anything else, and has unit test coverage.
2324 if (empty($this->financial_type_id)) {
2325 $this->find(TRUE);
2326 }
2327
474ebab9 2328 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2329 'paymentProcessor',
2330 $ids
2331 ));
2332
18135422 2333 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id) {
474ebab9 2334 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2335 $this->contribution_page_id,
2336 'payment_processor'
2337 );
ef6ae9af 2338 if ($paymentProcessorID) {
2339 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2340 }
474ebab9 2341 }
2342
2b57dd9f 2343 $ids['contributionType'] = $this->financial_type_id;
2344 $ids['financialType'] = $this->financial_type_id;
55df1211
AS
2345 if ($this->contribution_page_id) {
2346 $ids['contributionPage'] = $this->contribution_page_id;
474ebab9 2347 }
2348
55df1211
AS
2349 $this->loadRelatedEntitiesByID($ids);
2350
2b57dd9f 2351 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2352 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
6a488035 2353 }
6a488035 2354
474ebab9 2355 if (!empty($ids['pledge_payment'])) {
2356 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2357 if (empty($paymentID)) {
2358 continue;
2359 }
2360 $payment = new CRM_Pledge_BAO_PledgePayment();
2361 $payment->id = $paymentID;
2362 if (!$payment->find(TRUE)) {
2363 throw new Exception("Could not find pledge payment record: " . $paymentID);
2364 }
2365 $this->_relatedObjects['pledge_payment'][] = $payment;
2366 }
2367 }
2368
4ae9c8ac 2369 $this->loadRelatedMembershipObjects($ids);
aadcdd50 2370
2371 if ($this->_component != 'contribute') {
6a488035
TO
2372 // we are in event mode
2373 // make sure event exists and is valid
2374 $event = new CRM_Event_BAO_Event();
2375 $event->id = $ids['event'];
2376 if ($ids['event'] &&
2377 !$event->find(TRUE)
2378 ) {
2379 throw new Exception("Could not find event: " . $ids['event']);
2380 }
2381
2382 $this->_relatedObjects['event'] = &$event;
2383
2384 $participant = new CRM_Event_BAO_Participant();
2385 $participant->id = $ids['participant'];
2386 if ($ids['participant'] &&
2387 !$participant->find(TRUE)
2388 ) {
2389 throw new Exception("Could not find participant: " . $ids['participant']);
2390 }
2391 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2392
2393 $this->_relatedObjects['participant'] = &$participant;
2394
474ebab9 2395 // get the payment processor id from event - this is inaccurate see CRM-16923
2396 // in future we should look at throwing an exception here rather than an dubious guess.
6a488035
TO
2397 if (!$paymentProcessorID) {
2398 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
ef6ae9af 2399 if ($paymentProcessorID) {
2400 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2401 }
6a488035
TO
2402 }
2403 }
2404
6a488035
TO
2405 if ($paymentProcessorID) {
2406 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2407 $this->is_test ? 'test' : 'live'
2408 );
2409 $ids['paymentProcessor'] = $paymentProcessorID;
d6944518 2410 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
6a488035 2411 }
5bfb071e 2412 return TRUE;
6a488035
TO
2413 }
2414
16b10e64 2415 /**
6a488035
TO
2416 * Create array of message information - ie. return html version, txt version, to field
2417 *
014c4014
TO
2418 * @param array $input
2419 * Incoming information.
16b10e64 2420 * - is_recur - should this be treated as recurring (not sure why you wouldn't
6a488035
TO
2421 * just check presence of recur object but maintaining legacy approach
2422 * to be careful)
014c4014
TO
2423 * @param array $ids
2424 * IDs of related objects.
2425 * @param array $values
2426 * Any values that may have already been compiled by calling process.
6a488035 2427 * This is augmented by values 'gathered' by gatherMessageValues
014c4014
TO
2428 * @param bool $returnMessageText
2429 * Distinguishes between whether to send message or return.
6a488035
TO
2430 * message text. We are working towards this function ALWAYS returning message text & calling
2431 * function doing emails / pdfs with it
16b10e64 2432 *
a6c01b45
CW
2433 * @return array
2434 * messages
186c9c17
EM
2435 * @throws Exception
2436 */
d891a273 2437 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
4ff927bc 2438 $this->loadRelatedObjects($input, $ids);
2439
6a488035
TO
2440 if (empty($this->_component)) {
2441 $this->_component = CRM_Utils_Array::value('component', $input);
2442 }
2443
2444 //not really sure what params might be passed in but lets merge em into values
2445 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
55df1211 2446 $values['is_email_receipt'] = $this->isEmailReceipt($input, $values);
d9924163
E
2447 if (!empty($input['receipt_date'])) {
2448 $values['receipt_date'] = $input['receipt_date'];
2449 }
2450
d891a273 2451 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
6a488035
TO
2452 //what does recur 'mean here - to do with payment processor return functionality but
2453 // what is the importance
d891a273 2454 if (!empty($this->contribution_recur_id) && !empty($this->_relatedObjects['paymentProcessor'])) {
35cd38f5 2455 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
6a488035
TO
2456
2457 $entityID = $entity = NULL;
2458 if (isset($ids['contribution'])) {
2459 $entity = 'contribution';
2460 $entityID = $ids['contribution'];
2461 }
dccb668e
EM
2462 if (!empty($ids['membership'])) {
2463 //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
2464 // 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
2465 // line having loaded an array
2466 $ids['membership'] = (array) $ids['membership'];
6a488035 2467 $entity = 'membership';
dccb668e 2468 $entityID = $ids['membership'][0];
6a488035
TO
2469 }
2470
3e473c0b 2471 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
66df7769 2472 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2473 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
6a488035
TO
2474
2475 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2476 //direct mode showing billing block, so use directIPN for temporary
2477 $template->assign('contributeMode', 'directIPN');
2478 }
2479 }
2480 // todo remove strtolower - check consistency
2481 if (strtolower($this->_component) == 'event') {
66df7769 2482 $eventParams = array('id' => $this->_relatedObjects['participant']->event_id);
2483 $values['event'] = array();
2484
2485 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2486
2487 //get location details
2488 $locationParams = array('entity_id' => $this->_relatedObjects['participant']->event_id, 'entity_table' => 'civicrm_event');
2489 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2490
2491 $ufJoinParams = array(
2492 'entity_table' => 'civicrm_event',
2493 'entity_id' => $ids['event'],
2494 'module' => 'CiviEvent',
2495 );
2496
2497 list($custom_pre_id,
2498 $custom_post_ids
2499 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2500
2501 $values['custom_pre_id'] = $custom_pre_id;
2502 $values['custom_post_id'] = $custom_post_ids;
ec5b3633 2503 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
66df7769 2504 //and cases involving status updation through ipn
2505 // whatever that means!
95e5776c 2506 // total_amount appears to be the preferred input param & it is unclear why we support amount here
2507 // perhaps we should throw an e-notice if amount is set & force total_amount?
2508 if (!empty($input['amount'])) {
2509 $values['totalAmount'] = $input['amount'];
2510 }
55df1211 2511 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
66df7769 2512 if ($values['event']['is_email_confirm']) {
2513 $values['is_email_receipt'] = 1;
2514 }
b7bef093 2515
2b65b515 2516 if (!empty($ids['contribution'])) {
2517 $values['contributionId'] = $ids['contribution'];
2518 }
b7bef093 2519
6a488035
TO
2520 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2521 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2522 );
2523 }
2524 else {
2525 $values['contribution_id'] = $this->id;
a7488080 2526 if (!empty($ids['related_contact'])) {
6a488035
TO
2527 $values['related_contact'] = $ids['related_contact'];
2528 if (isset($ids['onbehalf_dupe_alert'])) {
2529 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2530 }
2531 $entityBlock = array(
2532 'contact_id' => $ids['contact'],
2533 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2534 'Home', 'id', 'name'
2535 ),
2536 );
2537 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2538 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2539 }
2540 $isTest = FALSE;
2541 if ($this->is_test) {
2542 $isTest = TRUE;
2543 }
2544 if (!empty($this->_relatedObjects['membership'])) {
2545 foreach ($this->_relatedObjects['membership'] as $membership) {
2546 if ($membership->id) {
85dea18b 2547 $values['isMembership'] = TRUE;
858f7096 2548 $values['membership_assign'] = TRUE;
6a488035
TO
2549
2550 // need to set the membership values here
6a488035
TO
2551 $template->assign('membership_name',
2552 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2553 );
2554 $template->assign('mem_start_date', $membership->start_date);
2555 $template->assign('mem_join_date', $membership->join_date);
2556 $template->assign('mem_end_date', $membership->end_date);
2557 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2558 $template->assign('mem_status', $membership_status);
2559 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
c2358f41 2560 $values['is_pay_later'] = 1;
6a488035 2561 }
37c88e84
JP
2562 // Pass amount to floatval as string '0.00' is considered a
2563 // valid amount and includes Fee section in the mail.
2564 if (isset($values['amount'])) {
2565 $values['amount'] = floatval($values['amount']);
2566 }
6a488035 2567
d891a273 2568 if (!empty($this->contribution_recur_id) && $paymentObject) {
3e473c0b 2569 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel');
6a488035
TO
2570 $template->assign('cancelSubscriptionUrl', $url);
2571 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2572 $template->assign('updateSubscriptionBillingUrl', $url);
2573 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2574 $template->assign('updateSubscriptionUrl', $url);
2575 }
2576
2577 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2578
2579 return $result;
2580 // otherwise if its about sending emails, continue sending without return, as we
2581 // don't want to exit the loop.
2582 }
2583 }
2584 }
2585 else {
2586 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2587 }
2588 }
2589 }
2590
16b10e64 2591 /**
6a488035
TO
2592 * Gather values for contribution mail - this function has been created
2593 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2594 * Values related to the contribution in question are gathered
2595 *
014c4014
TO
2596 * @param array $input
2597 * Input into function (probably from payment processor).
16b10e64 2598 * @param array $values
014c4014 2599 * @param array $ids
16b10e64 2600 * The set of ids related to the input.
6a488035 2601 *
a6c01b45 2602 * @return array
186c9c17 2603 */
00be9182 2604 public function _gatherMessageValues($input, &$values, $ids = array()) {
6a488035
TO
2605 // set display address of contributor
2606 if ($this->address_id) {
f2b2a3ff
TO
2607 $addressParams = array('id' => $this->address_id);
2608 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2609 $addressDetails = array_values($addressDetails);
6a488035 2610 }
2b221bad
TM
2611 // Else we assign the billing address of the contribution contact.
2612 else {
2613 $addressParams = array('contact_id' => $this->contact_id, 'is_billing' => 1);
2a0df9d9 2614 $addressDetails = (array) CRM_Core_BAO_Address::getValues($addressParams);
2615 $addressDetails = array_values($addressDetails);
2b221bad 2616 }
2a0df9d9 2617
2618 if (!empty($addressDetails[0]['display'])) {
2619 $values['address'] = $addressDetails[0]['display'];
2620 }
2621
6a488035 2622 if ($this->_component == 'contribute') {
a49aa7dd
TM
2623 //get soft contributions
2624 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
2625 if (!empty($softContributions)) {
2626 $values['softContributions'] = $softContributions['soft_credit'];
2627 }
6a488035 2628 if (isset($this->contribution_page_id)) {
55df1211 2629 // This is a call we want to use less, in favour of loading related objects.
f99a6f98 2630 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
6a488035 2631 if ($this->contribution_page_id) {
55df1211
AS
2632 // This is precautionary as there are some legacy flows, but it should really be
2633 // loaded by now.
2634 if (!isset($this->_relatedObjects['contributionPage'])) {
2635 $this->loadRelatedEntitiesByID(array('contributionPage' => $this->contribution_page_id));
2636 }
6a488035
TO
2637 // CRM-8254 - override default currency if applicable
2638 $config = CRM_Core_Config::singleton();
2639 $config->defaultCurrency = CRM_Utils_Array::value(
2640 'currency',
2641 $values,
2642 $config->defaultCurrency
2643 );
2644 }
2645 }
2646 // no contribution page -probably back office
2647 else {
2648 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
6a488035
TO
2649 $values['title'] = 'Contribution';
2650 }
2651 // set lineItem for contribution
2652 if ($this->id) {
270ff672 2653 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id);
2654 if (!empty($lineItems)) {
2655 $firstLineItem = reset($lineItems);
2656 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id'));
2657 $values['priceSetID'] = $priceSet['id'];
2658 foreach ($lineItems as &$eachItem) {
7c063f32 2659 if (isset($this->_relatedObjects['membership'])
2660 && is_array($this->_relatedObjects['membership'])
2661 && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
6a488035
TO
2662 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2663 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2664 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2665 }
270ff672 2666 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
2667 // However, that does create upgrade pain so would be better to be phased in.
2668 $values['useForMember'] = !$priceSet['is_quick_config'];
6a488035 2669 }
270ff672 2670 $values['lineItem'][0] = $lineItems;
f2b2a3ff 2671 }
6a488035
TO
2672 }
2673
2674 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2675 $this->id,
2676 $this->contact_id
2677 );
2678 // if this is onbehalf of contribution then set related contact
a7488080 2679 if (!empty($relatedContact['individual_id'])) {
6a488035
TO
2680 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2681 }
2682 }
2683 else {
2684 // event
2685 $eventParams = array(
2686 'id' => $this->_relatedObjects['event']->id,
2687 );
2688 $values['event'] = array();
2689
2690 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
7089d2d8
TM
2691 // add custom fields for event
2692 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id);
2693
2694 $eventCustomGroup = array();
2695 foreach ($eventGroupTree as $key => $group) {
2696 if ($key === 'info') {
2697 continue;
2698 }
2699
2700 foreach ($group['fields'] as $k => $customField) {
2701 $groupLabel = $group['title'];
2702 if (!empty($customField['customValue'])) {
2703 foreach ($customField['customValue'] as $customFieldValues) {
2704 $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2705 }
2706 }
2707 }
2708 }
2709 $values['event']['customGroup'] = $eventCustomGroup;
2710
2711 //get participant details
2712 $participantParams = array(
2713 'id' => $this->_relatedObjects['participant']->id,
2714 );
2715
2716 $values['participant'] = array();
2717
2718 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
2719 // add custom fields for event
2720 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id);
2721 $participantCustomGroup = array();
2722 foreach ($participantGroupTree as $key => $group) {
2723 if ($key === 'info') {
2724 continue;
2725 }
2726
2727 foreach ($group['fields'] as $k => $customField) {
2728 $groupLabel = $group['title'];
2729 if (!empty($customField['customValue'])) {
2730 foreach ($customField['customValue'] as $customFieldValues) {
2731 $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2732 }
2733 }
2734 }
2735 }
2736 $values['participant']['customGroup'] = $participantCustomGroup;
6a488035
TO
2737
2738 //get location details
2739 $locationParams = array(
2740 'entity_id' => $this->_relatedObjects['event']->id,
2741 'entity_table' => 'civicrm_event',
2742 );
2743 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2744
2745 $ufJoinParams = array(
2746 'entity_table' => 'civicrm_event',
f2b2a3ff
TO
2747 'entity_id' => $ids['event'],
2748 'module' => 'CiviEvent',
6a488035
TO
2749 );
2750
2751 list($custom_pre_id,
f2b2a3ff
TO
2752 $custom_post_ids
2753 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
6a488035
TO
2754
2755 $values['custom_pre_id'] = $custom_pre_id;
2756 $values['custom_post_id'] = $custom_post_ids;
2757
2758 // set lineItem for event contribution
2759 if ($this->id) {
2760 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2761 if (!empty($participantIds)) {
2762 foreach ($participantIds as $pIDs) {
2763 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2764 if (!CRM_Utils_System::isNull($lineItem)) {
2765 $values['lineItem'][] = $lineItem;
2766 }
2767 }
2768 }
2769 }
2770 }
2771
7089d2d8
TM
2772 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id);
2773
2774 $customGroup = array();
2775 foreach ($groupTree as $key => $group) {
2776 if ($key === 'info') {
2777 continue;
2778 }
2779
2780 foreach ($group['fields'] as $k => $customField) {
2781 $groupLabel = $group['title'];
2782 if (!empty($customField['customValue'])) {
2783 foreach ($customField['customValue'] as $customFieldValues) {
2784 $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues);
2785 }
2786 }
2787 }
2788 }
2789 $values['customGroup'] = $customGroup;
2790
6a488035
TO
2791 return $values;
2792 }
2793
2794 /**
9daadfce 2795 * Assign message variables to template but try to break the habit.
2796 *
2797 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
2798 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
2799 * multiple recurring payments for processors like IATS that use tokens.
2800 *
6a488035
TO
2801 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2802 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
9daadfce 2803 * Note we send directly from this function in some cases because it is only partly refactored.
2804 *
2805 * Don't call this function directly as the signature will change.
02af3683
EM
2806 *
2807 * @param $values
2808 * @param $input
02af3683
EM
2809 * @param bool $returnMessageText
2810 *
2811 * @return mixed
6a488035 2812 */
d891a273 2813 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
2814 $template = CRM_Core_Smarty::singleton();
6a488035
TO
2815 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2816 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2817 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
367b5943 2818
2819 // For some unit tests contribution cannot contain paymentProcessor information
2820 $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode'];
2821 $template->assign('contributeMode', CRM_Utils_Array::value($billingMode, CRM_Core_SelectValues::contributeMode()));
2822
02af3683 2823 //assign honor information to receipt message
8af73472 2824 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
6a488035 2825
8af73472 2826 if (isset($softRecord['soft_credit'])) {
7305d3e6 2827 //if id of contribution page is present
2828 if (!empty($values['id'])) {
2829 $values['honor'] = array(
2830 'honor_profile_values' => array(),
2831 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2832 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2833 );
6a488035 2834
f2b2a3ff 2835 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
7305d3e6 2836 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2837 }
2838 else {
2839 //offline contribution
2840 $softCreditTypes = $softCredits = array();
2841 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2842 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2843 $softCredits[$key] = array(
2844 'Name' => $softCredit['contact_name'],
21dfd5f5 2845 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
7305d3e6 2846 );
2847 }
2848 $template->assign('softCreditTypes', $softCreditTypes);
2849 $template->assign('softCredits', $softCredits);
2850 }
6a488035
TO
2851 }
2852
2853 $dao = new CRM_Contribute_DAO_ContributionProduct();
2854 $dao->contribution_id = $this->id;
2855 if ($dao->find(TRUE)) {
2856 $premiumId = $dao->product_id;
2857 $template->assign('option', $dao->product_option);
2858
2859 $productDAO = new CRM_Contribute_DAO_Product();
2860 $productDAO->id = $premiumId;
2861 $productDAO->find(TRUE);
2862 $template->assign('selectPremium', TRUE);
2863 $template->assign('product_name', $productDAO->name);
2864 $template->assign('price', $productDAO->price);
2865 $template->assign('sku', $productDAO->sku);
2866 }
f2b2a3ff 2867 $template->assign('title', CRM_Utils_Array::value('title', $values));
858f7096 2868 $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2869 if (!$values['amount'] && isset($this->total_amount)) {
2870 $values['amount'] = $this->total_amount;
6a488035 2871 }
858f7096 2872
6a488035
TO
2873 // add the new contribution values
2874 if (strtolower($this->_component) == 'contribute') {
2875 //PCP Info
2876 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2877 $softDAO->contribution_id = $this->id;
2878 if ($softDAO->find(TRUE)) {
2879 $template->assign('pcpBlock', TRUE);
2880 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2881 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2882 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2883
2884 //assign the pcp page title for email subject
2885 $pcpDAO = new CRM_PCP_DAO_PCP();
2886 $pcpDAO->id = $softDAO->pcp_id;
2887 if ($pcpDAO->find(TRUE)) {
2888 $template->assign('title', $pcpDAO->title);
2889 }
2890 }
2891 }
2892
2893 if ($this->financial_type_id) {
2894 $values['financial_type_id'] = $this->financial_type_id;
2895 }
2896
6a488035
TO
2897 $template->assign('trxn_id', $this->trxn_id);
2898 $template->assign('receive_date',
5bab7daf 2899 CRM_Utils_Date::processDate($this->receive_date)
6a488035 2900 );
76e8d9c4 2901 $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date);
6a488035
TO
2902 $template->assign('action', $this->is_test ? 1024 : 1);
2903 $template->assign('receipt_text',
2904 CRM_Utils_Array::value('receipt_text',
2905 $values
2906 )
2907 );
2908 $template->assign('is_monetary', 1);
d891a273 2909 $template->assign('is_recur', !empty($this->contribution_recur_id));
6a488035
TO
2910 $template->assign('currency', $this->currency);
2911 $template->assign('address', CRM_Utils_Address::format($input));
7089d2d8
TM
2912 if (!empty($values['customGroup'])) {
2913 $template->assign('customGroup', $values['customGroup']);
2914 }
a49aa7dd
TM
2915 if (!empty($values['softContributions'])) {
2916 $template->assign('softContributions', $values['softContributions']);
2917 }
6a488035
TO
2918 if ($this->_component == 'event') {
2919 $template->assign('title', $values['event']['title']);
2920 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2921 $viewRoles = array();
2922 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2923 $viewRoles[] = $participantRoles[$v];
2924 }
2925 $values['event']['participant_role'] = implode(', ', $viewRoles);
2926 $template->assign('event', $values['event']);
7089d2d8 2927 $template->assign('participant', $values['participant']);
6a488035
TO
2928 $template->assign('location', $values['location']);
2929 $template->assign('customPre', $values['custom_pre_id']);
2930 $template->assign('customPost', $values['custom_post_id']);
2931
2932 $isTest = FALSE;
2933 if ($this->_relatedObjects['participant']->is_test) {
2934 $isTest = TRUE;
2935 }
2936
2937 $values['params'] = array();
2938 //to get email of primary participant.
2939 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
f2b2a3ff
TO
2940 $primaryAmount[] = array(
2941 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
21dfd5f5 2942 'amount' => $this->_relatedObjects['participant']->fee_amount,
f2b2a3ff 2943 );
6a488035
TO
2944 //build an array of cId/pId of participants
2945 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2946 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2947 //send receipt to additional participant if exists
2948 if (count($additionalIDs)) {
2949 $template->assign('isPrimary', 0);
2950 $template->assign('customProfile', NULL);
2951 //set additionalParticipant true
2952 $values['params']['additionalParticipant'] = TRUE;
2953 foreach ($additionalIDs as $pId => $cId) {
2954 $amount = array();
2955 //to change the status pending to completed
2956 $additional = new CRM_Event_DAO_Participant();
2957 $additional->id = $pId;
2958 $additional->contact_id = $cId;
2959 $additional->find(TRUE);
2960 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2961 $additional->status_id = 1;
2962 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2963 //if additional participant dont have email
2964 //use display name.
2965 if (!$additionalParticipantInfo) {
2966 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2967 }
2968 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
f2b2a3ff
TO
2969 $primaryAmount[] = array(
2970 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
21dfd5f5 2971 'amount' => $additional->fee_amount,
f2b2a3ff 2972 );
6a488035
TO
2973 $additional->save();
2974 $additional->free();
2975 $template->assign('amount', $amount);
2976 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2977 }
2978 }
2979
2980 //build an array of custom profile and assigning it to template
2981 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2982
2983 if (count($customProfile)) {
2984 $template->assign('customProfile', $customProfile);
2985 }
2986
2987 // for primary contact
2988 $values['params']['additionalParticipant'] = FALSE;
2989 $template->assign('isPrimary', 1);
2990 $template->assign('amount', $primaryAmount);
2991 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2992 if ($this->payment_instrument_id) {
2993 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2994 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2995 }
2996 // carry paylater, since we did not created billing,
2997 // so need to pull email from primary location, CRM-4395
2998 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2999 }
3000 return $template;
3001 }
3002
3003 /**
100fef9d 3004 * Check whether payment processor supports
6a488035
TO
3005 * cancellation of contribution subscription
3006 *
014c4014
TO
3007 * @param int $contributionId
3008 * Contribution id.
6a488035 3009 *
77b97be7
EM
3010 * @param bool $isNotCancelled
3011 *
a130e045 3012 * @return bool
6a488035 3013 */
00be9182 3014 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
6a488035
TO
3015 $cacheKeyString = "$contributionId";
3016 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
3017
3018 static $supportsCancel = array();
3019
3020 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3021 $supportsCancel[$cacheKeyString] = FALSE;
3022 $isCancelled = FALSE;
3023
3024 if ($isNotCancelled) {
3025 $isCancelled = self::isSubscriptionCancelled($contributionId);
3026 }
3027
3028 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
3029 if (!empty($paymentObject)) {
1524a007 3030 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
6a488035
TO
3031 }
3032 }
3033 return $supportsCancel[$cacheKeyString];
3034 }
3035
3036 /**
fe482240 3037 * Check whether subscription is already cancelled.
6a488035 3038 *
014c4014
TO
3039 * @param int $contributionId
3040 * Contribution id.
6a488035 3041 *
a6c01b45
CW
3042 * @return string
3043 * contribution status
6a488035 3044 */
00be9182 3045 public static function isSubscriptionCancelled($contributionId) {
6a488035
TO
3046 $sql = "
3047 SELECT cr.contribution_status_id
3048 FROM civicrm_contribution_recur cr
3049 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3050 WHERE con.id = %1 LIMIT 1";
f2b2a3ff 3051 $params = array(1 => array($contributionId, 'Integer'));
6a488035 3052 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
f2b2a3ff 3053 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
6a488035
TO
3054 if ($status == 'Cancelled') {
3055 return TRUE;
3056 }
3057 return FALSE;
3058 }
3059
3060 /**
fe482240 3061 * Create all financial accounts entry.
6a488035 3062 *
014c4014
TO
3063 * @param array $params
3064 * Contribution object, line item array and params for trxn.
6a488035 3065 *
6a488035 3066 *
02af3683 3067 * @param array $financialTrxnValues
77b97be7
EM
3068 *
3069 * @return null|object
6a488035 3070 */
00be9182 3071 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
cb579c66 3072 $skipRecords = $update = $return = $isRelatedId = FALSE;
02af3683 3073
d37ade2e 3074 $additionalParticipantId = array();
6a488035 3075 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
10fd773f 3076 $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']];
6a488035
TO
3077
3078 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
3079 $entityId = $params['participant_id'];
3080 $entityTable = 'civicrm_participant';
d37ade2e 3081 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
6a488035 3082 }
8aa7457a
EM
3083 elseif (!empty($params['membership_id'])) {
3084 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3085 // are created off one contribution should be handled elsewhere
3086 $entityId = $params['membership_id'];
3087 $entityTable = 'civicrm_membership';
3088 }
6a488035
TO
3089 else {
3090 $entityId = $params['contribution']->id;
3091 $entityTable = 'civicrm_contribution';
3092 }
4d34aefa 3093
cb579c66
PN
3094 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
3095 $isRelatedId = TRUE;
3096 }
85dea18b 3097
464bb009 3098 $entityID[] = $entityId;
d37ade2e 3099 if (!empty($additionalParticipantId)) {
3100 $entityID += $additionalParticipantId;
464bb009 3101 }
4d34aefa 3102 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
a7488080 3103 if (empty($params['prevContribution'])) {
6a488035
TO
3104 $entityID = NULL;
3105 }
e005ab6b
PN
3106 else {
3107 $update = TRUE;
3108 }
4d34aefa 3109
f8325309
PJ
3110 $statusId = $params['contribution']->contribution_status_id;
3111 // CRM-13964 partial payment
4e92d4f4 3112 if ($contributionStatus == 'Partially paid'
f2b2a3ff
TO
3113 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
3114 ) {
79148eaa
PN
3115 $partialAmtPay = CRM_Utils_Rule::cleanMoney($params['partial_amount_pay']);
3116 $partialAmtTotal = CRM_Utils_Rule::cleanMoney($params['partial_payment_total']);
ede1935f 3117
876b8ab0 3118 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], 'Accounts Receivable Account is');
f8325309 3119 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
ede1935f 3120 $params['total_amount'] = $partialAmtPay;
0f602e3f 3121
ede1935f 3122 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
0f602e3f 3123 if (empty($balanceTrxnInfo['trxn_id'])) {
ede1935f 3124 // create new balance transaction record
876b8ab0 3125 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], 'Accounts Receivable Account is');
ede1935f 3126
0f602e3f 3127 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
ede1935f
PJ
3128 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
3129 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
2d8ae159 3130 $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis');
ede1935f
PJ
3131 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3132 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
3133 $balanceTrxnParams['currency'] = $params['contribution']->currency;
3134 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
3135 $balanceTrxnParams['status_id'] = $statusId;
3136 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3137 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
a246714d
PN
3138 if (!empty($balanceTrxnParams['from_financial_account_id']) &&
3139 ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses))
3140 ) {
3141 $balanceTrxnParams['is_payment'] = 1;
3142 }
a7488080 3143 if (!empty($params['payment_processor'])) {
ede1935f
PJ
3144 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
3145 }
14b74ca6 3146 $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
ede1935f 3147 }
f8325309
PJ
3148 }
3149
6a488035 3150 // build line item array if its not set in $params
a7488080 3151 if (empty($params['line_item']) || $additionalParticipantId) {
cb579c66 3152 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
6a488035
TO
3153 }
3154
4e92d4f4 3155 if ($contributionStatus != 'Failed' &&
3156 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)
f2b2a3ff 3157 ) {
6a488035 3158 $skipRecords = TRUE;
f2b2a3ff 3159 $pendingStatus = array(
4e92d4f4 3160 'Pending',
3161 'In Progress',
f2b2a3ff 3162 );
4e92d4f4 3163 if (in_array($contributionStatus, $pendingStatus)) {
bf2cf926 3164 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3165 $params['financial_type_id'],
3166 'Accounts Receivable Account is'
3167 );
6a488035 3168 }
a7488080 3169 elseif (!empty($params['payment_processor'])) {
6a488035 3170 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
bf722049 3171 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array(
3172 'id' => $params['payment_processor'],
3173 'return' => 'payment_instrument_id',
3174 ));
6a488035 3175 }
a7488080 3176 elseif (!empty($params['payment_instrument_id'])) {
6a488035
TO
3177 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3178 }
3179 else {
ac7514c2
PN
3180 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3181 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3182 $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
3183 }
3184
3185 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
8cc574cf 3186 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
6a488035
TO
3187 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3188 }
3189 //build financial transaction params
3190 $trxnParams = array(
3191 'contribution_id' => $params['contribution']->id,
3192 'to_financial_account_id' => $params['to_financial_account_id'],
2d8ae159 3193 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
6a488035
TO
3194 'total_amount' => $totalAmount,
3195 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
60a2aeee 3196 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
6a488035
TO
3197 'currency' => $params['contribution']->currency,
3198 'trxn_id' => $params['contribution']->trxn_id,
f8325309 3199 'status_id' => $statusId,
bf722049 3200 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id),
6a488035
TO
3201 'check_number' => CRM_Utils_Array::value('check_number', $params),
3202 );
8a0c74ae 3203 if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') {
10fd773f 3204 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis');
797d4c52 3205 if (isset($params['refund_trxn_id'])) {
3206 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3207 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3208 }
10fd773f 3209 }
a246714d 3210 //CRM-16259, set is_payment flag for non pending status
0170d873 3211 if (!in_array($contributionStatus, $pendingStatus)) {
a246714d
PN
3212 $trxnParams['is_payment'] = 1;
3213 }
a7488080 3214 if (!empty($params['payment_processor'])) {
8ef12e64 3215 $trxnParams['payment_processor_id'] = $params['payment_processor'];
6a488035 3216 }
0f602e3f
PJ
3217
3218 if (isset($fromFinancialAccountId)) {
3219 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3220 }
3221
3222 // consider external values passed for recording transaction entry
02af3683
EM
3223 if (!empty($financialTrxnValues)) {
3224 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
0f602e3f
PJ
3225 }
3226
6a488035
TO
3227 $params['trxnParams'] = $trxnParams;
3228
a7488080 3229 if (!empty($params['prevContribution'])) {
99cdd94d 3230 $updated = FALSE;
404f77c9
PN
3231 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3232 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3233 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
797d4c52 3234 if (!isset($params['trxnParams']['trxn_id'])) {
3235 // Actually I have no idea why we are overwriting any values from the previous contribution.
3236 // (filling makes sense to me). However, only protecting this value as I really really know we
3237 // don't want this one overwritten.
3238 // CRM-17751.
3239 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3240 }
404f77c9 3241 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
48ea0708 3242
182228d5 3243 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
f2b2a3ff
TO
3244 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3245 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3246 ) {
182228d5
PN
3247 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3248 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3249 }
85dea18b 3250
404f77c9 3251 //if financial type is changed
a7488080 3252 if (!empty($params['financial_type_id']) &&
f2b2a3ff
TO
3253 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3254 ) {
8cf6bd83
PN
3255 $accountRelationship = 'Income Account is';
3256 if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) {
3257 $accountRelationship = 'Deferred Revenue Account is';
3258 }
876b8ab0
PN
3259 $oldFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['prevContribution']->financial_type_id, $accountRelationship);
3260 $newFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['financial_type_id'], $accountRelationship);
404f77c9
PN
3261 if ($oldFinancialAccount != $newFinancialAccount) {
3262 $params['total_amount'] = 0;
b81ee58c 3263 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
876b8ab0
PN
3264 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(
3265 $params['prevContribution']->financial_type_id, $accountRelationship);
404f77c9
PN
3266 }
3267 else {
3268 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
a7488080 3269 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
404f77c9
PN
3270 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3271 }
3272 }
3273 self::updateFinancialAccounts($params, 'changeFinancialType');
3274 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3275 $params['financial_account_id'] = $newFinancialAccount;
8cf6bd83 3276 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
404f77c9
PN
3277 self::updateFinancialAccounts($params);
3278 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
99cdd94d 3279 $updated = TRUE;
8cf6bd83 3280 $params['deferred_financial_account_id'] = $newFinancialAccount;
404f77c9 3281 }
6a488035 3282 }
48ea0708 3283
6a488035 3284 //Update contribution status
404f77c9 3285 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
797d4c52 3286 if (!isset($params['refund_trxn_id'])) {
3287 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3288 // gets preference over another so I am only 'protecting' a very specific tested flow
3289 // and letting natural justice take care of the rest.
3290 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3291 }
a7488080 3292 if (!empty($params['contribution_status_id']) &&
f2b2a3ff
TO
3293 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3294 ) {
6a488035
TO
3295 //Update Financial Records
3296 self::updateFinancialAccounts($params, 'changedStatus');
99cdd94d 3297 $updated = TRUE;
6a488035
TO
3298 }
3299
3300 // change Payment Instrument for a Completed contribution
3301 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3302 // instrument is null and now new payment instrument is added along with the payment
404f77c9
PN
3303 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3304 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
6a488035 3305 if (array_key_exists('payment_instrument_id', $params)) {
f2b2a3ff 3306 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
6a488035 3307 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
f2b2a3ff
TO
3308 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
3309 ) {
6a488035
TO
3310 //check if status is changed from Pending to Completed
3311 // do not update payment instrument changes for Pending to Completed
3312 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
f2b2a3ff
TO
3313 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
3314 ) {
6a488035
TO
3315 // for all other statuses create new financial records
3316 self::updateFinancialAccounts($params, 'changePaymentInstrument');
d9814f68
PN
3317 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3318 self::updateFinancialAccounts($params, 'changePaymentInstrument');
99cdd94d 3319 $updated = TRUE;
6a488035
TO
3320 }
3321 }
4c9b6178 3322 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
f2b2a3ff
TO
3323 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
3324 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
3325 ) {
6a488035
TO
3326 // for any other payment instrument changes create new financial records
3327 self::updateFinancialAccounts($params, 'changePaymentInstrument');
d9814f68
PN
3328 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3329 self::updateFinancialAccounts($params, 'changePaymentInstrument');
99cdd94d 3330 $updated = TRUE;
6a488035 3331 }
4c9b6178 3332 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
f2b2a3ff
TO
3333 $params['contribution']->check_number != $params['prevContribution']->check_number
3334 ) {
6a488035
TO
3335 // another special case when check number is changed, create new financial records
3336 // create financial trxn with negative amount
6a488035
TO
3337 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3338 self::updateFinancialAccounts($params, 'changePaymentInstrument');
3339 // create financial trxn with positive amount
3340 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
3341 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
3342 self::updateFinancialAccounts($params, 'changePaymentInstrument');
99cdd94d 3343 $updated = TRUE;
6a488035
TO
3344 }
3345 }
48ea0708 3346
404f77c9
PN
3347 //if Change contribution amount
3348 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
3349 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
d9814f68 3350 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
404f77c9
PN
3351 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3352 if (isset($totalAmount) &&
f2b2a3ff
TO
3353 $totalAmount != $params['prevContribution']->total_amount
3354 ) {
404f77c9
PN
3355 //Update Financial Records
3356 $params['trxnParams']['from_financial_account_id'] = NULL;
404f77c9 3357 self::updateFinancialAccounts($params, 'changedAmount');
99cdd94d 3358 $updated = TRUE;
3359 }
3360
3361 if (!$updated) {
3362 // Looks like we might have a data correction update.
3363 // This would be a case where a transaction id has been entered but it is incorrect &
3364 // the person goes back in & fixes it, as opposed to a new transaction.
3365 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3366 // the data fix scenario.
3367 // CRM-17751.
3368 if (isset($params['refund_trxn_id'])) {
3369 $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']);
48714ae7 3370 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
99cdd94d 3371 civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id']));
3372 }
3373 }
d72b084a 3374 $cardType = CRM_Utils_Array::value('card_type_id', $params);
2c4a6dc8
PN
3375 $panTruncation = CRM_Utils_Array::value('pan_truncation', $params);
3376 CRM_Core_BAO_FinancialTrxn::updateCreditCardDetails($params['contribution']->id, $panTruncation, $cardType);
6a488035 3377 }
6a488035
TO
3378 }
3379
3380 if (!$update) {
1c19e0a3
PJ
3381 // records finanical trxn and entity financial trxn
3382 // also make it available as return value
9c472292 3383 self::recordAlwaysAccountsReceivable($trxnParams, $params);
1c19e0a3 3384 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3d93e98e
PN
3385 $params['entity_id'] = $financialTxn->id;
3386 if (empty($params['partial_payment_total']) && empty($params['partial_amount_pay'])) {
3387 self::$_trxnIDs[] = $financialTxn->id;
3388 }
6a488035 3389 }
e005ab6b 3390 }
b44e3f84 3391 // record line items and financial items
a7488080 3392 if (empty($params['skipLineItem'])) {
e005ab6b 3393 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
6a488035
TO
3394 }
3395
14b74ca6 3396 // create batch entry if batch_id is passed and
3397 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3398 if (!empty($params['batch_id']) && !empty($financialTxn)) {
6a488035
TO
3399 $entityParams = array(
3400 'batch_id' => $params['batch_id'],
3401 'entity_table' => 'civicrm_financial_trxn',
3402 'entity_id' => $financialTxn->id,
e005ab6b 3403 );
6a488035
TO
3404 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
3405 }
3406
3407 // when a fee is charged
8cc574cf 3408 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
6a488035
TO
3409 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3410 }
3411
a7488080 3412 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
f2b2a3ff
TO
3413 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3414 ) {
6a488035
TO
3415 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3416 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3417 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3418 }
3419 unset($params['line_item']);
7b361924 3420 self::$_trxnIDs = NULL;
1c19e0a3 3421 return $return;
6a488035
TO
3422 }
3423
3424 /**
fe482240 3425 * Update all financial accounts entry.
6a488035 3426 *
014c4014
TO
3427 * @param array $params
3428 * Contribution object, line item array and params for trxn.
6a488035 3429 *
014c4014
TO
3430 * @param string $context
3431 * Update scenarios.
6a488035 3432 *
77b97be7
EM
3433 * @param null $skipTrxn
3434 *
6a488035 3435 */
00be9182 3436 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
6a488035
TO
3437 $itemAmount = $trxnID = NULL;
3438 //get all the statuses
3439 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
67d61c72 3440 $previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name');
3441 if (($previousContributionStatus == 'Pending'
3442 || $previousContributionStatus == 'In Progress')
b81ee58c 3443 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
f2b2a3ff
TO
3444 && $context == 'changePaymentInstrument'
3445 ) {
6a488035
TO
3446 return;
3447 }
8084abdd
PN
3448 if ((($previousContributionStatus == 'Partially paid'
3449 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
19f6eba2 3450 || ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE
8084abdd 3451 && $params['contribution']->contribution_status_id == array_search('Partially paid', $contributionStatus)))
827e15a4
E
3452 && $context == 'changedStatus'
3453 ) {
3454 return;
3455 }
6a488035 3456 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
16c30586 3457 $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
6a488035
TO
3458 }
3459 if ($context == 'changedStatus') {
3460 //get all the statuses
3461 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
a7f2802f 3462 $cancelledTaxAmount = 0;
67d61c72 3463 if ($previousContributionStatus == 'Completed'
52da5b1e 3464 && (self::isContributionStatusNegative($params['contribution']->contribution_status_id))
f2b2a3ff
TO
3465 ) {
3466 $params['trxnParams']['total_amount'] = -$params['total_amount'];
a7f2802f 3467 $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $params, '0.00');
8d20d89c 3468 if (empty($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") {
4add5adb
GC
3469 $creditNoteId = self::createCreditNoteId();
3470 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
8762d39a 3471 }
6a488035 3472 }
67d61c72 3473 elseif (($previousContributionStatus == 'Pending'
3474 && $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress'
f2b2a3ff 3475 ) {
6a488035 3476 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
876b8ab0 3477 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
ec04cb12 3478
6a488035 3479 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
ec04cb12 3480 $params['trxnParams']['to_financial_account_id'] = $arAccountId;
f2b2a3ff 3481 $params['trxnParams']['total_amount'] = -$params['total_amount'];
8762d39a 3482 if (is_null($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") {
4add5adb
GC
3483 $creditNoteId = self::createCreditNoteId();
3484 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId);
8762d39a 3485 }
6a488035 3486 }
ec04cb12
GC
3487 else {
3488 $params['trxnParams']['from_financial_account_id'] = $arAccountId;
3489 }
6a488035 3490 }
a7f2802f 3491 $itemAmount = $params['trxnParams']['total_amount'] + $cancelledTaxAmount;
6a488035
TO
3492 }
3493 elseif ($context == 'changePaymentInstrument') {
b001aaef 3494 $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount'];
bf4385cb
SL
3495 $deferredFinancialAccount = CRM_Utils_Array::value('deferred_financial_account_id', $params);
3496 if (empty($deferredFinancialAccount)) {
876b8ab0 3497 $deferredFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['prevContribution']->financial_type_id, 'Deferred Revenue Account is');
bf4385cb
SL
3498 }
3499 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC', FALSE, NULL, $deferredFinancialAccount);
230be83b
SL
3500 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3501 if ($params['total_amount'] != $params['trxnParams']['total_amount']) {
bf4385cb 3502 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
230be83b 3503 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
122250ec
SL
3504 }
3505 else {
bf4385cb 3506 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
122250ec
SL
3507 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3508 }
6a488035
TO
3509 }
3510 }
6a488035
TO
3511
3512 if ($context == 'changedStatus') {
67d61c72 3513 if (($previousContributionStatus == 'Pending'
3514 || $previousContributionStatus == 'In Progress')
f2b2a3ff
TO
3515 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
3516 ) {
3b624e58
EM
3517 if (empty($params['line_item'])) {
3518 //CRM-15296
3519 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3520 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3521 // & this can be removed
3522 return;
3523 }
9c472292 3524 self::recordAlwaysAccountsReceivable($params['trxnParams'], $params);
b34861f3 3525 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
9c472292 3526 $params['entity_id'] = self::$_trxnIDs[] = $trxn->id;
b34861f3 3527 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3528 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3529
3530 $entityParams = array(
3531 'entity_table' => 'civicrm_financial_item',
b34861f3 3532 );
6a488035
TO
3533 foreach ($params['line_item'] as $fieldId => $fields) {
3534 foreach ($fields as $fieldValueId => $fieldValues) {
3535 $fparams = array(
3536 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3537 2 => array($fieldValues['id'], 'Integer'),
3538 );
6a488035 3539 CRM_Core_DAO::executeQuery($query, $fparams);
464bb009
PN
3540 $fparams = array(
3541 1 => array($fieldValues['id'], 'Integer'),
3542 );
3543 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3544 while ($financialItem->fetch()) {
3545 $entityParams['entity_id'] = $financialItem->id;
3546 $entityParams['amount'] = $financialItem->amount;
9c472292
PN
3547 foreach (self::$_trxnIDs as $tID) {
3548 $entityParams['financial_trxn_id'] = $tID;
3549 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3550 }
464bb009 3551 }
6a488035
TO
3552 }
3553 }
3554 return;
3555 }
3556 }
b34861f3 3557 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3558 $params['entity_id'] = $trxn->id;
6a488035
TO
3559 if ($context != 'changePaymentInstrument') {
3560 $itemParams['entity_table'] = 'civicrm_line_item';
3561 $trxnIds['id'] = $params['entity_id'];
3562 foreach ($params['line_item'] as $fieldId => $fields) {
3563 foreach ($fields as $fieldValueId => $fieldValues) {
8cf6bd83 3564 $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($fieldValues['id']);
6a488035
TO
3565 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3566 if ($params['contribution']->receive_date) {
3567 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3568 }
3569
bf2cf926 3570 $financialAccount = self::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem);
6a488035
TO
3571
3572 $currency = $params['prevContribution']->currency;
3573 if ($params['contribution']->currency) {
3574 $currency = $params['contribution']->currency;
3575 }
05e92f54 3576 $diff = 1;
52da5b1e 3577 if ($context == 'changeFinancialType' || self::isContributionStatusNegative($params['contribution']->contribution_status_id)) {
a7f2802f
PN
3578 $diff = -1;
3579 }
a7488080 3580 if (!empty($params['is_quick_config'])) {
6a488035
TO
3581 $amount = $itemAmount;
3582 if (!$amount) {
3583 $amount = $params['total_amount'];
3584 }
3585 }
3586 else {
6a488035
TO
3587 $amount = $diff * $fieldValues['line_total'];
3588 }
3589
3590 $itemParams = array(
3591 'transaction_date' => $receiveDate,
3592 'contact_id' => $params['prevContribution']->contact_id,
3593 'currency' => $currency,
3594 'amount' => $amount,
bf2cf926 3595 'description' => $prevFinancialItem->description,
3596 'status_id' => $prevFinancialItem->status_id,
6a488035
TO
3597 'financial_account_id' => $financialAccount,
3598 'entity_table' => 'civicrm_line_item',
21dfd5f5 3599 'entity_id' => $fieldValues['id'],
6a488035 3600 );
8cf6bd83
PN
3601 $financialItem = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3602 $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount;
3603 $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id;
c40e1ff4 3604
3605 if ($fieldValues['tax_amount']) {
aaffa79f 3606 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
5a18a545 3607 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
c40e1ff4 3608 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
5a18a545 3609 $itemParams['description'] = $taxTerm;
c40e1ff4 3610 if ($fieldValues['financial_type_id']) {
5a18a545 3611 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
c40e1ff4 3612 }
3613 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3614 }
6a488035
TO
3615 }
3616 }
3617 }
423ae5b1 3618 if ($context == 'changeFinancialType') {
6535ff79 3619 $params['skipLineItem'] = FALSE;
423ae5b1
PN
3620 foreach ($params['line_item'] as &$lineItems) {
3621 foreach ($lineItems as &$line) {
3622 $line['financial_type_id'] = $params['financial_type_id'];
3623 }
3624 }
3625 }
bf4385cb 3626 if ($context == 'changePaymentInstrument') {
8e10ee7c
PN
3627 // store financial item Proportionaly.
3628 $trxnParams = array(
3629 'total_amount' => $trxn->total_amount,
3630 'contribution_id' => $params['contribution']->id,
3631 );
97df5796 3632 self::assignProportionalLineItems($trxnParams, $trxn->id, $params['prevContribution']->total_amount);
bf4385cb 3633 }
8cf6bd83 3634 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, $context);
6a488035
TO
3635 }
3636
52da5b1e 3637 /**
3638 * Is this contribution status a reversal.
3639 *
3640 * If so we would expect to record a negative value in the financial_trxn table.
3641 *
3642 * @param int $status_id
3643 *
3644 * @return bool
3645 */
3646 public static function isContributionStatusNegative($status_id) {
3647 $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded');
3648 return in_array(CRM_Contribute_PseudoConstant::contributionStatus($status_id, 'name'), $reversalStatuses);
3649 }
3650
6a488035 3651 /**
fe482240 3652 * Check status validation on update of a contribution.
6a488035 3653 *
014c4014
TO
3654 * @param array $values
3655 * Previous form values before submit.
6a488035 3656 *
014c4014
TO
3657 * @param array $fields
3658 * The input form values.
6a488035 3659 *
014c4014
TO
3660 * @param array $errors
3661 * List of errors.
6a488035 3662 *
77b97be7 3663 * @return bool
6a488035 3664 */
00be9182 3665 public static function checkStatusValidation($values, &$fields, &$errors) {
8cc574cf 3666 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
c71ae314
PN
3667 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3668 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3669 return FALSE;
3670 }
3671 }
6a488035
TO
3672 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3673 $checkStatus = array(
3674 'Cancelled' => array('Completed', 'Refunded'),
52da5b1e 3675 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'),
8084abdd 3676 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'),
f73acc78 3677 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
21dfd5f5 3678 'Refunded' => array('Cancelled', 'Completed'),
827e15a4 3679 'Partially paid' => array('Completed'),
6a488035
TO
3680 );
3681
da017017
PN
3682 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3683 CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array()))
3684 ) {
f2b2a3ff 3685 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
353ffa53
TO
3686 1 => $contributionStatuses[$values['contribution_status_id']],
3687 2 => $contributionStatuses[$fields['contribution_status_id']],
3688 ));
6a488035
TO
3689 }
3690 }
c3d24ba7
PN
3691
3692 /**
fe482240 3693 * Delete contribution of contact.
c3d24ba7
PN
3694 *
3695 * CRM-12155
3696 *
014c4014
TO
3697 * @param int $contactId
3698 * Contact id.
c3d24ba7 3699 *
c3d24ba7 3700 */
00be9182 3701 public static function deleteContactContribution($contactId) {
c3d24ba7
PN
3702 $contribution = new CRM_Contribute_DAO_Contribution();
3703 $contribution->contact_id = $contactId;
3704 $contribution->find();
3705 while ($contribution->fetch()) {
3706 self::deleteContribution($contribution->id);
3707 }
3708 }
16c0ec8d
CW
3709
3710 /**
3711 * Get options for a given contribution field.
3712 * @see CRM_Core_DAO::buildOptions
3713 *
014c4014 3714 * @param string $fieldName
bed98343 3715 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3716 * @param array $props whatever is known about this dao object.
77b97be7 3717 *
a130e045 3718 * @return array|bool
16c0ec8d
CW
3719 */
3720 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3721 $className = __CLASS__;
3722 $params = array();
9d5c7f14 3723 if (isset($props['orderColumn'])) {
3724 $params['orderColumn'] = $props['orderColumn'];
3725 }
16c0ec8d
CW
3726 switch ($fieldName) {
3727 // This field is not part of this object but the api supports it
3728 case 'payment_processor':
3729 $className = 'CRM_Contribute_BAO_ContributionPage';
3730 // Filter results by contribution page
3731 if (!empty($props['contribution_page_id'])) {
03a8c3dc 3732 $page = civicrm_api('contribution_page', 'getsingle', array(
3733 'version' => 3,
21dfd5f5 3734 'id' => ($props['contribution_page_id']),
03a8c3dc 3735 ));
16c0ec8d
CW
3736 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3737 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3738 }
33a429d4 3739 break;
ea100cb5 3740
33a429d4
CW
3741 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3742 case 'honor_type_id':
3743 $className = 'CRM_Contribute_BAO_ContributionSoft';
3744 $fieldName = 'soft_credit_type_id';
3745 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3746 break;
16c0ec8d
CW
3747 }
3748 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3749 }
03a8c3dc 3750
3b67ab13 3751 /**
fe482240 3752 * Validate financial type.
3b67ab13
PN
3753 *
3754 * CRM-13231
3755 *
014c4014
TO
3756 * @param int $financialTypeId
3757 * Financial Type id.
3b67ab13 3758 *
77b97be7
EM
3759 * @param string $relationName
3760 *
3761 * @return array|bool
3b67ab13 3762 */
00be9182 3763 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
876b8ab0 3764 $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, $relationName);
3b67ab13
PN
3765
3766 if (!$financialAccount) {
3767 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3768 }
3769 return FALSE;
3770 }
16c0ec8d 3771
3d7de127 3772
d424ffde 3773 /**
fe482240 3774 * Function to record additional payment for partial and refund contributions.
3d7de127 3775 *
014c4014 3776 * @param int $contributionId
16b10e64 3777 * is the invoice contribution id (got created after processing participant payment).
d424ffde 3778 * @param array $trxnsData
16b10e64 3779 * to take user provided input of transaction details.
014c4014
TO
3780 * @param string $paymentType
3781 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
100fef9d 3782 * @param int $participantId
bc854509 3783 * @param bool $updateStatus
186c9c17
EM
3784 *
3785 * @return null|object
3786 */
ebfaa544 3787 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) {
0f602e3f 3788 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
e8cf3013
PJ
3789 $getInfoOf['id'] = $contributionId;
3790 $defaults = array();
3791 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
af0fda98 3792 if (!$participantId) {
545ca071 3793 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
af0fda98 3794 }
e8cf3013 3795
dc3011e3
PN
3796 // build params for recording financial trxn entry
3797 $params['contribution'] = $contributionDAO;
3798 $params = array_merge($defaults, $params);
3799 $params['skipLineItem'] = TRUE;
3800 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
876b8ab0 3801 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
e8cf3013 3802 if ($paymentType == 'owed') {
e8cf3013
PJ
3803 $params['partial_payment_total'] = $contributionDAO->total_amount;
3804 $params['partial_amount_pay'] = $trxnsData['total_amount'];
60a2aeee 3805 $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
e8cf3013
PJ
3806
3807 // record the entry
3808 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
dc3011e3 3809 $toFinancialAccount = $arAccountId;
e8cf3013 3810 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
921bca19
DG
3811 if (!empty($trxnId)) {
3812 $trxnId = $trxnId['trxn_id'];
3813 }
3814 elseif (!empty($contributionDAO->payment_instrument_id)) {
3815 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3816 }
3817 else {
3818 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3819 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3820 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3821 }
0f602e3f 3822
e8cf3013
PJ
3823 // update statuses
3824 // criteria for updates contribution total_amount == financial_trxns of partial_payments
b8adb851 3825 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
0f602e3f 3826FROM civicrm_financial_trxn ft
a695703f
PJ
3827LEFT JOIN civicrm_entity_financial_trxn eft
3828 ON (ft.id = eft.financial_trxn_id)
3829WHERE eft.entity_table = 'civicrm_contribution'
3830 AND eft.entity_id = {$contributionId}
3831 AND ft.to_financial_account_id != {$toFinancialAccount}
3832 AND ft.status_id = {$statusId}
0f602e3f 3833";
b8adb851 3834 $query = CRM_Core_DAO::executeQuery($sql);
3835 $query->fetch();
3836 $sumOfPayments = $query->sum_of_payments;
e8cf3013
PJ
3837
3838 // update statuses
3839 if ($contributionDAO->total_amount == $sumOfPayments) {
921bca19
DG
3840 // update contribution status and
3841 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3842 $contributionDAO->contribution_status_id = $statusId;
3843 $contributionDAO->cancel_date = 'null';
3844 $contributionDAO->cancel_reason = NULL;
b8adb851 3845 $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount'];
3846 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
3847 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
921bca19
DG
3848 $contributionDAO->save();
3849
3850 //Change status of financial record too
3851 $financialTrxn->status_id = $statusId;
3852 $financialTrxn->save();
3853
e8cf3013
PJ
3854 // note : not using the self::add method,
3855 // the reason because it performs 'status change' related code execution for financial records
3856 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3857 // are coded below i.e. just updating financial_item status to 'Paid'
e8cf3013
PJ
3858
3859 if ($participantId) {
3860 // update participant status
e8cf3013 3861 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
28e4e707
PJ
3862 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3863 foreach ($ids as $val) {
3864 $participantUpdate['id'] = $val;
3865 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3866 CRM_Event_BAO_Participant::add($participantUpdate);
3867 }
e8cf3013
PJ
3868 }
3869
3870 // update financial item statuses
3871 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3872 $paidStatus = array_search('Paid', $financialItemStatus);
3873
5684b818 3874 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
e8cf3013
PJ
3875 $sqlFinancialItemUpdate = "
3876UPDATE civicrm_financial_item fi
3877 LEFT JOIN civicrm_entity_financial_trxn eft
3878 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3879SET status_id = {$paidStatus}
5684b818 3880WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
e8cf3013
PJ
3881";
3882 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3883 }
3884 }
3885 elseif ($paymentType == 'refund') {
f2b2a3ff 3886 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
dc3011e3 3887 $trxnsData['from_financial_account_id'] = $arAccountId;
e8cf3013
PJ
3888 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3889 // record the entry
3890 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3891
aac57c29
PJ
3892 // note : not using the self::add method,
3893 // the reason because it performs 'status change' related code execution for financial records
e8cf3013 3894 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
aac57c29 3895 // are coded below i.e. just updating financial_item status to 'Paid'
ebfaa544
PN
3896 if ($updateStatus) {
3897 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3898 }
e8cf3013
PJ
3899 // add financial item entry
3900 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
4ab71644
E
3901 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionDAO->id);
3902 if (!empty($lineItems)) {
3903 foreach ($lineItems as $lineItemId => $lineItemValue) {
3904 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount / $contributionDAO->total_amount);
3905 $addFinancialEntry = array(
3906 'transaction_date' => $financialTrxn->trxn_date,
3907 'contact_id' => $contributionDAO->contact_id,
3908 'amount' => round($paid, 2),
3909 'status_id' => array_search('Paid', $financialItemStatus),
3910 'entity_id' => $lineItemId,
3911 'entity_table' => 'civicrm_line_item',
3912 );
3913 $trxnIds['id'] = $financialTrxn->id;
3914 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3915 }
615a1e0f 3916 }
0f602e3f
PJ
3917 if ($participantId) {
3918 // update participant status
0f602e3f 3919 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
28e4e707
PJ
3920 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3921 foreach ($ids as $val) {
3922 $participantUpdate['id'] = $val;
3923 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3924 CRM_Event_BAO_Participant::add($participantUpdate);
3925 }
0f602e3f 3926 }
0f602e3f 3927 }
bd99f5fe 3928
e8cf3013 3929 // activity creation
bd99f5fe
PJ
3930 if (!empty($financialTrxn)) {
3931 if ($participantId) {
3932 $inputParams['id'] = $participantId;
3933 $values = array();
3934 $ids = array();
3935 $component = 'event';
3936 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3937 $entityObj = $entityObj[$participantId];
3938 }
685dc433
PN
3939 else {
3940 $entityObj = $contributionDAO;
3941 $component = 'contribution';
3942 }
bd99f5fe
PJ
3943 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3944
66526669 3945 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
bd99f5fe
PJ
3946 }
3947 return $financialTrxn;
3948 }
3949
186c9c17
EM
3950 /**
3951 * @param $entityObj
3952 * @param $trxnObj
3953 * @param $activityType
3954 * @param $component
100fef9d 3955 * @param int $contributionId
186c9c17
EM
3956 *
3957 * @throws CRM_Core_Exception
3958 */
00be9182 3959 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
bd99f5fe 3960 if ($component == 'event') {
685dc433 3961 $title = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
bd99f5fe 3962 }
685dc433
PN
3963 else {
3964 $title = ts('Contribution');
3965 }
3966 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3967 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
3968 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3969 $targetCid = $entityObj->contact_id;
3970 // source record id would be the contribution id
3971 $srcRecId = $contributionId;
bd99f5fe
PJ
3972
3973 // activity params
3974 $activityParams = array(
3975 'source_contact_id' => $targetCid,
3976 'source_record_id' => $srcRecId,
3977 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3978 $activityType,
3979 'name'
3980 ),
3981 'subject' => $subject,
3982 'activity_date_time' => $date,
3983 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3984 'Completed',
3985 'name'
3986 ),
3987 'skipRecentView' => TRUE,
3988 );
3989
3990 // create activity with target contacts
3991 $session = CRM_Core_Session::singleton();
3992 $id = $session->get('userID');
3993 if ($id) {
3994 $activityParams['source_contact_id'] = $id;
3995 $activityParams['target_contact_id'][] = $targetCid;
3996 }
3997 CRM_Activity_BAO_Activity::create($activityParams);
0f602e3f 3998 }
16c0ec8d 3999
186c9c17 4000 /**
fe482240 4001 * Get list of payments displayed by Contribute_Page_PaymentInfo.
8cf01b22 4002 *
100fef9d 4003 * @param int $id
186c9c17
EM
4004 * @param $component
4005 * @param bool $getTrxnInfo
4006 * @param bool $usingLineTotal
4007 *
4008 * @return mixed
4009 */
00be9182 4010 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
29c61b58
PJ
4011 if ($component == 'event') {
4012 $entity = 'participant';
e8cf3013 4013 $entityTable = 'civicrm_participant';
29c61b58 4014 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
ae53df5f
PJ
4015
4016 if (!$contributionId) {
4017 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4018 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4019 $id = $primaryParticipantId;
4020 }
22825dfc 4021 if (!$contributionId) {
4022 return;
ae53df5f
PJ
4023 }
4024 }
29c61b58 4025 }
d4c0653f 4026 else {
4027 $contributionId = $id;
4028 $entity = 'contribution';
4029 $entityTable = 'civicrm_contribution';
4030 }
4031
29c61b58 4032 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
1010c4e1 4033 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
4d193d61 4034 if (!$baseTrxnId) {
5684b818
PJ
4035 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
4036 $baseTrxnId = $baseTrxnId['financialTrxnId'];
5684b818 4037 }
18fdfcc3 4038 if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) {
685dc433 4039 $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
bc2eeabb
PJ
4040 }
4041 else {
4042 $baseTrxnId = $total['trxn_id'];
4043 $total = $total['total_amount'];
4044 }
1010c4e1 4045
bc2eeabb 4046 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
356579e9 4047 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
8cf01b22 4048
8cf01b22 4049 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
876b8ab0 4050 $feeFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, 'Expense Account is');
8cf01b22 4051
356579e9
PJ
4052 if ($paymentBalance == 0 && $contributionIsPayLater) {
4053 $paymentBalance = $total;
4054 }
4055
29c61b58
PJ
4056 $info['total'] = $total;
4057 $info['paid'] = $total - $paymentBalance;
4058 $info['balance'] = $paymentBalance;
4059 $info['id'] = $id;
4060 $info['component'] = $component;
356579e9 4061 $info['payLater'] = $contributionIsPayLater;
bc2eeabb
PJ
4062 $rows = array();
4063 if ($getTrxnInfo && $baseTrxnId) {
8cf01b22 4064 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
29c61b58 4065 $sql = "
3636b520 4066 SELECT GROUP_CONCAT(fa.`name`) as financial_account,
4067 ft.total_amount,
4068 ft.payment_instrument_id,
d72b084a 4069 ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, ft.currency, ft.pan_truncation, ft.card_type_id
3636b520 4070
636b20c5 4071 FROM civicrm_contribution con
4072 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
4073 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id
4d193d61 4074 AND ft.to_financial_account_id != %2
800f0fd3 4075 LEFT JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item')
636b20c5 4076 LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id
800f0fd3 4077 LEFT JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id
636b20c5 4078
7fedcca5 4079 WHERE con.id = %1 AND ft.is_payment = 1
3636b520 4080 GROUP BY ft.id";
4d193d61
PN
4081 $queryParams = array(
4082 1 => array($contributionId, 'Integer'),
4083 2 => array($feeFinancialAccount, 'Integer'),
4d193d61
PN
4084 );
4085 $resultDAO = CRM_Core_DAO::executeQuery($sql, $queryParams);
536b8316 4086 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
636b20c5 4087
f2b2a3ff 4088 while ($resultDAO->fetch()) {
536b8316
PJ
4089 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
4090 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
d72b084a 4091 if ($resultDAO->card_type_id) {
4092 $creditCardType = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $resultDAO->card_type_id);
67d56bb5
PN
4093 $pantruncation = '';
4094 if ($resultDAO->pan_truncation) {
4095 $pantruncation = ": {$resultDAO->pan_truncation}";
4096 }
4097 $paidByLabel .= " ({$creditCardType}{$pantruncation})";
4098 }
536b8316 4099 $val = array(
29c61b58 4100 'total_amount' => $resultDAO->total_amount,
636b20c5 4101 'financial_type' => $resultDAO->financial_account,
536b8316 4102 'payment_instrument' => $paidByLabel,
29c61b58
PJ
4103 'receive_date' => $resultDAO->trxn_date,
4104 'trxn_id' => $resultDAO->trxn_id,
4105 'status' => $statuses[$resultDAO->status_id],
7e7e2e3f 4106 'currency' => $resultDAO->currency,
29c61b58 4107 );
536b8316
PJ
4108 if ($paidByName == 'Check') {
4109 $val['check_number'] = $resultDAO->check_number;
4110 }
4111 $rows[] = $val;
29c61b58
PJ
4112 }
4113 $info['transaction'] = $rows;
4114 }
4115 return $info;
4116 }
5a18a545 4117
4118 /**
2912ed09 4119 * Get financial account id has 'Sales Tax Account is' account relationship with financial type.
5a18a545 4120 *
100fef9d 4121 * @param int $financialTypeId
5a18a545 4122 *
2912ed09 4123 * @return int
4124 * Financial Account Id
5a18a545 4125 */
00be9182 4126 public static function getFinancialAccountId($financialTypeId) {
5a18a545 4127 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
4128 $searchParams = array(
4129 'entity_table' => 'civicrm_financial_type',
4130 'entity_id' => $financialTypeId,
4131 'account_relationship' => $accountRel,
4132 );
4133 $result = array();
f2b2a3ff 4134 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
5a18a545 4135
f2b2a3ff 4136 return CRM_Utils_Array::value('financial_account_id', $result);
5a18a545 4137 }
b5935203 4138
7a9ab499 4139 /**
2912ed09 4140 * Get the tax amount (misnamed function).
7a9ab499
EM
4141 *
4142 * @param array $params
4143 * @param bool $isLineItem
4144 *
2912ed09 4145 * @return array
7a9ab499 4146 */
115fa278 4147 public static function checkTaxAmount($params, $isLineItem = FALSE) {
b5935203 4148 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
4149
7a9ab499 4150 // Update contribution.
b5935203 4151 if (!empty($params['id'])) {
2912ed09 4152 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4153 // there are no tax implications - early return.
4154 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4155 return $params;
4156 }
4157 if (empty($params['prevContribution'])) {
4158 $params['prevContribution'] = self::getOriginalContribution($params['id']);
4159 }
a76b8bd8 4160
4161 foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) {
2912ed09 4162 if (!isset($params[$field])) {
4163 if ($field == 'total_amount' && $params['prevContribution']->tax_amount) {
4164 // Tax amount gets added back on later....
4165 $params['total_amount'] = $params['prevContribution']->total_amount -
4166 $params['prevContribution']->tax_amount;
99a4cd32
SL
4167 }
4168 else {
2912ed09 4169 $params[$field] = $params['prevContribution']->$field;
4170 if ($params[$field] != $params['prevContribution']->$field) {
2912ed09 4171 }
99a4cd32
SL
4172 }
4173 }
b107e882 4174 }
a76b8bd8 4175
2912ed09 4176 self::calculateMissingAmountParams($params, $params['id']);
4177 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4178 // Assign tax Amount on update of contribution
4179 if (!empty($params['prevContribution']->tax_amount)) {
b5935203 4180 $params['tax_amount'] = 'null';
4181 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
4182 foreach ($params['line_item'] as $setID => $priceField) {
4183 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4184 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4185 }
4186 }
4187 }
4188 }
4189 }
4190
2912ed09 4191 // New Contribution and update of contribution with tax rate financial type
5525990d 4192 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
f2b2a3ff
TO
4193 empty($params['skipLineItem']) && !$isLineItem
4194 ) {
4195 $taxRateParams = $taxRates[$params['financial_type_id']];
def7e770 4196 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams);
f2b2a3ff 4197 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
b5935203 4198
f2b2a3ff
TO
4199 // Get Line Item on update of contribution
4200 if (isset($params['id'])) {
4201 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
4202 }
4203 else {
4204 CRM_Price_BAO_LineItem::getLineItemArray($params);
4205 }
4206 foreach ($params['line_item'] as $setID => $priceField) {
4207 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4208 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
b5935203 4209 }
5525990d 4210 }
def7e770 4211 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount'];
f2b2a3ff 4212 }
4c9b6178 4213 elseif (isset($params['api.line_item.create'])) {
5525990d 4214 // Update total amount of contribution using lineItem
b5935203 4215 $taxAmountArray = array();
4216 foreach ($params['api.line_item.create'] as $key => $value) {
4217 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
f2b2a3ff 4218 $taxRate = $taxRates[$value['financial_type_id']];
5525990d 4219 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
b5935203 4220 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4221 }
4222 }
4223 $params['tax_amount'] = array_sum($taxAmountArray);
5525990d 4224 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
b5935203 4225 }
4226 else {
4227 // update line item of contrbution
4228 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
4229 $taxRate = $taxRates[$params['financial_type_id']];
4230 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
4231 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4232 }
4233 }
4234 return $params;
4235 }
96025800 4236
4d47ad17
PN
4237 /**
4238 * Check financial type validation on update of a contribution.
4239 *
4240 * @param Integer $financialTypeId
4241 * Value of latest Financial Type.
4242 *
8499d1ea 4243 * @param Integer $contributionId
4d47ad17
PN
4244 * Contribution Id.
4245 *
4246 * @param array $errors
4247 * List of errors.
4248 *
4249 * @return bool
4250 */
4251 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4252 if (!empty($financialTypeId)) {
4253 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4254 if ($oldFinancialTypeId == $financialTypeId) {
4255 return FALSE;
4256 }
4257 }
4258 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4259 $params = array(
8499d1ea 4260 '1' => array($contributionId, 'Integer'),
4d47ad17
PN
4261 );
4262 $result = CRM_Core_DAO::executeQuery($sql, $params);
4263 if ($result->N > 1) {
4264 $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
4265 }
4266 }
4267
6d0cf504
EM
4268 /**
4269 * Update related pledge payment payments.
4270 *
5e27919e
EM
4271 * This function has been refactored out of the back office contribution form and may
4272 * still overlap with other functions.
4273 *
6d0cf504
EM
4274 * @param string $action
4275 * @param int $pledgePaymentID
4276 * @param int $contributionID
4277 * @param bool $adjustTotalAmount
4278 * @param float $total_amount
4279 * @param float $original_total_amount
4280 * @param int $contribution_status_id
4281 * @param int $original_contribution_status_id
4282 */
5e27919e 4283 public static function updateRelatedPledge(
6d0cf504
EM
4284 $action,
4285 $pledgePaymentID,
4286 $contributionID,
4287 $adjustTotalAmount,
4288 $total_amount,
4289 $original_total_amount,
4290 $contribution_status_id,
4291 $original_contribution_status_id
4292 ) {
8e776a1a
SB
4293 if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) {
4294 return;
4295 }
4296
6d0cf504
EM
4297 if ($pledgePaymentID) {
4298 //store contribution id in payment record.
4299 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4300 }
4301 else {
4302 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4303 $contributionID,
4304 'id',
4305 'contribution_id'
4306 );
4307 }
fcdf24a4 4308
8e776a1a 4309 if (!$pledgePaymentID) {
fcdf24a4
SB
4310 return;
4311 }
6d0cf504
EM
4312 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4313 $contributionID,
4314 'pledge_id',
4315 'contribution_id'
4316 );
4317
4318 $updatePledgePaymentStatus = FALSE;
4319
4320 // If either the status or the amount has changed we update the pledge status.
4321 if ($action & CRM_Core_Action::ADD) {
4322 $updatePledgePaymentStatus = TRUE;
4323 }
4324 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4325 ($original_total_amount != $total_amount))
4326 ) {
4327 $updatePledgePaymentStatus = TRUE;
4328 }
4329
4330 if ($updatePledgePaymentStatus) {
4331 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
4332 array($pledgePaymentID),
4333 $contribution_status_id,
4334 NULL,
4335 $total_amount,
4336 $adjustTotalAmount
4337 );
4338 }
4339 }
456b0145 4340
ae6884ce 4341 /**
4342 * Compute the stats values
4343 *
bc854509 4344 * @param string $stat either 'mode' or 'median'
4345 * @param string $sql
4346 * @param string $alias of civicrm_contribution
4347 *
4348 * @return array|null
ae6884ce 4349 */
4350 public static function computeStats($stat, $sql, $alias = NULL) {
899439b0 4351 $mode = $median = array();
23ce9a3a 4352 switch ($stat) {
ae6884ce 4353 case 'mode':
4354 $modeDAO = CRM_Core_DAO::executeQuery($sql);
4355 while ($modeDAO->fetch()) {
4356 if ($modeDAO->civicrm_contribution_total_amount_count > 1) {
4357 $mode[] = CRM_Utils_Money::format($modeDAO->amount, $modeDAO->currency);
4358 }
4359 else {
4360 $mode[] = 'N/A';
4361 }
4362 }
4363 return $mode;
4364
4365 case 'median':
ae6884ce 4366 $currencies = CRM_Core_OptionGroup::values('currencies_enabled');
4367 foreach ($currencies as $currency => $val) {
e9ec4119 4368 $midValue = 0;
ae6884ce 4369 $where = "AND {$alias}.currency = '{$currency}'";
4370 $rowCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) as count {$sql} {$where}");
4371
4372 $even = FALSE;
4373 $offset = 1;
4374 $medianRow = floor($rowCount / 2);
4375 if ($rowCount % 2 == 0 && !empty($medianRow)) {
4376 $even = TRUE;
4377 $offset++;
4378 $medianRow--;
4379 }
4380
4381 $medianValue = "SELECT {$alias}.total_amount as median
4382 {$sql} {$where}
4383 ORDER BY median LIMIT {$medianRow},{$offset}";
4384 $medianValDAO = CRM_Core_DAO::executeQuery($medianValue);
4385 while ($medianValDAO->fetch()) {
4386 if ($even) {
4387 $midValue = $midValue + $medianValDAO->median;
4388 }
4389 else {
4390 $median[] = CRM_Utils_Money::format($medianValDAO->median, $currency);
4391 }
4392 }
4393 if ($even) {
23ce9a3a 4394 $midValue = $midValue / 2;
ae6884ce 4395 $median[] = CRM_Utils_Money::format($midValue, $currency);
4396 }
4397 }
4398 return $median;
4399
23ce9a3a 4400 default:
bc854509 4401 return NULL;
ae6884ce 4402 }
4403 }
4404
3c49d90c 4405 /**
4406 * Is there only one line item attached to the contribution.
4407 *
4408 * @param int $id
4409 * Contribution ID.
4410 *
4411 * @return bool
4412 * @throws \CiviCRM_API3_Exception
4413 */
4414 public static function isSingleLineItem($id) {
467fe956 4415 $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id));
3c49d90c 4416 return ($lineItemCount == 1);
4417 }
4418
db59bb73
EM
4419 /**
4420 * Complete an order.
4421 *
4422 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4423 *
4424 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4425 *
4426 * Moving it out of the BaseIPN class is just the first step.
4427 *
4428 * @param array $input
4429 * @param array $ids
4430 * @param array $objects
4431 * @param CRM_Core_Transaction $transaction
4432 * @param int $recur
4433 * @param CRM_Contribute_BAO_Contribution $contribution
4434 * @param bool $isRecurring
4b6c8c1e 4435 * Duplication of param needs review. Only used by AuthorizeNetIPN
db59bb73 4436 * @param int $isFirstOrLastRecurringPayment
4b6c8c1e 4437 * Deprecated param only used by AuthorizeNetIPN.
bc854509 4438 *
4439 * @return array
db59bb73 4440 */
59626c7f 4441 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) {
db59bb73 4442 $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
66df7769 4443 // The previous details are used when calculating line items so keep it before any code that 'does something'
4444 if (!empty($contribution->id)) {
4445 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id),
4446 CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
4447 }
b3b7f4c5 4448 $inputContributionWhiteList = array(
4449 'fee_amount',
4450 'net_amount',
4451 'trxn_id',
4452 'check_number',
4453 'payment_instrument_id',
4454 'is_test',
1c98b2d6 4455 'campaign_id',
12829b5d 4456 'receive_date',
d9924163 4457 'receipt_date',
d5580ed4 4458 'contribution_status_id',
b3b7f4c5 4459 );
3c49d90c 4460 if (self::isSingleLineItem($primaryContributionID)) {
4461 $inputContributionWhiteList[] = 'financial_type_id';
4462 }
b3b7f4c5 4463
7f4ef731 4464 $participant = CRM_Utils_Array::value('participant', $objects);
4465 $memberships = CRM_Utils_Array::value('membership', $objects);
4466 $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
294cc627 4467 $recurringContributionID = (empty($recurContrib->id)) ? NULL : $recurContrib->id;
7f4ef731 4468 $event = CRM_Utils_Array::value('event', $objects);
b3b7f4c5 4469
43c8d1dd 4470 $paymentProcessorId = '';
4471 if (isset($objects['paymentProcessor'])) {
4472 if (is_array($objects['paymentProcessor'])) {
4473 $paymentProcessorId = $objects['paymentProcessor']['id'];
4474 }
4475 else {
4476 $paymentProcessorId = $objects['paymentProcessor']->id;
4477 }
4478 }
4479
b929cdb4 4480 $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4481
b3b7f4c5 4482 $contributionParams = array_merge(array(
b929cdb4 4483 'contribution_status_id' => $completedContributionStatusID,
7f4ef731 4484 'source' => self::getRecurringContributionDescription($contribution, $event),
b3b7f4c5 4485 ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4486 ));
bf722049 4487 $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
b3b7f4c5 4488
f443eb02
SL
4489 // If paymentProcessor is not set then the payment_instrument_id would not be correct.
4490 // not clear when or if this would occur if you encounter this please fix here & add a unit test.
4491 if (empty($contributionParams['payment_instrument_id']) && isset($contribution->_relatedObjects['paymentProcessor']['payment_instrument_id'])) {
4492 $contributionParams['payment_instrument_id'] = $contribution->_relatedObjects['paymentProcessor']['payment_instrument_id'];
4493 }
4494
294cc627 4495 if ($recurringContributionID) {
4496 $contributionParams['contribution_recur_id'] = $recurringContributionID;
b3b7f4c5 4497 }
7f4ef731 4498 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4499
4500 if (empty($contributionParams['receive_date']) && $changeDate) {
4501 $contributionParams['receive_date'] = $changeDate;
4502 }
4503
43c8d1dd 4504 self::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
7f4ef731 4505 $contributionParams['financial_type_id'] = $contribution->financial_type_id;
db59bb73
EM
4506
4507 if (is_numeric($memberships)) {
4508 $memberships = array($objects['membership']);
4509 }
4510
db59bb73
EM
4511 $values = array();
4512 if (isset($input['is_email_receipt'])) {
4513 $values['is_email_receipt'] = $input['is_email_receipt'];
4514 }
b3b7f4c5 4515
db59bb73
EM
4516 if ($input['component'] == 'contribute') {
4517 if ($contribution->contribution_page_id) {
7f4ef731 4518 // Figure out what we gain from this.
5602ee2b 4519 // Note that we may have overwritten the is_email_receipt input, fix that below.
db59bb73 4520 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
db59bb73 4521 }
294cc627 4522 elseif ($recurContrib && $recurringContributionID) {
db59bb73
EM
4523 $values['amount'] = $recurContrib->amount;
4524 $values['financial_type_id'] = $objects['contributionType']->id;
4525 $values['title'] = $source = ts('Offline Recurring Contribution');
db59bb73
EM
4526 }
4527
5602ee2b 4528 if (isset($input['is_email_receipt'])) {
4529 // CRM-19601 - we may have overwritten this above.
4530 $values['is_email_receipt'] = $input['is_email_receipt'];
4531 }
4532 elseif ($recurContrib && $recurringContributionID) {
db59bb73
EM
4533 //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
4534 // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
4535 $values['is_email_receipt'] = $recurContrib->is_email_receipt;
4536 }
4537
db59bb73 4538 if (!empty($memberships)) {
db59bb73
EM
4539 foreach ($memberships as $membershipTypeIdKey => $membership) {
4540 if ($membership) {
4ff927bc 4541 $membershipParams = array(
4542 'id' => $membership->id,
4543 'contact_id' => $membership->contact_id,
4544 'is_test' => $membership->is_test,
4545 'membership_type_id' => $membership->membership_type_id,
4546 );
db59bb73 4547
1f7c01e4 4548 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
4549 $membershipParams['membership_type_id'],
4550 $membershipParams['is_test'],
4551 $membershipParams['id']
db59bb73
EM
4552 );
4553
4554 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
4555 // this picks up membership type changes during renewals
7c3f3d59 4556 // @todo this is almost certainly an obsolete sql call, the pre-change
4557 // membership is accessible via $this->_relatedObjects
db59bb73
EM
4558 $sql = "
4559SELECT membership_type_id
4560FROM civicrm_membership_log
1f7c01e4 4561WHERE membership_id={$membershipParams['id']}
db59bb73
EM
4562ORDER BY id DESC
4563LIMIT 1;";
1f7c01e4 4564 $dao = CRM_Core_DAO::executeQuery($sql);
db59bb73
EM
4565 if ($dao->fetch()) {
4566 if (!empty($dao->membership_type_id)) {
1f7c01e4 4567 $membershipParams['membership_type_id'] = $dao->membership_type_id;
db59bb73 4568 }
db59bb73 4569 }
db59bb73
EM
4570 $dao->free();
4571
4ff927bc 4572 $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType(
4573 $membershipParams['membership_type_id'],
4574 $primaryContributionID
4575 );
4b6c8c1e 4576 $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
db59bb73
EM
4577 if ($currentMembership) {
4578 /*
4579 * Fixed FOR CRM-4433
4580 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
4581 * when Contribution mode is notify and membership is for renewal )
4582 */
4583 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
4584
4585 // @todo - we should pass membership_type_id instead of null here but not
4586 // adding as not sure of testing
1f7c01e4 4587 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
4ff927bc 4588 $changeDate, NULL, $membershipParams['num_terms']
db59bb73
EM
4589 );
4590
1f7c01e4 4591 $dates['join_date'] = $currentMembership['join_date'];
db59bb73 4592 }
db59bb73
EM
4593
4594 //get the status for membership.
4595 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
4596 $dates['end_date'],
4597 $dates['join_date'],
4598 'today',
4599 TRUE,
1f7c01e4 4600 $membershipParams['membership_type_id'],
4601 $membershipParams
db59bb73
EM
4602 );
4603
c31bec3d 4604 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
db59bb73
EM
4605 //we might be renewing membership,
4606 //so make status override false.
1f7c01e4 4607 $membershipParams['is_override'] = FALSE;
f8d3033b 4608 //CRM-17723 - reset static $relatedContactIds array()
4609 $var = TRUE;
4610 CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
1f7c01e4 4611 civicrm_api3('Membership', 'create', $membershipParams);
b95fe31c 4612 //CRM-19600: Add Membership Renewal activity
4613 CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Renewal', $membership->contact_id);
db59bb73
EM
4614 }
4615 }
db59bb73
EM
4616 }
4617 }
4618 else {
0bad10e7 4619 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
7f4ef731 4620 if ($event->is_email_confirm) {
66df7769 4621 // @todo this should be set by the function that sends the mail after sending.
4622 $contributionParams['receipt_date'] = $changeDate;
4623 }
4624 $participantParams['id'] = $participant->id;
1c98b2d6 4625 $participantParams['status_id'] = 'Registered';
66df7769 4626 civicrm_api3('Participant', 'create', $participantParams);
db59bb73 4627 }
db59bb73
EM
4628 }
4629
b3b7f4c5 4630 $contributionParams['id'] = $contribution->id;
db59bb73 4631
7150b1c8 4632 // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
0e6ccb2e
K
4633 // unsetting it here does NOT cause any other contribution test to fail!
4634 unset($contributionParams['financial_type_id']);
734d2daa 4635 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
db59bb73
EM
4636
4637 // Add new soft credit against current $contribution.
4638 if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
4639 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
4640 }
4641
db59bb73
EM
4642 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4643 'labelColumn' => 'name',
4644 'flip' => 1,
4645 ));
43c8d1dd 4646 if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
db59bb73
EM
4647 $input['payment_processor'] = $paymentProcessorId;
4648 }
db59bb73
EM
4649
4650 if (!empty($contribution->_relatedObjects['participant'])) {
4651 $input['contribution_mode'] = 'participant';
4652 $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
db59bb73
EM
4653 }
4654 elseif (!empty($contribution->_relatedObjects['membership'])) {
db59bb73 4655 $input['contribution_mode'] = 'membership';
d5580ed4 4656 $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
b34861f3 4657 $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input);
4658 $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
db59bb73 4659 }
db59bb73
EM
4660
4661 CRM_Core_Error::debug_log_message("Contribution record updated successfully");
4662 $transaction->commit();
4663
294cc627 4664 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution->id, $recurringContributionID,
43c8d1dd 4665 $contributionParams['contribution_status_id'], $input['amount']);
db59bb73
EM
4666
4667 // create an activity record
4668 if ($input['component'] == 'contribute') {
4669 //CRM-4027
4670 $targetContactID = NULL;
4671 if (!empty($ids['related_contact'])) {
4672 $targetContactID = $contribution->contact_id;
4673 $contribution->contact_id = $ids['related_contact'];
4674 }
4675 CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
4676 // event
4677 }
4678 else {
4679 CRM_Activity_BAO_Activity::addActivity($participant);
4680 }
4681
4682 // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
4683 // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
4684 if (!array_key_exists('is_email_receipt', $values) ||
4685 $values['is_email_receipt'] == 1
4686 ) {
ec7e3954
E
4687 civicrm_api3('Contribution', 'sendconfirmation', array(
4688 'id' => $contribution->id,
4689 'payment_processor_id' => $paymentProcessorId,
4690 ));
db59bb73
EM
4691 CRM_Core_Error::debug_log_message("Receipt sent");
4692 }
4693
4694 CRM_Core_Error::debug_log_message("Success: Database updated");
4695 if ($isRecurring) {
4696 CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur,
4697 $isFirstOrLastRecurringPayment);
4698 }
734d2daa 4699 return $contributionResult;
db59bb73
EM
4700 }
4701
4702 /**
4703 * Send receipt from contribution.
4704 *
4705 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4706 *
4707 * Note that the compose message part has been moved to contribution
4708 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4709 *
4710 * @param array $input
4711 * Incoming data from Payment processor.
4712 * @param array $ids
4713 * Related object IDs.
ec7e3954 4714 * @param int $contributionID
db59bb73
EM
4715 * @param array $values
4716 * Values related to objects that have already been loaded.
db59bb73
EM
4717 * @param bool $returnMessageText
4718 * Should text be returned instead of sent. This.
4719 * is because the function is also used to generate pdfs
4720 *
4721 * @return array
ec7e3954
E
4722 * @throws \CRM_Core_Exception
4723 * @throws \CiviCRM_API3_Exception
db59bb73 4724 */
6626a693 4725 public static function sendMail(&$input, &$ids, $contributionID, &$values,
ec7e3954 4726 $returnMessageText = FALSE) {
ec7e3954
E
4727
4728 $contribution = new CRM_Contribute_BAO_Contribution();
4729 $contribution->id = $contributionID;
4730 if (!$contribution->find(TRUE)) {
4731 throw new CRM_Core_Exception('Contribution does not exist');
4732 }
4733 $contribution->loadRelatedObjects($input, $ids, TRUE);
db59bb73
EM
4734 // set receipt from e-mail and name in value
4735 if (!$returnMessageText) {
cefed6df 4736 list($values['receipt_from_name'], $values['receipt_from_email']) = self::generateFromEmailAndName($input, $contribution);
db59bb73 4737 }
d891a273 4738 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
cc7b912f 4739 // Contribution ID should really always be set. But ?
76e8d9c4 4740 if (!$returnMessageText && (!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) {
cc7b912f 4741 civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id));
4742 }
76e8d9c4 4743 return $return;
db59bb73
EM
4744 }
4745
cefed6df
SL
4746 /**
4747 * Generate From email and from name in an array values
4748 */
4749 public static function generateFromEmailAndName($input, $contribution) {
4750 // Use input valuse if supplied.
4751 if (!empty($input['receipt_from_email'])) {
4752 return array(CRM_Utils_array::value('receipt_from_name', $input, ''), $input['receipt_from_email']);
4753 }
4754 // if we are still empty see if we can use anything from a contribution page.
4755 $pageValues = array();
4756 if (!empty($contribution->contribution_page_id)) {
4757 $pageValues = civicrm_api3('ContributionPage', 'getsingle', array('id' => $contribution->contribution_page_id));
4758 }
4759 // if we are still empty see if we can use anything from a contribution page.
4760 if (!empty($pageValues['receipt_from_email'])) {
4761 return array($pageValues['receipt_from_name'], $pageValues['receipt_from_email']);
4762 }
b5bfb58f
SL
4763 // If we are still empty fall back to the domain or logged in user information.
4764 return CRM_Core_BAO_Domain::getDefaultReceiptFrom();
cefed6df
SL
4765 }
4766
1844808f
GC
4767 /**
4768 * Generate credit note id with next avaible number
4769 *
1844808f
GC
4770 * @return string
4771 * Credit Note Id.
4772 */
4add5adb 4773 public static function createCreditNoteId() {
aaffa79f 4774 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
1844808f 4775
8d20d89c 4776 $creditNoteNum = CRM_Core_DAO::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution");
1844808f
GC
4777 $creditNoteId = NULL;
4778
4779 do {
4780 $creditNoteNum++;
4781 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum;
4782 $result = civicrm_api3('Contribution', 'getcount', array(
4783 'sequential' => 1,
4784 'creditnote_id' => $creditNoteId,
4785 ));
4786 } while ($result > 0);
4787
1844808f
GC
4788 return $creditNoteId;
4789 }
4790
4ae9c8ac 4791 /**
4792 * Load related memberships.
4793 *
4794 * Note that in theory it should be possible to retrieve these from the line_item table
4795 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4796 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4797 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4798 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4799 *
4800 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4801 *
4802 * @param array $ids
4803 *
4804 * @throws Exception
4805 */
4806 public function loadRelatedMembershipObjects(&$ids) {
4807 $query = "
4808 SELECT membership_id
4809 FROM civicrm_membership_payment
4810 WHERE contribution_id = %1 ";
4811 $params = array(1 => array($this->id, 'Integer'));
356bfcaf 4812 $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, array());
4ae9c8ac 4813
4814 $dao = CRM_Core_DAO::executeQuery($query, $params);
4815 while ($dao->fetch()) {
356bfcaf 4816 if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) {
4817 $ids['membership'][$dao->membership_id] = $dao->membership_id;
4ae9c8ac 4818 }
4819 }
4820
4821 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4822 foreach ($ids['membership'] as $id) {
4823 if (!empty($id)) {
4824 $membership = new CRM_Member_BAO_Membership();
4825 $membership->id = $id;
4826 if (!$membership->find(TRUE)) {
4827 throw new Exception("Could not find membership record: $id");
4828 }
4829 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
4830 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
4831 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
4832 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
4833 $membership->free();
4834 }
4835 }
4836 }
4837 }
4838
6b18d1bd
PN
4839 /**
4840 * This function is used to record partial payments for contribution
4841 *
4842 * @param array $contribution
4843 *
4844 * @param array $params
4845 *
4846 * @return object
4847 */
4848 public static function recordPartialPayment($contribution, $params) {
4849 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
4850 $pendingStatus = array(
4851 array_search('Pending', $contributionStatuses),
4852 array_search('In Progress', $contributionStatuses),
4853 );
4854 $statusId = array_search('Completed', $contributionStatuses);
4855 if (in_array(CRM_Utils_Array::value('contribution_status_id', $contribution), $pendingStatus)) {
876b8ab0 4856 $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
6b18d1bd
PN
4857 }
4858 elseif (!empty($params['payment_processor'])) {
4859 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
4860 }
4861 elseif (!empty($params['payment_instrument_id'])) {
4862 $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']);
4863 }
4864 else {
4865 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
4866 $queryParams = array(1 => array($relationTypeId, 'Integer'));
4867 $balanceTrxnParams['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
4868 }
876b8ab0 4869 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is');
6b18d1bd
PN
4870 $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId;
4871 $balanceTrxnParams['total_amount'] = $params['total_amount'];
4872 $balanceTrxnParams['contribution_id'] = $params['contribution_id'];
4873 $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ? $params['contribution_receive_date'] : date('YmdHis');
4874 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
4875 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('total_amount', $params);
4876 $balanceTrxnParams['currency'] = $contribution['currency'];
4877 $balanceTrxnParams['trxn_id'] = CRM_Utils_Array::value('contribution_trxn_id', $params, NULL);
4878 $balanceTrxnParams['status_id'] = $statusId;
4879 $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $params, $contribution['payment_instrument_id']);
4880 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
4881 if ($fromFinancialAccountId != NULL &&
4882 ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses))
4883 ) {
4884 $balanceTrxnParams['is_payment'] = 1;
4885 }
4886 if (!empty($params['payment_processor'])) {
4887 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
4888 }
4889 return CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
4890 }
4891
7f4ef731 4892 /**
467fe956 4893 * Get the description (source field) for the recurring contribution.
4894 *
4895 * @param CRM_Contribute_BAO_Contribution $contribution
4896 * @param CRM_Event_DAO_Event|null $event
4897 *
4898 * @return array
4899 * @throws \CiviCRM_API3_Exception
4900 */
7f4ef731 4901 protected static function getRecurringContributionDescription($contribution, $event) {
6046ccbb 4902 if (!empty($contribution->source)) {
7b9947fb
ML
4903 return $contribution->source;
4904 }
4052b01e 4905 elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
7f4ef731 4906 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array(
4907 'id' => $contribution->contribution_page_id,
4908 'return' => 'title',
4909 ));
4910 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4911 }
467fe956 4912 elseif ($event) {
7f4ef731 4913 return ts('Online Event Registration') . ': ' . $event->title;
4914 }
bef53ccf 4915 elseif (!empty($contribution->contribution_recur_id)) {
4916 return 'recurring contribution';
4917 }
4918 return '';
7f4ef731 4919 }
4920
0618910b
PN
4921 /**
4922 * Function to add payments for contribution
4923 * for Partially Paid status
4924 *
0618910b 4925 * @param array $contributions
958a4abe 4926 * @param array $contributionStatusId
0618910b
PN
4927 *
4928 */
955ee56e 4929 public static function addPayments($contributions, $contributionStatusId = NULL) {
e4ba8498 4930 // get financial trxn which is a payment
57dcb94e 4931 $ftSql = "SELECT ft.id, ft.total_amount
b34861f3 4932 FROM civicrm_financial_trxn ft
0618910b 4933 INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution'
57dcb94e 4934 WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1";
e8403178
PN
4935 $contributionStatus = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
4936 'labelColumn' => 'name',
4937 ));
69ea45f2 4938 foreach ($contributions as $k => $contribution) {
e8403178 4939 if (!($contributionStatus[$contribution->contribution_status_id] == 'Partially paid'
958a4abe 4940 || CRM_Utils_Array::value($contributionStatusId, $contributionStatus) == 'Partially paid')
e8403178 4941 ) {
69ea45f2
PN
4942 continue;
4943 }
57dcb94e 4944 $ftDao = CRM_Core_DAO::executeQuery($ftSql, array(1 => array($contribution->id, 'Integer')));
2a21b19d 4945 $ftDao->fetch();
2a21b19d 4946
955ee56e
PN
4947 // store financial item Proportionaly.
4948 $trxnParams = array(
4949 'total_amount' => $ftDao->total_amount,
4950 'contribution_id' => $contribution->id,
dea99e05 4951 );
955ee56e 4952 self::assignProportionalLineItems($trxnParams, $ftDao->id, $contribution->total_amount);
0618910b
PN
4953 }
4954 }
4955
27d9f6c5 4956 /**
1b7fd6d4 4957 * Function use to store line item proportionaly in
27d9f6c5
PN
4958 * in entity financial trxn table
4959 *
955ee56e 4960 * @param array $trxnParams
8de1ade9
PN
4961 *
4962 * @param Integer $trxnId
4963 *
4964 * @param float $contributionTotalAmount
27d9f6c5
PN
4965 *
4966 */
955ee56e
PN
4967 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4968 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']);
27d9f6c5
PN
4969 if (!empty($lineItems)) {
4970 // get financial item
8e10ee7c
PN
4971 list($ftIds, $taxItems) = self::getLastFinancialItemIds($trxnParams['contribution_id']);
4972 $entityParams = array(
4973 'contribution_total_amount' => $contributionTotalAmount,
4974 'trxn_total_amount' => $trxnParams['total_amount'],
4975 'trxn_id' => $trxnId,
3e00a301 4976 );
8e10ee7c 4977 self::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
27d9f6c5
PN
4978 }
4979 }
4980
5c8b902b 4981 /**
bc854509 4982 * Function to check line items.
5c8b902b
PN
4983 *
4984 * @param array $params
4985 * array of order params.
4986 *
bc854509 4987 * @throws \API_Exception
5c8b902b
PN
4988 */
4989 public static function checkLineItems(&$params) {
4990 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
4991 $lineItemAmount = 0;
4992 foreach ($params['line_items'] as &$lineItems) {
4993 foreach ($lineItems['line_item'] as &$item) {
4994 if (empty($item['financial_type_id'])) {
4995 $item['financial_type_id'] = $params['financial_type_id'];
4996 }
4997 $lineItemAmount += $item['line_total'];
4998 }
4999 }
5000 if (!isset($totalAmount)) {
5001 $params['total_amount'] = $lineItemAmount;
5002 }
5003 elseif ($totalAmount != $lineItemAmount) {
af004c04 5004 throw new API_Exception("Line item total doesn't match with total amount.");
5c8b902b 5005 }
5c8b902b
PN
5006 }
5007
bf2cf926 5008 /**
5009 * Get the financial account for the item associated with the new transaction.
5010 *
5011 * @param array $params
5012 * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem
5013 *
5014 * @return int
5015 */
5016 public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) {
5017
5018 if (!empty($params['financial_account_id'])) {
5019 return $params['financial_account_id'];
5020 }
5021 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name');
5022 $preferredAccountsRelationships = array(
5023 'Refunded' => 'Credit/Contra Revenue Account is',
5024 'Chargeback' => 'Chargeback Account is',
5025 );
5026 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
5027 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
5028 return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
5029 $financialTypeID,
5030 $preferredAccountsRelationships[$contributionStatus]
5031 );
5032 }
5033 return $prevFinancialItem->financial_account_id;
5034 }
5035
f99a6f98 5036 /**
5037 * ContributionPage values were being imposed onto values.
5038 *
5039 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
5040 * REALLY didn't want superimposed. The rest are left there in their overkill out
5041 * of cautiousness.
5042 *
5043 * The rationale for making this explicit is that it was a case of carefully set values being
5044 * seemingly randonly overwritten without much care. In general I think array randomly setting
5045 * variables en mass is risky.
5046 *
5047 * @param array $values
5048 *
5049 * @return array
5050 */
5051 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
5052 $contributionPageValues = array();
5053 CRM_Contribute_BAO_ContributionPage::setValues(
5054 $this->contribution_page_id,
5055 $contributionPageValues
5056 );
5057 $valuesToCopy = array(
5058 // These are the values that I believe to be useful.
e4dcb541 5059 'id',
f99a6f98 5060 'title',
f99a6f98 5061 'pay_later_receipt',
5062 'pay_later_text',
5063 'receipt_from_email',
5064 'receipt_from_name',
5065 'receipt_text',
ee1dffa7 5066 'custom_pre_id',
f99a6f98 5067 'custom_post_id',
5068 'honoree_profile_id',
5069 'onbehalf_profile_id',
ee1dffa7 5070 'honor_block_is_active',
f99a6f98 5071 // Kinda might be - but would be on the contribution...
5072 'campaign_id',
5073 'currency',
5074 // Included for 'fear of regression' but can't justify any use for these....
5075 'intro_text',
5076 'payment_processor',
5077 'financial_type_id',
5078 'amount_block_is_active',
5079 'bcc_receipt',
5080 'cc_receipt',
5081 'created_date',
5082 'created_id',
5083 'default_amount_id',
5084 'end_date',
5085 'footer_text',
5086 'goal_amount',
5087 'initial_amount_help_text',
5088 'initial_amount_label',
5089 'intro_text',
5090 'is_allow_other_amount',
5091 'is_billing_required',
5092 'is_confirm_enabled',
5093 'is_credit_card_only',
5094 'is_monetary',
5095 'is_partial_payment',
5096 'is_recur_installments',
5097 'is_recur_interval',
5098 'is_share',
5099 'max_amount',
5100 'min_amount',
5101 'min_initial_amount',
5102 'recur_frequency_unit',
5103 'start_date',
5104 'thankyou_footer',
5105 'thankyou_text',
5106 'thankyou_title',
5107
5108 );
5109 foreach ($valuesToCopy as $valueToCopy) {
5110 if (isset($contributionPageValues[$valueToCopy])) {
5111 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
5112 }
5113 }
5114 return $values;
5115 }
5116
ce7fc91a
PN
5117 /**
5118 * Get values of CiviContribute Settings
5119 * and check if its enabled or not.
756661dc
PN
5120 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
5121 * in serialized form. Usually this should be stored as flat settings for each form fields
5122 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
5123 * settings we will live with an inconsistency because it's too hard to change for now.
5124 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
ce7fc91a
PN
5125 *
5126 *
5127 * @param string $name
5128 * @return string
5129 *
5130 */
5131 public static function checkContributeSettings($name = NULL) {
5132 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
5133
5134 if ($name) {
5135 return CRM_Utils_Array::value($name, $contributeSettings);
5136 }
5137 return $contributeSettings;
5138 }
5139
643413a0 5140 /**
5141 * This function process contribution related objects.
5142 *
5143 * @param int $contributionId
5144 * @param int $statusId
5145 * @param int|null $previousStatusId
5146 *
5147 * @param string $receiveDate
5148 *
5149 * @return null|string
5150 */
5151 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
5152 $statusMsg = NULL;
5153 if (!$contributionId || !$statusId) {
5154 return $statusMsg;
5155 }
5156
5157 $params = array(
5158 'contribution_id' => $contributionId,
5159 'contribution_status_id' => $statusId,
5160 'previous_contribution_status_id' => $previousStatusId,
5161 'receive_date' => $receiveDate,
5162 );
5163
5164 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
5165
5166 if (!is_array($updateResult) ||
5167 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
5168 !is_array($updatedComponents) ||
5169 empty($updatedComponents)
5170 ) {
5171 return $statusMsg;
5172 }
5173
5174 // get the user display name.
5175 $sql = "
5176 SELECT display_name as displayName
5177 FROM civicrm_contact
5178LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
5179 WHERE civicrm_contribution.id = {$contributionId}";
5180 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
5181
5182 // get the status message for user.
5183 foreach ($updatedComponents as $componentName => $updatedStatusId) {
5184
5185 if ($componentName == 'CiviMember') {
5186 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5187 CRM_Member_PseudoConstant::membershipStatus()
5188 );
5189 if ($updatedStatusName == 'Cancelled') {
5190 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
5191 }
5192 elseif ($updatedStatusName == 'Expired') {
5193 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
5194 }
5195 else {
5196 $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult);
5197 if ($endDate) {
5198 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
5199 array(
5200 1 => $userDisplayName,
5201 2 => $endDate,
5202 )
5203 );
5204 }
5205 }
5206 }
5207
5208 if ($componentName == 'CiviEvent') {
5209 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5210 CRM_Event_PseudoConstant::participantStatus()
5211 );
5212 if ($updatedStatusName == 'Cancelled') {
5213 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
5214 }
5215 elseif ($updatedStatusName == 'Registered') {
5216 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
5217 }
5218 }
5219
5220 if ($componentName == 'CiviPledge') {
5221 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
5222 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
5223 );
5224 if ($updatedStatusName == 'Cancelled') {
5225 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
5226 }
5227 elseif ($updatedStatusName == 'Failed') {
5228 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
5229 }
5230 elseif ($updatedStatusName == 'Completed') {
5231 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
5232 }
5233 }
5234 }
5235
5236 return $statusMsg;
5237 }
5238
2912ed09 5239 /**
5240 * Get the contribution as it is in the database before being updated.
5241 *
5242 * @param int $contributionID
5243 *
5244 * @return array
5245 */
5246 private static function getOriginalContribution($contributionID) {
5247 return self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
5248 }
5249
94183dd6
SL
5250 /**
5251 * Assign Test Value.
5252 *
5253 * @param string $fieldName
5254 * @param array $fieldDef
5255 * @param int $counter
5256 */
5257 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5258 if ($fieldName == 'tax_amount') {
5259 $this->{$fieldName} = "0.00";
5260 }
5261 elseif ($fieldName == 'net_amount') {
5262 $this->{$fieldName} = "2.00";
5263 }
5264 elseif ($fieldName == 'total_amount') {
5265 $this->{$fieldName} = "3.00";
5266 }
5267 elseif ($fieldName == 'fee_amount') {
5268 $this->{$fieldName} = "1.00";
5269 }
5270 else {
5271 parent::assignTestValues($fieldName, $fieldDef, $counter);
5272 }
5273 }
5274
623712fb
PN
5275 /**
5276 * Check if contribution has participant/membership payment.
5277 *
5278 * @param int $contributionId
5279 * Contribution ID
5280 *
5281 * @return bool
5282 */
5283 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5284 // get line item for contribution
77dbdcbc 5285 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
623712fb
PN
5286 // check if line item is for membership or participant
5287 foreach ($lineItems as $items) {
5288 if ($items['entity_table'] == 'civicrm_participant') {
6f148218 5289 $flag = FALSE;
623712fb
PN
5290 break;
5291 }
5292 elseif ($items['entity_table'] == 'civicrm_membership') {
6f148218 5293 $flag = FALSE;
623712fb
PN
5294 }
5295 else {
6f148218 5296 $flag = TRUE;
623712fb
PN
5297 break;
5298 }
5299 }
5300 return $flag;
5301 }
5302
14b1ab0c
PN
5303 /**
5304 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5305 *
9c472292
PN
5306 * @param array $trxnParams
5307 * Financial trxn params
5308 * @param string $contributionParams
5309 * Contribution Params
a9c48769 5310 *
9c472292 5311 * @return string
14b1ab0c 5312 */
9c472292 5313 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
14b1ab0c
PN
5314 if (!self::checkContributeSettings('always_post_to_accounts_receivable')) {
5315 return NULL;
5316 }
9c472292 5317 $statusId = $contributionParams['contribution']->contribution_status_id;
14b1ab0c 5318 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
a9c48769 5319 $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId];
352cae98 5320 $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id];
14b1ab0c 5321 // Return if contribution status is not completed.
352cae98
PN
5322 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5323 || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5324 && $contributionParams['prevContribution']->is_pay_later == 0
5325 )))
5326 ) {
14b1ab0c
PN
5327 return NULL;
5328 }
352cae98 5329
9c472292
PN
5330 $params = $trxnParams;
5331 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $contributionParams) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id;
876b8ab0 5332 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
9c472292
PN
5333 $params['to_financial_account_id'] = $arAccountId;
5334 $params['status_id'] = array_search('Pending', $contributionStatuses);
5335 $params['is_payment'] = FALSE;
5336 $trxn = CRM_Core_BAO_FinancialTrxn::create($params);
5337 self::$_trxnIDs[] = $trxn->id;
5338 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
14b1ab0c
PN
5339 }
5340
d9553c2e
PN
5341 /**
5342 * Calculate financial item amount when contribution is updated.
5343 *
5344 * @param array $params
5345 * contribution params
5346 * @param array $amountParams
5347 *
5348 * @param string $context
5349 *
5350 * @return float
5351 */
5352 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5353 if (!empty($params['is_quick_config'])) {
5354 $amount = $amountParams['item_amount'];
5355 if (!$amount) {
5356 $amount = $params['total_amount'];
5357 if ($context === NULL) {
5358 $amount -= CRM_Utils_Array::value('tax_amount', $params, 0);
5359 }
5360 }
5361 }
5362 else {
5363 $amount = $amountParams['line_total'];
5364 if ($context == 'changedAmount') {
5365 $amount -= $amountParams['previous_line_total'];
5366 }
5367 $amount *= $amountParams['diff'];
5368 }
5369 return $amount;
5370 }
5371
cdc6ce4d
PN
5372 /**
5373 * Retrieve Sales Tax Financial Accounts.
5374 *
5375 *
5376 * @return array
5377 *
5378 */
5379 public static function getSalesTaxFinancialAccounts() {
5380 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5381 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5382 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5383 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5384 $queryParams = array(1 => array($accountRel, 'Integer'));
5385 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
5386 $financialAccount = array();
5387 while ($dao->fetch()) {
5388 $financialAccount[$dao->id] = $dao->id;
5389 }
5390 return $financialAccount;
5391 }
5392
53f969b9
PN
5393 /**
5394 * Create tax entry in civicrm_entity_financial_trxn table.
5395 *
5396 * @param array $entityParams
5397 *
5398 * @param array $eftParams
5399 *
5400 */
5401 public static function createProportionalEntry($entityParams, $eftParams) {
5402 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
eb0af899 5403 // Record Entity Financial Trxn; CRM-20145
1aca1f1e 5404 $eftParams['amount'] = CRM_Contribute_BAO_Contribution_Utils::formatAmount($paid);
53f969b9
PN
5405 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5406 }
5407
5408 /**
5409 * Create array of last financial item id's.
5410 *
bc854509 5411 * @param int $contributionId
53f969b9 5412 *
bc854509 5413 * @return array
53f969b9
PN
5414 */
5415 public static function getLastFinancialItemIds($contributionId) {
5416 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5417 FROM civicrm_financial_item fi
5418 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5419 WHERE li.contribution_id = %1";
5420 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($contributionId, 'Integer')));
5421 $ftIds = $taxItems = array();
5422 $salesTaxFinancialAccount = self::getSalesTaxFinancialAccounts();
5423 while ($dao->fetch()) {
5424 /* if sales tax item*/
5425 if (in_array($dao->financial_account_id, $salesTaxFinancialAccount)) {
5426 $taxItems[$dao->price_field_value_id] = array(
5427 'financial_item_id' => $dao->id,
5428 'amount' => $dao->tax_amount,
5429 );
5430 }
5431 else {
5432 $ftIds[$dao->price_field_value_id] = $dao->id;
5433 }
5434 }
5435 return array($ftIds, $taxItems);
5436 }
5437
5438 /**
5439 * Create proportional entries in civicrm_entity_financial_trxn.
5440 *
5441 * @param array $entityParams
5442 *
5443 * @param array $lineItems
5444 *
5445 * @param array $ftIds
5446 *
5447 * @param array $taxItems
5448 *
5449 */
5450 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5451 $eftParams = array(
5452 'entity_table' => 'civicrm_financial_item',
5453 'financial_trxn_id' => $entityParams['trxn_id'],
5454 );
5455 foreach ($lineItems as $key => $value) {
5456 if ($value['qty'] == 0) {
5457 continue;
5458 }
5459 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5460 $entityParams['line_item_amount'] = $value['line_total'];
5461 self::createProportionalEntry($entityParams, $eftParams);
5462 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5463 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5464 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5465 self::createProportionalEntry($entityParams, $eftParams);
5466 }
5467 }
5468 }
5469
55df1211
AS
5470 /**
5471 * Load entities related to the contribution into $this->_relatedObjects.
5472 *
5473 * @param array $ids
5474 *
5475 * @throws \CRM_Core_Exception
5476 */
5477 protected function loadRelatedEntitiesByID($ids) {
5478 $entities = array(
5479 'contact' => 'CRM_Contact_BAO_Contact',
5480 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5481 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5482 'financialType' => 'CRM_Financial_BAO_FinancialType',
5483 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5484 );
5485 foreach ($entities as $entity => $bao) {
5486 if (!empty($ids[$entity])) {
5487 $this->_relatedObjects[$entity] = new $bao();
5488 $this->_relatedObjects[$entity]->id = $ids[$entity];
5489 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
5490 throw new CRM_Core_Exception($entity . ' could not be loaded');
5491 }
5492 }
5493 }
5494 }
5495
5496 /**
5497 * Should an email receipt be sent for this contribution when complete.
5498 *
5499 * @param array $input
5500 *
5501 * @return mixed
5502 */
5503 protected function isEmailReceipt($input) {
5504 if (isset($input['is_email_receipt'])) {
5505 return $input['is_email_receipt'];
5506 }
5507 if (!empty($this->_relatedObjects['contribution_page_id'])) {
5508 return $this->_relatedObjects['contribution_page_id']->is_email_receipt;
5509 }
5510 return TRUE;
5511 }
5512
7e2ec997
E
5513 /**
5514 * Function to replace contribution tokens.
5515 *
5516 * @param array $contributionIds
5517 *
5518 * @param string $subject
5519 *
5520 * @param array $subjectToken
5521 *
5522 * @param string $text
5523 *
5524 * @param string $html
5525 *
5526 * @param array $messageToken
5527 *
5528 * @param bool $escapeSmarty
5529 *
5530 * @return array
5531 */
5532 public static function replaceContributionTokens(
5533 $contributionIds,
5534 $subject,
5535 $subjectToken,
5536 $text,
5537 $html,
5538 $messageToken,
5539 $escapeSmarty
5540 ) {
5541 if (empty($contributionIds)) {
5542 return array();
5543 }
5544 $contributionDetails = array();
5545 foreach ($contributionIds as $id) {
5546 $result = civicrm_api3('Contribution', 'get', array('id' => $id));
5547 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5548 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5549 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5550 }
5551 return $contributionDetails;
5552 }
5553
5ce9cbe9 5554}