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