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