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