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