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