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