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