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