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