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