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