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