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