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