Merge pull request #18777 from civicrm/5.31
[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 = CRM_Core_DAO::executeQuery($sql);
2274 if ($dao->fetch()) {
2275 if (!empty($dao->membership_type_id)) {
2276 $membership->membership_type_id = $dao->membership_type_id;
2277 $membership->save();
2278 }
2279 }
2280 // else fall back to using current membership type
2281 // Figure out number of terms
2282 $numterms = 1;
2283 $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
2284 foreach ($lineitems as $lineitem) {
2285 if ($membership->membership_type_id == ($lineitem['membership_type_id'] ?? NULL)) {
2286 $numterms = $lineitem['membership_num_terms'] ?? NULL;
2287
2288 // in case membership_num_terms comes through as null or zero
2289 $numterms = $numterms >= 1 ? $numterms : 1;
2290 break;
2291 }
2292 }
2293
2294 // CRM-15735-to update the membership status as per the contribution receive date
2295 $joinDate = NULL;
2296 $oldStatus = $membership->status_id;
2297 if (!empty($params['receive_date'])) {
2298 $joinDate = $params['receive_date'];
2299 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
2300 $membership->end_date,
2301 $membership->join_date,
2302 $params['receive_date'],
2303 FALSE,
2304 $membership->membership_type_id,
2305 (array) $membership
2306 );
2307 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
2308 $membership->save();
2309 }
2310
2311 if ($currentMembership) {
2312 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
2313 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
2314 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
2315 }
2316 else {
2317 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
2318 }
2319
2320 //get the status for membership.
2321 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
2322 $dates['end_date'],
2323 $dates['join_date'],
2324 'now',
2325 TRUE,
2326 $membership->membership_type_id,
2327 (array) $membership
2328 );
2329
2330 $formattedParams = [
2331 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
2332 array_search('Current', $membershipStatuses)
2333 ),
2334 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
2335 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
2336 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
2337 ];
2338
2339 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
2340
2341 $membership->copyValues($formattedParams);
2342 $membership->save();
2343
2344 //updating the membership log
2345 $membershipLog = [];
2346 $membershipLog = $formattedParams;
2347 $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'] ?? NULL, $format);
2348 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
2349
2350 $membershipLog['start_date'] = $logStartDate;
2351 $membershipLog['membership_id'] = $membership->id;
2352 $membershipLog['modified_id'] = $membership->contact_id;
2353 $membershipLog['modified_date'] = date('Ymd');
2354 $membershipLog['membership_type_id'] = $membership->membership_type_id;
2355
2356 CRM_Member_BAO_MembershipLog::add($membershipLog);
2357
2358 //update related Memberships.
2359 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
2360
2361 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
2362 $scheduledActivityID = CRM_Utils_Array::value('id',
2363 civicrm_api3('Activity', 'Get',
2364 [
2365 'source_record_id' => $membership->id,
2366 'activity_type_id' => $activityType,
2367 'status_id' => 'Scheduled',
2368 'options' => [
2369 'limit' => 1,
2370 'sort' => 'id DESC',
2371 ],
2372 ]
2373 )
2374 );
2375 // 1. Update Schedule Membership Signup/Renewal activity to completed on successful payment of pending membership
2376 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
2377 if ($scheduledActivityID) {
2378 CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $membership->contact_id, ['id' => $scheduledActivityID]);
2379 break;
2380 }
2381 }
2382
2383 // track membership status change if any
2384 if (!empty($oldStatus) && $membership->status_id != $oldStatus) {
2385 $allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
2386 CRM_Activity_BAO_Activity::addActivity($membership,
2387 'Change Membership Status',
2388 NULL,
2389 [
2390 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
2391 'source_contact_id' => $membershipLog['modified_id'],
2392 'priority_id' => 'Normal',
2393 ]
2394 );
2395 }
2396
2397 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
2398 if ($processContributionObject) {
2399 $processContribution = TRUE;
2400 }
2401
2402 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
2403 }
2404 }
2405 }
2406
2407 if ($participant) {
2408 $updatedStatusId = array_search('Registered', $participantStatuses);
2409 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
2410
2411 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
2412 if ($processContributionObject) {
2413 $processContribution = TRUE;
2414 }
2415 }
2416
2417 if ($pledgePayment) {
2418 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
2419
2420 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
2421 if ($processContributionObject) {
2422 $processContribution = TRUE;
2423 }
2424 }
2425 }
2426
2427 // process contribution object.
2428 if ($processContribution) {
2429 $contributionParams = [];
2430 $fields = [
2431 'contact_id',
2432 'total_amount',
2433 'receive_date',
2434 'is_test',
2435 'campaign_id',
2436 'payment_instrument_id',
2437 'trxn_id',
2438 'invoice_id',
2439 'financial_type_id',
2440 'contribution_status_id',
2441 'non_deductible_amount',
2442 'receipt_date',
2443 'check_number',
2444 ];
2445 foreach ($fields as $field) {
2446 if (empty($params[$field])) {
2447 continue;
2448 }
2449 $contributionParams[$field] = $params[$field];
2450 }
2451
2452 $contributionParams['id'] = $contributionId;
2453 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams);
2454 }
2455
2456 return $updateResult;
2457 }
2458
2459 /**
2460 * Returns all contribution related object ids.
2461 *
2462 * @param $contributionId
2463 *
2464 * @return array
2465 */
2466 public static function getComponentDetails($contributionId) {
2467 $componentDetails = $pledgePayment = [];
2468 if (!$contributionId) {
2469 return $componentDetails;
2470 }
2471
2472 $query = "
2473 SELECT c.id as contribution_id,
2474 c.contact_id as contact_id,
2475 c.contribution_recur_id,
2476 mp.membership_id as membership_id,
2477 m.membership_type_id as membership_type_id,
2478 pp.participant_id as participant_id,
2479 p.event_id as event_id,
2480 pgp.id as pledge_payment_id
2481 FROM civicrm_contribution c
2482 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
2483 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
2484 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
2485 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
2486 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
2487 WHERE c.id = $contributionId";
2488
2489 $dao = CRM_Core_DAO::executeQuery($query);
2490 $componentDetails = [];
2491
2492 while ($dao->fetch()) {
2493 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
2494 $componentDetails['contact_id'] = $dao->contact_id;
2495 if ($dao->event_id) {
2496 $componentDetails['event'] = $dao->event_id;
2497 }
2498 if ($dao->participant_id) {
2499 $componentDetails['participant'] = $dao->participant_id;
2500 }
2501 if ($dao->membership_id) {
2502 if (!isset($componentDetails['membership'])) {
2503 $componentDetails['membership'] = $componentDetails['membership_type'] = [];
2504 }
2505 $componentDetails['membership'][] = $dao->membership_id;
2506 $componentDetails['membership_type'][] = $dao->membership_type_id;
2507 }
2508 if ($dao->pledge_payment_id) {
2509 $pledgePayment[] = $dao->pledge_payment_id;
2510 }
2511 if ($dao->contribution_recur_id) {
2512 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
2513 }
2514 }
2515
2516 if ($pledgePayment) {
2517 $componentDetails['pledge_payment'] = $pledgePayment;
2518 }
2519
2520 return $componentDetails;
2521 }
2522
2523 /**
2524 * @param int $contactId
2525 * @param bool $includeSoftCredit
2526 *
2527 * @return null|string
2528 */
2529 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
2530 if (!$contactId) {
2531 return 0;
2532 }
2533 $financialTypes = CRM_Financial_BAO_FinancialType::getAllAvailableFinancialTypes();
2534 $additionalWhere = " AND contribution.financial_type_id IN (0)";
2535 $liWhere = " AND i.financial_type_id IN (0)";
2536 if (!empty($financialTypes)) {
2537 $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
2538 $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")";
2539 }
2540 $contactContributionsSQL = "
2541 SELECT contribution.id AS id
2542 FROM civicrm_contribution contribution
2543 LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere
2544 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId}
2545 $additionalWhere
2546 AND i.id IS NULL";
2547
2548 $contactSoftCreditContributionsSQL = "
2549 SELECT contribution.id
2550 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
2551 ON ( contribution.id = softContribution.contribution_id )
2552 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
2553 $query = "SELECT count( x.id ) count FROM ( ";
2554 $query .= $contactContributionsSQL;
2555
2556 if ($includeSoftCredit) {
2557 $query .= " UNION ";
2558 $query .= $contactSoftCreditContributionsSQL;
2559 }
2560
2561 $query .= ") x";
2562
2563 return CRM_Core_DAO::singleValueQuery($query);
2564 }
2565
2566 /**
2567 * Repeat a transaction as part of a recurring series.
2568 *
2569 * The ideal flow is
2570 * 1) Processor calls contribution.repeattransaction with contribution_status_id = Pending
2571 * 2) The repeattransaction loads the 'template contribution' and calls a hook to allow altering of it .
2572 * 3) Repeat transaction calls order.create to create the pending contribution with correct line items
2573 * and associated entities.
2574 * 4) The calling code calls Payment.create which in turn calls CompleteOrder (if completing)
2575 * which updates the various entities and sends appropriate emails.
2576 *
2577 * Gaps in the above (@todo)
2578 * 1) many processors still call repeattransaction with contribution_status_id = Completed
2579 * 2) repeattransaction code is current munged into completeTransaction code for historical bad coding reasons
2580 * 3) Repeat transaction duplicates rather than calls Order.create
2581 * 4) Use of payment.create still limited - completetransaction is more common.
2582 * 5) the template transaction is tricky - historically we used the first contribution
2583 * linked to a recurring contribution. More recently that was changed to be the most recent.
2584 * Ideally it would be an actual template - not a contribution used as a template which
2585 * would give more appropriate flexibility. Note line_items have an entity so that table
2586 * could be used for the line item template - the difficulty is the custom fields...
2587 * 6) the determination of the membership to be linked is tricksy. The prioritised method is
2588 * to load the membership(s) referred to via line items in the template transactions. Any other
2589 * method is likely to lead to incorrect line items & related entities being created (as the line_item
2590 * link is a required part of 'correct data'). However there are 3 other methods to determine it
2591 * - membership_payment record
2592 * - civicrm_membership.contribution_recur_id
2593 * - input override.
2594 * Passing in an input override WILL ensure the membership is extended to prevent regressions
2595 * of historical processors since this has been handled 'forever' - specifically for paypal.
2596 * albeit by an even nastier mechanism than the current input override.
2597 * The count is out on how correct related entities wind up in this case.
2598 *
2599 * @param CRM_Contribute_BAO_Contribution $contribution
2600 * @param array $input
2601 * @param array $contributionParams
2602 *
2603 * @return bool|array
2604 * @throws CiviCRM_API3_Exception
2605 */
2606 protected static function repeatTransaction(&$contribution, $input, $contributionParams) {
2607 if (!empty($contribution->id)) {
2608 return FALSE;
2609 }
2610 if (empty($contribution->id)) {
2611 // Unclear why this would only be set for repeats.
2612 if (!empty($input['amount'])) {
2613 $contribution->total_amount = $contributionParams['total_amount'] = $input['amount'];
2614 }
2615
2616 if (!empty($contributionParams['contribution_recur_id'])) {
2617 $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', [
2618 'id' => $contributionParams['contribution_recur_id'],
2619 ]);
2620 if (!empty($recurringContribution['campaign_id'])) {
2621 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2622 $contributionParams['campaign_id'] = $recurringContribution['campaign_id'];
2623 }
2624 if (!empty($recurringContribution['financial_type_id'])) {
2625 // CRM-17718 the campaign id on the contribution recur record should get precedence.
2626 $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id'];
2627 }
2628 }
2629 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution(
2630 $contributionParams['contribution_recur_id'],
2631 array_intersect_key($contributionParams, [
2632 'total_amount' => TRUE,
2633 'financial_type_id' => TRUE,
2634 ])
2635 );
2636 $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item'];
2637 $contributionParams['status_id'] = 'Pending';
2638
2639 if (isset($contributionParams['financial_type_id']) && count($input['line_item']) === 1) {
2640 // We permit the financial type to be overridden for single line items.
2641 // More comments on this are in getTemplateTransaction.
2642 $contribution->financial_type_id = $contributionParams['financial_type_id'];
2643 }
2644 else {
2645 $contributionParams['financial_type_id'] = $templateContribution['financial_type_id'];
2646 }
2647 foreach (['contact_id', 'currency', 'source'] as $fieldName) {
2648 $contributionParams[$fieldName] = $templateContribution[$fieldName];
2649 }
2650
2651 $contributionParams['source'] = $contributionParams['source'] ?: ts('Recurring contribution');
2652
2653 //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments
2654 //do not create CC or BCC emails or profile notifications.
2655 //The if is just to be safe. Not sure if we can ever arrive with this unset
2656 // but per CRM-19478 it seems it can be 'null'
2657 if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
2658 $contributionParams['contribution_page_id'] = $contribution->contribution_page_id;
2659 }
2660 if (!empty($contribution->tax_amount)) {
2661 $contributionParams['tax_amount'] = $contribution->tax_amount;
2662 }
2663
2664 $createContribution = civicrm_api3('Contribution', 'create', $contributionParams);
2665 $contribution->id = $createContribution['id'];
2666 $contribution->copyCustomFields($templateContribution['id'], $contribution->id);
2667 self::handleMembershipIDOverride($contribution->id, $input);
2668 return $createContribution;
2669 }
2670 }
2671
2672 /**
2673 * Get individual id for onbehalf contribution.
2674 *
2675 * @param int $contributionId
2676 * Contribution id.
2677 * @param int $contributorId
2678 * Contributor id.
2679 *
2680 * @return array
2681 * containing organization id and individual id
2682 */
2683 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
2684
2685 $ids = [];
2686
2687 if (!$contributionId) {
2688 return $ids;
2689 }
2690
2691 // fetch contributor id if null
2692 if (!$contributorId) {
2693 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
2694 $contributionId, 'contact_id'
2695 );
2696 }
2697
2698 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
2699 $activityTypeId = array_search('Contribution', $activityTypeIds);
2700
2701 if ($activityTypeId && $contributorId) {
2702 $activityQuery = "
2703 SELECT civicrm_activity_contact.contact_id
2704 FROM civicrm_activity_contact
2705 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
2706 WHERE civicrm_activity.activity_type_id = %1
2707 AND civicrm_activity.source_record_id = %2
2708 AND civicrm_activity_contact.record_type_id = %3
2709 ";
2710
2711 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2712 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2713
2714 $params = [
2715 1 => [$activityTypeId, 'Integer'],
2716 2 => [$contributionId, 'Integer'],
2717 3 => [$sourceID, 'Integer'],
2718 ];
2719
2720 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
2721
2722 // for on behalf contribution source is individual and contributor is organization
2723 if ($sourceContactId && $sourceContactId != $contributorId) {
2724 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
2725 // get rel type id for employee of relation
2726 foreach ($relationshipTypeIds as $id => $typeVals) {
2727 if ($typeVals['name_a_b'] == 'Employee of') {
2728 $relationshipTypeId = $id;
2729 break;
2730 }
2731 }
2732
2733 $rel = new CRM_Contact_DAO_Relationship();
2734 $rel->relationship_type_id = $relationshipTypeId;
2735 $rel->contact_id_a = $sourceContactId;
2736 $rel->contact_id_b = $contributorId;
2737 if ($rel->find(TRUE)) {
2738 $ids['individual_id'] = $rel->contact_id_a;
2739 $ids['organization_id'] = $rel->contact_id_b;
2740 }
2741 }
2742 }
2743
2744 return $ids;
2745 }
2746
2747 /**
2748 * @return array
2749 */
2750 public static function getContributionDates() {
2751 $config = CRM_Core_Config::singleton();
2752 $currentMonth = date('m');
2753 $currentDay = date('d');
2754 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
2755 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
2756 (int ) $config->fiscalYearStart['d'] > $currentDay
2757 )
2758 ) {
2759 $year = date('Y') - 1;
2760 }
2761 else {
2762 $year = date('Y');
2763 }
2764 $year = ['Y' => $year];
2765 $yearDate = $config->fiscalYearStart;
2766 $yearDate = array_merge($year, $yearDate);
2767 $yearDate = CRM_Utils_Date::format($yearDate);
2768
2769 $monthDate = date('Ym') . '01';
2770
2771 $now = date('Ymd');
2772
2773 return [
2774 'now' => $now,
2775 'yearDate' => $yearDate,
2776 'monthDate' => $monthDate,
2777 ];
2778 }
2779
2780 /**
2781 * Load objects relations to contribution object.
2782 * Objects are stored in the $_relatedObjects property
2783 * In the first instance we are just moving functionality from BASEIpn -
2784 *
2785 * @see http://issues.civicrm.org/jira/browse/CRM-9996
2786 *
2787 * Note that the unit test for the BaseIPN class tests this function
2788 *
2789 * @param array $input
2790 * Input as delivered from Payment Processor.
2791 * @param array $ids
2792 * Ids as Loaded by Payment Processor.
2793 * @param bool $loadAll
2794 * Load all related objects - even where id not passed in? (allows API to call this).
2795 *
2796 * @return bool
2797 * @throws CRM_Core_Exception
2798 */
2799 public function loadRelatedObjects($input, &$ids, $loadAll = FALSE) {
2800 // @todo deprecate this function - the steps should be
2801 // 1) add additional functions like 'getRelatedMemberships'
2802 // 2) switch all calls that refer to ->_relatedObjects to
2803 // using the helper functions
2804 // 3) make ->_relatedObjects noisy in some way (deprecation won't work for properties - hmm
2805 // 4) make ->_relatedObjects protected
2806 // 5) hone up the individual functions to not use rely on this having been called
2807 // 6) deprecate like mad
2808 if ($loadAll) {
2809 $ids = array_merge($this->getComponentDetails($this->id), $ids);
2810 if (empty($ids['contact']) && isset($this->contact_id)) {
2811 $ids['contact'] = $this->contact_id;
2812 }
2813 }
2814 if (empty($this->_component)) {
2815 if (!empty($ids['event'])) {
2816 $this->_component = 'event';
2817 }
2818 else {
2819 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2820 }
2821 }
2822
2823 // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious
2824 // refactoring than anything else, and has unit test coverage.
2825 if (empty($this->financial_type_id)) {
2826 $this->find(TRUE);
2827 }
2828
2829 $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value(
2830 'paymentProcessor',
2831 $ids
2832 ));
2833
2834 if (!isset($input['payment_processor_id']) && !$paymentProcessorID && $this->contribution_page_id) {
2835 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2836 $this->contribution_page_id,
2837 'payment_processor'
2838 );
2839 if ($paymentProcessorID) {
2840 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage;
2841 }
2842 }
2843
2844 $ids['contributionType'] = $this->financial_type_id;
2845 $ids['financialType'] = $this->financial_type_id;
2846 if ($this->contribution_page_id) {
2847 $ids['contributionPage'] = $this->contribution_page_id;
2848 }
2849
2850 $this->loadRelatedEntitiesByID($ids);
2851
2852 if (!empty($ids['contributionRecur']) && !$paymentProcessorID) {
2853 $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id;
2854 }
2855
2856 if (!empty($ids['pledge_payment'])) {
2857 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2858 if (empty($paymentID)) {
2859 continue;
2860 }
2861 $payment = new CRM_Pledge_BAO_PledgePayment();
2862 $payment->id = $paymentID;
2863 if (!$payment->find(TRUE)) {
2864 throw new CRM_Core_Exception("Could not find pledge payment record: " . $paymentID);
2865 }
2866 $this->_relatedObjects['pledge_payment'][] = $payment;
2867 }
2868 }
2869
2870 // These are probably no longer accessed from anywhere
2871 // @todo remove this line, after ensuring not used.
2872 $ids = $this->loadRelatedMembershipObjects($ids);
2873
2874 if ($this->_component != 'contribute') {
2875 // we are in event mode
2876 // make sure event exists and is valid
2877 $event = new CRM_Event_BAO_Event();
2878 $event->id = $ids['event'];
2879 if ($ids['event'] &&
2880 !$event->find(TRUE)
2881 ) {
2882 throw new CRM_Core_Exception("Could not find event: " . $ids['event']);
2883 }
2884
2885 $this->_relatedObjects['event'] = &$event;
2886
2887 $participant = new CRM_Event_BAO_Participant();
2888 $participant->id = $ids['participant'];
2889 if ($ids['participant'] &&
2890 !$participant->find(TRUE)
2891 ) {
2892 throw new CRM_Core_Exception("Could not find participant: " . $ids['participant']);
2893 }
2894 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2895
2896 $this->_relatedObjects['participant'] = &$participant;
2897
2898 // get the payment processor id from event - this is inaccurate see CRM-16923
2899 // in future we should look at throwing an exception here rather than an dubious guess.
2900 if (!$paymentProcessorID) {
2901 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2902 if ($paymentProcessorID) {
2903 $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent;
2904 }
2905 }
2906 }
2907
2908 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id);
2909 if (!empty($relatedContact['individual_id'])) {
2910 $ids['related_contact'] = $relatedContact['individual_id'];
2911 }
2912
2913 if ($paymentProcessorID) {
2914 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2915 $this->is_test ? 'test' : 'live'
2916 );
2917 $ids['paymentProcessor'] = $paymentProcessorID;
2918 $this->_relatedObjects['paymentProcessor'] = $paymentProcessor;
2919 }
2920
2921 // Add contribution id to $ids. CRM-20401
2922 $ids['contribution'] = $this->id;
2923 return TRUE;
2924 }
2925
2926 /**
2927 * Create array of message information - ie. return html version, txt version, to field
2928 *
2929 * @param array $input
2930 * Incoming information.
2931 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2932 * just check presence of recur object but maintaining legacy approach
2933 * to be careful)
2934 * @param array $ids
2935 * IDs of related objects.
2936 * @param array $values
2937 * Any values that may have already been compiled by calling process.
2938 * This is augmented by values 'gathered' by gatherMessageValues
2939 * @param bool $returnMessageText
2940 * Distinguishes between whether to send message or return.
2941 * message text. We are working towards this function ALWAYS returning message text & calling
2942 * function doing emails / pdfs with it
2943 *
2944 * @return array
2945 * messages
2946 * @throws Exception
2947 */
2948 public function composeMessageArray(&$input, &$ids, &$values, $returnMessageText = TRUE) {
2949 $this->loadRelatedObjects($input, $ids);
2950
2951 if (empty($this->_component)) {
2952 $this->_component = $input['component'] ?? NULL;
2953 }
2954
2955 //not really sure what params might be passed in but lets merge em into values
2956 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2957 $values['is_email_receipt'] = !$returnMessageText;
2958 if (!empty($input['receipt_date'])) {
2959 $values['receipt_date'] = $input['receipt_date'];
2960 }
2961
2962 $template = $this->_assignMessageVariablesToTemplate($values, $input, $returnMessageText);
2963 //what does recur 'mean here - to do with payment processor return functionality but
2964 // what is the importance
2965 if (!empty($this->contribution_recur_id) && !empty($this->_relatedObjects['paymentProcessor'])) {
2966 $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']);
2967
2968 $entityID = $entity = NULL;
2969 if (isset($ids['contribution'])) {
2970 $entity = 'contribution';
2971 $entityID = $ids['contribution'];
2972 }
2973 if (!empty($ids['membership'])) {
2974 //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
2975 // 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
2976 // line having loaded an array
2977 $ids['membership'] = (array) $ids['membership'];
2978 $entity = 'membership';
2979 $entityID = $ids['membership'][0];
2980 }
2981
2982 $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel'));
2983 $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing'));
2984 $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update'));
2985
2986 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2987 //direct mode showing billing block, so use directIPN for temporary
2988 $template->assign('contributeMode', 'directIPN');
2989 }
2990 }
2991 // todo remove strtolower - check consistency
2992 if (strtolower($this->_component) == 'event') {
2993 $eventParams = ['id' => $this->_relatedObjects['participant']->event_id];
2994 $values['event'] = [];
2995
2996 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2997
2998 //get location details
2999 $locationParams = [
3000 'entity_id' => $this->_relatedObjects['participant']->event_id,
3001 'entity_table' => 'civicrm_event',
3002 ];
3003 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
3004
3005 $ufJoinParams = [
3006 'entity_table' => 'civicrm_event',
3007 'entity_id' => $ids['event'],
3008 'module' => 'CiviEvent',
3009 ];
3010
3011 list($custom_pre_id,
3012 $custom_post_ids
3013 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
3014
3015 $values['custom_pre_id'] = $custom_pre_id;
3016 $values['custom_post_id'] = $custom_post_ids;
3017 //for tasks 'Change Participant Status' and 'Update multiple Contributions' case
3018 //and cases involving status updation through ipn
3019 // whatever that means!
3020 // total_amount appears to be the preferred input param & it is unclear why we support amount here
3021 // perhaps we should throw an e-notice if amount is set & force total_amount?
3022 if (!empty($input['amount'])) {
3023 $values['totalAmount'] = $input['amount'];
3024 }
3025 // @todo set this in is_email_receipt, based on $this->_relatedObjects.
3026 if ($values['event']['is_email_confirm']) {
3027 $values['is_email_receipt'] = 1;
3028 }
3029
3030 if (!empty($ids['contribution'])) {
3031 $values['contributionId'] = $ids['contribution'];
3032 }
3033
3034 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
3035 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
3036 );
3037 }
3038 else {
3039 $values['contribution_id'] = $this->id;
3040 if (!empty($ids['related_contact'])) {
3041 $values['related_contact'] = $ids['related_contact'];
3042 if (isset($ids['onbehalf_dupe_alert'])) {
3043 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
3044 }
3045 $entityBlock = [
3046 'contact_id' => $ids['contact'],
3047 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
3048 'Home', 'id', 'name'
3049 ),
3050 ];
3051 $address = CRM_Core_BAO_Address::getValues($entityBlock);
3052 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
3053 }
3054 $isTest = FALSE;
3055 if ($this->is_test) {
3056 $isTest = TRUE;
3057 }
3058 if (!empty($this->_relatedObjects['membership'])) {
3059 foreach ($this->_relatedObjects['membership'] as $membership) {
3060 if ($membership->id) {
3061 $values['membership_id'] = $membership->id;
3062 $values['isMembership'] = TRUE;
3063 $values['membership_assign'] = TRUE;
3064
3065 // need to set the membership values here
3066 $template->assign('membership_name',
3067 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
3068 );
3069 $template->assign('mem_start_date', $membership->start_date);
3070 $template->assign('mem_join_date', $membership->join_date);
3071 $template->assign('mem_end_date', $membership->end_date);
3072 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
3073 $template->assign('mem_status', $membership_status);
3074 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
3075 $values['is_pay_later'] = 1;
3076 }
3077 // Pass amount to floatval as string '0.00' is considered a
3078 // valid amount and includes Fee section in the mail.
3079 if (isset($values['amount'])) {
3080 $values['amount'] = floatval($values['amount']);
3081 }
3082
3083 if (!empty($this->contribution_recur_id) && $paymentObject) {
3084 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel');
3085 $template->assign('cancelSubscriptionUrl', $url);
3086 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
3087 $template->assign('updateSubscriptionBillingUrl', $url);
3088 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
3089 $template->assign('updateSubscriptionUrl', $url);
3090 }
3091
3092 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3093
3094 return $result;
3095 // otherwise if its about sending emails, continue sending without return, as we
3096 // don't want to exit the loop.
3097 }
3098 }
3099 }
3100 else {
3101 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
3102 }
3103 }
3104 }
3105
3106 /**
3107 * Gather values for contribution mail - this function has been created
3108 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
3109 * Values related to the contribution in question are gathered
3110 *
3111 * @param array $input
3112 * Input into function (probably from payment processor).
3113 * @param array $values
3114 * @param array $ids
3115 * The set of ids related to the input.
3116 *
3117 * @return array
3118 * @throws \CRM_Core_Exception
3119 */
3120 public function _gatherMessageValues($input, &$values, $ids = []) {
3121 // set display address of contributor
3122 $values['billingName'] = '';
3123 if ($this->address_id) {
3124 $addressDetails = CRM_Core_BAO_Address::getValues(['id' => $this->address_id], FALSE, 'id');
3125 $addressDetails = reset($addressDetails);
3126 $values['billingName'] = $addressDetails['name'] ?? '';
3127 }
3128 // Else we assign the billing address of the contribution contact.
3129 else {
3130 $addressDetails = (array) CRM_Core_BAO_Address::getValues(['contact_id' => $this->contact_id, 'is_billing' => 1]);
3131 $addressDetails = reset($addressDetails);
3132 }
3133 $values['address'] = $addressDetails['display'] ?? '';
3134
3135 if ($this->_component === 'contribute') {
3136 //get soft contributions
3137 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE);
3138 if (!empty($softContributions)) {
3139 // For pcp soft credit, there is no 'soft_credit' member it comes
3140 // back in different array members, but shortly after returning from
3141 // this function it calls _assignMessageVariablesToTemplate which does
3142 // its own lookup of any pcp soft credit, so we can skip it here.
3143 $values['softContributions'] = $softContributions['soft_credit'] ?? NULL;
3144 }
3145 if (isset($this->contribution_page_id)) {
3146 // This is a call we want to use less, in favour of loading related objects.
3147 $values = $this->addContributionPageValuesToValuesHeavyHandedly($values);
3148 if ($this->contribution_page_id) {
3149 // This is precautionary as there are some legacy flows, but it should really be
3150 // loaded by now.
3151 if (!isset($this->_relatedObjects['contributionPage'])) {
3152 $this->loadRelatedEntitiesByID(['contributionPage' => $this->contribution_page_id]);
3153 }
3154 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($values);
3155 }
3156 }
3157 // no contribution page -probably back office
3158 else {
3159 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
3160 $values['title'] = 'Contribution';
3161 }
3162 // set lineItem for contribution
3163 if ($this->id) {
3164 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id);
3165 if (!empty($lineItems)) {
3166 $firstLineItem = reset($lineItems);
3167 $priceSet = [];
3168 if (!empty($firstLineItem['price_set_id'])) {
3169 $priceSet = civicrm_api3('PriceSet', 'getsingle', [
3170 'id' => $firstLineItem['price_set_id'],
3171 'return' => 'is_quick_config, id',
3172 ]);
3173 $values['priceSetID'] = $priceSet['id'];
3174 }
3175 foreach ($lineItems as &$eachItem) {
3176 if (isset($this->_relatedObjects['membership'])
3177 && is_array($this->_relatedObjects['membership'])
3178 && array_key_exists($eachItem['entity_id'] . '_' . $eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
3179 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->join_date);
3180 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->start_date);
3181 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['entity_id'] . '_' . $eachItem['membership_type_id']]->end_date);
3182 }
3183 // This is actually used in conjunction with is_quick_config in the template & we should deprecate it.
3184 // However, that does create upgrade pain so would be better to be phased in.
3185 $values['useForMember'] = empty($priceSet['is_quick_config']);
3186 }
3187 $values['lineItem'][0] = $lineItems;
3188 }
3189 }
3190
3191 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
3192 $this->id,
3193 $this->contact_id
3194 );
3195 // if this is onbehalf of contribution then set related contact
3196 if (!empty($relatedContact['individual_id'])) {
3197 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
3198 }
3199 }
3200 else {
3201 $values = array_merge($values, $this->loadEventMessageTemplateParams((int) $ids['event'], (int) $this->_relatedObjects['participant']->id, $this->id));
3202 }
3203
3204 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $this->id);
3205
3206 $customGroup = [];
3207 foreach ($groupTree as $key => $group) {
3208 if ($key === 'info') {
3209 continue;
3210 }
3211
3212 foreach ($group['fields'] as $k => $customField) {
3213 $groupLabel = $group['title'];
3214 if (!empty($customField['customValue'])) {
3215 foreach ($customField['customValue'] as $customFieldValues) {
3216 $customGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
3217 }
3218 }
3219 }
3220 }
3221 $values['customGroup'] = $customGroup;
3222
3223 $values['is_pay_later'] = $this->is_pay_later;
3224
3225 return $values;
3226 }
3227
3228 /**
3229 * Assign message variables to template but try to break the habit.
3230 *
3231 * In order to get away from leaky variables it is better to ensure variables are set in values and assign them
3232 * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing
3233 * multiple recurring payments for processors like IATS that use tokens.
3234 *
3235 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
3236 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
3237 * Note we send directly from this function in some cases because it is only partly refactored.
3238 *
3239 * Don't call this function directly as the signature will change.
3240 *
3241 * @param $values
3242 * @param $input
3243 * @param bool $returnMessageText
3244 *
3245 * @return mixed
3246 */
3247 public function _assignMessageVariablesToTemplate(&$values, $input, $returnMessageText = TRUE) {
3248 // @todo - this should have a better separation of concerns - ie.
3249 // gatherMessageValues should build an array of values to be assigned to the template
3250 // and this function should assign them (assigning null if not set).
3251 // the way the pcpParams & honor Params section works is a baby-step towards this.
3252 $template = CRM_Core_Smarty::singleton();
3253 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
3254 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
3255 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
3256 $template->assign('billingName', $values['billingName']);
3257
3258 // For some unit tests contribution cannot contain paymentProcessor information
3259 $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode'];
3260 $template->assign('contributeMode', CRM_Core_SelectValues::contributeMode()[$billingMode] ?? NULL);
3261
3262 //assign honor information to receipt message
3263 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
3264
3265 $honorParams = [
3266 'soft_credit_type' => NULL,
3267 'honor_block_is_active' => NULL,
3268 ];
3269 if (isset($softRecord['soft_credit'])) {
3270 //if id of contribution page is present
3271 if (!empty($values['id'])) {
3272 $values['honor'] = [
3273 'honor_profile_values' => [],
3274 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
3275 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
3276 ];
3277
3278 $honorParams['soft_credit_type'] = $softRecord['soft_credit'][1]['soft_credit_type_label'];
3279 $honorParams['honor_block_is_active'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id');
3280 }
3281 else {
3282 //offline contribution
3283 $softCreditTypes = $softCredits = [];
3284 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
3285 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
3286 $softCredits[$key] = [
3287 'Name' => $softCredit['contact_name'],
3288 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
3289 ];
3290 }
3291 $template->assign('softCreditTypes', $softCreditTypes);
3292 $template->assign('softCredits', $softCredits);
3293 }
3294 }
3295
3296 $dao = new CRM_Contribute_DAO_ContributionProduct();
3297 $dao->contribution_id = $this->id;
3298 if ($dao->find(TRUE)) {
3299 $premiumId = $dao->product_id;
3300 $template->assign('option', $dao->product_option);
3301
3302 $productDAO = new CRM_Contribute_DAO_Product();
3303 $productDAO->id = $premiumId;
3304 $productDAO->find(TRUE);
3305 $template->assign('selectPremium', TRUE);
3306 $template->assign('product_name', $productDAO->name);
3307 $template->assign('price', $productDAO->price);
3308 $template->assign('sku', $productDAO->sku);
3309 }
3310 $template->assign('title', $values['title'] ?? NULL);
3311 $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
3312 if (!$values['amount'] && isset($this->total_amount)) {
3313 $values['amount'] = $this->total_amount;
3314 }
3315
3316 $pcpParams = [
3317 'pcpBlock' => NULL,
3318 'pcp_display_in_roll' => NULL,
3319 'pcp_roll_nickname' => NULL,
3320 'pcp_personal_note' => NULL,
3321 'title' => NULL,
3322 ];
3323
3324 if (strtolower($this->_component) == 'contribute') {
3325 //PCP Info
3326 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
3327 $softDAO->contribution_id = $this->id;
3328 if ($softDAO->find(TRUE)) {
3329 $pcpParams['pcpBlock'] = TRUE;
3330 $pcpParams['pcp_display_in_roll'] = $softDAO->pcp_display_in_roll;
3331 $pcpParams['pcp_roll_nickname'] = $softDAO->pcp_roll_nickname;
3332 $pcpParams['pcp_personal_note'] = $softDAO->pcp_personal_note;
3333
3334 //assign the pcp page title for email subject
3335 $pcpDAO = new CRM_PCP_DAO_PCP();
3336 $pcpDAO->id = $softDAO->pcp_id;
3337 if ($pcpDAO->find(TRUE)) {
3338 $pcpParams['title'] = $pcpDAO->title;
3339 }
3340 }
3341 }
3342 foreach (array_merge($honorParams, $pcpParams) as $templateKey => $templateValue) {
3343 $template->assign($templateKey, $templateValue);
3344 }
3345
3346 if ($this->financial_type_id) {
3347 $values['financial_type_id'] = $this->financial_type_id;
3348 }
3349
3350 $template->assign('trxn_id', $this->trxn_id);
3351 $template->assign('receive_date',
3352 CRM_Utils_Date::processDate($this->receive_date)
3353 );
3354 $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date);
3355 $template->assign('action', $this->is_test ? 1024 : 1);
3356 $template->assign('receipt_text', $values['receipt_text'] ?? NULL);
3357 $template->assign('is_monetary', 1);
3358 $template->assign('is_recur', !empty($this->contribution_recur_id));
3359 $template->assign('currency', $this->currency);
3360 $template->assign('address', CRM_Utils_Address::format($input));
3361 if (!empty($values['customGroup'])) {
3362 $template->assign('customGroup', $values['customGroup']);
3363 }
3364 if (!empty($values['softContributions'])) {
3365 $template->assign('softContributions', $values['softContributions']);
3366 }
3367 if ($this->_component == 'event') {
3368 $template->assign('title', $values['event']['title']);
3369 $participantRoles = CRM_Event_PseudoConstant::participantRole();
3370 $viewRoles = [];
3371 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
3372 $viewRoles[] = $participantRoles[$v];
3373 }
3374 $values['event']['participant_role'] = implode(', ', $viewRoles);
3375 $template->assign('event', $values['event']);
3376 $template->assign('participant', $values['participant']);
3377 $template->assign('location', $values['location']);
3378 $template->assign('customPre', $values['custom_pre_id']);
3379 $template->assign('customPost', $values['custom_post_id']);
3380
3381 $isTest = FALSE;
3382 if ($this->_relatedObjects['participant']->is_test) {
3383 $isTest = TRUE;
3384 }
3385
3386 $values['params'] = [];
3387 //to get email of primary participant.
3388 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
3389 $primaryAmount[] = [
3390 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
3391 'amount' => $this->_relatedObjects['participant']->fee_amount,
3392 ];
3393 //build an array of cId/pId of participants
3394 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
3395 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
3396 //send receipt to additional participant if exists
3397 if (count($additionalIDs)) {
3398 $template->assign('isPrimary', 0);
3399 $template->assign('customProfile', NULL);
3400 //set additionalParticipant true
3401 $values['params']['additionalParticipant'] = TRUE;
3402 foreach ($additionalIDs as $pId => $cId) {
3403 $amount = [];
3404 //to change the status pending to completed
3405 $additional = new CRM_Event_DAO_Participant();
3406 $additional->id = $pId;
3407 $additional->contact_id = $cId;
3408 $additional->find(TRUE);
3409 $additional->register_date = $this->_relatedObjects['participant']->register_date;
3410 $additional->status_id = 1;
3411 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
3412 //if additional participant dont have email
3413 //use display name.
3414 if (!$additionalParticipantInfo) {
3415 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
3416 }
3417 $amount[0] = [
3418 'label' => $additional->fee_level,
3419 'amount' => $additional->fee_amount,
3420 ];
3421 $primaryAmount[] = [
3422 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
3423 'amount' => $additional->fee_amount,
3424 ];
3425 $additional->save();
3426 $template->assign('amount', $amount);
3427 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
3428 }
3429 }
3430
3431 //build an array of custom profile and assigning it to template
3432 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
3433
3434 if (count($customProfile)) {
3435 $template->assign('customProfile', $customProfile);
3436 }
3437
3438 // for primary contact
3439 $values['params']['additionalParticipant'] = FALSE;
3440 $template->assign('isPrimary', 1);
3441 $template->assign('amount', $primaryAmount);
3442 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
3443 if ($this->payment_instrument_id) {
3444 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
3445 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
3446 }
3447 // carry paylater, since we did not created billing,
3448 // so need to pull email from primary location, CRM-4395
3449 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
3450 }
3451 return $template;
3452 }
3453
3454 /**
3455 * Check whether payment processor supports
3456 * cancellation of contribution subscription
3457 *
3458 * @param int $contributionId
3459 * Contribution id.
3460 *
3461 * @param bool $isNotCancelled
3462 *
3463 * @return bool
3464 */
3465 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
3466 $cacheKeyString = "$contributionId";
3467 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
3468
3469 static $supportsCancel = [];
3470
3471 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
3472 $supportsCancel[$cacheKeyString] = FALSE;
3473 $isCancelled = FALSE;
3474
3475 if ($isNotCancelled) {
3476 $isCancelled = self::isSubscriptionCancelled($contributionId);
3477 }
3478
3479 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
3480 if (!empty($paymentObject)) {
3481 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
3482 }
3483 }
3484 return $supportsCancel[$cacheKeyString];
3485 }
3486
3487 /**
3488 * Check whether subscription is already cancelled.
3489 *
3490 * @param int $contributionId
3491 * Contribution id.
3492 *
3493 * @return string
3494 * contribution status
3495 */
3496 public static function isSubscriptionCancelled($contributionId) {
3497 $sql = "
3498 SELECT cr.contribution_status_id
3499 FROM civicrm_contribution_recur cr
3500 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
3501 WHERE con.id = %1 LIMIT 1";
3502 $params = [1 => [$contributionId, 'Integer']];
3503 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
3504 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name');
3505 if ($status == 'Cancelled') {
3506 return TRUE;
3507 }
3508 return FALSE;
3509 }
3510
3511 /**
3512 * Create all financial accounts entry.
3513 *
3514 * @param array $params
3515 * Contribution object, line item array and params for trxn.
3516 *
3517 *
3518 * @param array $financialTrxnValues
3519 *
3520 * @return null|\CRM_Core_BAO_FinancialTrxn
3521 */
3522 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
3523 $skipRecords = $update = $return = $isRelatedId = FALSE;
3524 $isUpdate = !empty($params['prevContribution']);
3525
3526 $additionalParticipantId = [];
3527 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3528 $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']];
3529
3530 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
3531 $entityId = $params['participant_id'];
3532 $entityTable = 'civicrm_participant';
3533 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
3534 }
3535 elseif (!empty($params['membership_id'])) {
3536 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
3537 // are created off one contribution should be handled elsewhere
3538 $entityId = $params['membership_id'];
3539 $entityTable = 'civicrm_membership';
3540 }
3541 else {
3542 $entityId = $params['contribution']->id;
3543 $entityTable = 'civicrm_contribution';
3544 }
3545
3546 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
3547 $isRelatedId = TRUE;
3548 }
3549
3550 $entityID[] = $entityId;
3551 if (!empty($additionalParticipantId)) {
3552 $entityID += $additionalParticipantId;
3553 }
3554 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
3555 if (empty($params['prevContribution'])) {
3556 $entityID = NULL;
3557 }
3558
3559 $statusId = $params['contribution']->contribution_status_id;
3560
3561 // build line item array if its not set in $params
3562 if (empty($params['line_item']) || $additionalParticipantId) {
3563 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
3564 }
3565
3566 if ($contributionStatus != 'Failed' &&
3567 !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later)
3568 ) {
3569 $skipRecords = TRUE;
3570 $pendingStatus = [
3571 'Pending',
3572 'In Progress',
3573 ];
3574 if (in_array($contributionStatus, $pendingStatus)) {
3575 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3576 $params['financial_type_id'],
3577 'Accounts Receivable Account is'
3578 );
3579 }
3580 elseif (!empty($params['payment_processor'])) {
3581 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($params['payment_processor'], NULL, 'civicrm_payment_processor');
3582 $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', [
3583 'id' => $params['payment_processor'],
3584 'return' => 'payment_instrument_id',
3585 ]);
3586 }
3587 elseif (!empty($params['payment_instrument_id'])) {
3588 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
3589 }
3590 else {
3591 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3592 $queryParams = [1 => [$relationTypeId, 'Integer']];
3593 $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);
3594 }
3595
3596 $totalAmount = $params['total_amount'] ?? NULL;
3597 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
3598 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
3599 }
3600 //build financial transaction params
3601 $trxnParams = [
3602 'contribution_id' => $params['contribution']->id,
3603 'to_financial_account_id' => $params['to_financial_account_id'],
3604 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'),
3605 'total_amount' => $totalAmount,
3606 'fee_amount' => $params['fee_amount'] ?? NULL,
3607 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
3608 'currency' => $params['contribution']->currency,
3609 'trxn_id' => $params['contribution']->trxn_id,
3610 // @todo - this is getting the status id from the contribution - that is BAD - ie the contribution could be partially
3611 // paid but each payment is completed. The work around is to pass in the status_id in the trxn_params but
3612 // this should really default to completed (after discussion).
3613 'status_id' => $statusId,
3614 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id),
3615 'check_number' => $params['check_number'] ?? NULL,
3616 'pan_truncation' => $params['pan_truncation'] ?? NULL,
3617 'card_type_id' => $params['card_type_id'] ?? NULL,
3618 ];
3619 if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') {
3620 $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis');
3621 if (isset($params['refund_trxn_id'])) {
3622 // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form.
3623 $trxnParams['trxn_id'] = $params['refund_trxn_id'];
3624 }
3625 }
3626 //CRM-16259, set is_payment flag for non pending status
3627 if (!in_array($contributionStatus, $pendingStatus)) {
3628 $trxnParams['is_payment'] = 1;
3629 }
3630 if (!empty($params['payment_processor'])) {
3631 $trxnParams['payment_processor_id'] = $params['payment_processor'];
3632 }
3633
3634 if (isset($fromFinancialAccountId)) {
3635 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
3636 }
3637
3638 // consider external values passed for recording transaction entry
3639 if (!empty($financialTrxnValues)) {
3640 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
3641 }
3642 if (empty($trxnParams['payment_processor_id'])) {
3643 unset($trxnParams['payment_processor_id']);
3644 }
3645
3646 $params['trxnParams'] = $trxnParams;
3647
3648 if ($isUpdate) {
3649 $updated = FALSE;
3650 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
3651 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
3652 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
3653 if (!isset($params['trxnParams']['trxn_id'])) {
3654 // Actually I have no idea why we are overwriting any values from the previous contribution.
3655 // (filling makes sense to me). However, only protecting this value as I really really know we
3656 // don't want this one overwritten.
3657 // CRM-17751.
3658 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
3659 }
3660 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
3661
3662 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
3663 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
3664 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
3665 ) {
3666 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3667 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
3668 }
3669
3670 //if financial type is changed
3671 if (!empty($params['financial_type_id']) &&
3672 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
3673 ) {
3674 $accountRelationship = 'Income Account is';
3675 if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) {
3676 $accountRelationship = 'Deferred Revenue Account is';
3677 }
3678 $oldFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['prevContribution']->financial_type_id, $accountRelationship);
3679 $newFinancialAccount = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship($params['financial_type_id'], $accountRelationship);
3680 if ($oldFinancialAccount != $newFinancialAccount) {
3681 $params['total_amount'] = 0;
3682 // If we have a fee amount set reverse this as well.
3683 if (isset($params['fee_amount'])) {
3684 $params['trxnParams']['fee_amount'] = 0 - $params['fee_amount'];
3685 }
3686 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
3687 $params['trxnParams']['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
3688 $params['prevContribution']->financial_type_id, $accountRelationship);
3689 }
3690 else {
3691 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3692 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3693 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3694 }
3695 }
3696 self::updateFinancialAccounts($params, 'changeFinancialType');
3697 $params['skipLineItem'] = FALSE;
3698 foreach ($params['line_item'] as &$lineItems) {
3699 foreach ($lineItems as &$line) {
3700 $line['financial_type_id'] = $params['financial_type_id'];
3701 }
3702 }
3703 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changeFinancialType');
3704 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
3705 $params['financial_account_id'] = $newFinancialAccount;
3706 $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount'];
3707 // Set the transaction fee amount back to the original value for creating the new positive financial trxn.
3708 if (isset($params['fee_amount'])) {
3709 $params['trxnParams']['fee_amount'] = $params['fee_amount'];
3710 }
3711 self::updateFinancialAccounts($params);
3712 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE);
3713 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
3714 $updated = TRUE;
3715 $params['deferred_financial_account_id'] = $newFinancialAccount;
3716 }
3717 }
3718
3719 //Update contribution status
3720 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
3721 if (!isset($params['refund_trxn_id'])) {
3722 // CRM-17751 This has previously been deliberately set. No explanation as to why one variant
3723 // gets preference over another so I am only 'protecting' a very specific tested flow
3724 // and letting natural justice take care of the rest.
3725 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3726 }
3727 if (!empty($params['contribution_status_id']) &&
3728 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3729 ) {
3730 //Update Financial Records
3731 $callUpdateFinancialAccounts = self::updateFinancialAccountsOnContributionStatusChange($params);
3732 if ($callUpdateFinancialAccounts) {
3733 self::updateFinancialAccounts($params, 'changedStatus');
3734 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedStatus');
3735 }
3736 $updated = TRUE;
3737 }
3738
3739 // change Payment Instrument for a Completed contribution
3740 // first handle special case when contribution is changed from Pending to Completed status when initial payment
3741 // instrument is null and now new payment instrument is added along with the payment
3742 if (!$params['contribution']->payment_instrument_id) {
3743 $params['contribution']->find(TRUE);
3744 }
3745 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3746 $params['trxnParams']['check_number'] = $params['check_number'] ?? NULL;
3747
3748 if (self::isPaymentInstrumentChange($params, $pendingStatus)) {
3749 $updated = CRM_Core_BAO_FinancialTrxn::updateFinancialAccountsOnPaymentInstrumentChange($params);
3750 }
3751
3752 //if Change contribution amount
3753 $params['trxnParams']['fee_amount'] = $params['fee_amount'] ?? NULL;
3754 $params['trxnParams']['net_amount'] = $params['net_amount'] ?? NULL;
3755 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
3756 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
3757 if (isset($totalAmount) &&
3758 $totalAmount != $params['prevContribution']->total_amount
3759 ) {
3760 //Update Financial Records
3761 $params['trxnParams']['from_financial_account_id'] = NULL;
3762 self::updateFinancialAccounts($params, 'changedAmount');
3763 CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, 'changedAmount');
3764 $updated = TRUE;
3765 }
3766
3767 if (!$updated) {
3768 // Looks like we might have a data correction update.
3769 // This would be a case where a transaction id has been entered but it is incorrect &
3770 // the person goes back in & fixes it, as opposed to a new transaction.
3771 // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting
3772 // the data fix scenario.
3773 // CRM-17751.
3774 if (isset($params['refund_trxn_id'])) {
3775 $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']);
3776 if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) {
3777 civicrm_api3('FinancialTrxn', 'create', [
3778 'id' => $refundIDs['financialTrxnId'],
3779 'trxn_id' => $params['refund_trxn_id'],
3780 ]);
3781 }
3782 }
3783 $cardType = $params['card_type_id'] ?? NULL;
3784 $panTruncation = $params['pan_truncation'] ?? NULL;
3785 CRM_Core_BAO_FinancialTrxn::updateCreditCardDetails($params['contribution']->id, $panTruncation, $cardType);
3786 }
3787 }
3788
3789 else {
3790 // records finanical trxn and entity financial trxn
3791 // also make it available as return value
3792 self::recordAlwaysAccountsReceivable($trxnParams, $params);
3793 $trxnParams['pan_truncation'] = $params['pan_truncation'] ?? NULL;
3794 $trxnParams['card_type_id'] = $params['card_type_id'] ?? NULL;
3795 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
3796 $params['entity_id'] = $financialTxn->id;
3797 if (empty($params['partial_payment_total']) && empty($params['partial_amount_to_pay'])) {
3798 self::$_trxnIDs[] = $financialTxn->id;
3799 }
3800 }
3801 }
3802 // record line items and financial items
3803 if (empty($params['skipLineItem'])) {
3804 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $isUpdate);
3805 }
3806
3807 // create batch entry if batch_id is passed and
3808 // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611
3809 if (!empty($params['batch_id']) && !empty($financialTxn)) {
3810 $entityParams = [
3811 'batch_id' => $params['batch_id'],
3812 'entity_table' => 'civicrm_financial_trxn',
3813 'entity_id' => $financialTxn->id,
3814 ];
3815 CRM_Batch_BAO_EntityBatch::create($entityParams);
3816 }
3817
3818 // when a fee is charged
3819 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
3820 CRM_Core_BAO_FinancialTrxn::recordFees($params);
3821 }
3822
3823 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
3824 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
3825 ) {
3826 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
3827 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
3828 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
3829 }
3830 unset($params['line_item']);
3831 self::$_trxnIDs = NULL;
3832 return $return;
3833 }
3834
3835 /**
3836 * Update all financial accounts entry.
3837 *
3838 * @param array $params
3839 * Contribution object, line item array and params for trxn.
3840 *
3841 * @param string $context
3842 * Update scenarios.
3843 *
3844 * @todo stop passing $params by reference. It is unclear the purpose of doing this &
3845 * adds unpredictability.
3846 *
3847 */
3848 public static function updateFinancialAccounts(&$params, $context = NULL) {
3849 $trxnID = NULL;
3850 $inputParams = $params;
3851 $isARefund = self::isContributionUpdateARefund($params['prevContribution']->contribution_status_id, $params['contribution']->contribution_status_id);
3852
3853 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
3854 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3855 $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = ($params['total_amount'] - $params['prevContribution']->total_amount);
3856 }
3857
3858 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3859 // @todo we should stop passing $params by reference - splitting this out would be a step towards that.
3860 $params['entity_id'] = $trxn->id;
3861
3862 $itemParams['entity_table'] = 'civicrm_line_item';
3863 $trxnIds['id'] = $params['entity_id'];
3864 $previousLineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($params['contribution']->id);
3865 foreach ($params['line_item'] as $fieldId => $fields) {
3866 $params = self::createFinancialItemsForLine($params, $context, $fields, $previousLineItems, $inputParams, $isARefund, $trxnIds, $fieldId);
3867 }
3868 }
3869
3870 /**
3871 * Is this contribution status a reversal.
3872 *
3873 * If so we would expect to record a negative value in the financial_trxn table.
3874 *
3875 * @param int $status_id
3876 *
3877 * @return bool
3878 */
3879 public static function isContributionStatusNegative($status_id) {
3880 $reversalStatuses = ['Cancelled', 'Chargeback', 'Refunded'];
3881 return in_array(CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $status_id), $reversalStatuses, TRUE);
3882 }
3883
3884 /**
3885 * Check status validation on update of a contribution.
3886 *
3887 * @param array $values
3888 * Previous form values before submit.
3889 *
3890 * @param array $fields
3891 * The input form values.
3892 *
3893 * @param array $errors
3894 * List of errors.
3895 *
3896 * @return bool
3897 */
3898 public static function checkStatusValidation($values, &$fields, &$errors) {
3899 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3900 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3901 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3902 return FALSE;
3903 }
3904 }
3905 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3906 $checkStatus = [
3907 'Cancelled' => ['Completed', 'Refunded'],
3908 'Completed' => ['Cancelled', 'Refunded', 'Chargeback'],
3909 'Pending' => ['Cancelled', 'Completed', 'Failed', 'Partially paid'],
3910 'In Progress' => ['Cancelled', 'Completed', 'Failed'],
3911 'Refunded' => ['Cancelled', 'Completed'],
3912 'Partially paid' => ['Completed'],
3913 'Pending refund' => ['Completed', 'Refunded'],
3914 'Failed' => ['Pending'],
3915 ];
3916
3917 if (!in_array($contributionStatuses[$fields['contribution_status_id']],
3918 CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, []))
3919 ) {
3920 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", [
3921 1 => $contributionStatuses[$values['contribution_status_id']],
3922 2 => $contributionStatuses[$fields['contribution_status_id']],
3923 ]);
3924 }
3925 }
3926
3927 /**
3928 * Delete contribution of contact.
3929 *
3930 * @see https://issues.civicrm.org/jira/browse/CRM-12155
3931 *
3932 * @param int $contactId
3933 * Contact id.
3934 *
3935 */
3936 public static function deleteContactContribution($contactId) {
3937 $contribution = new CRM_Contribute_DAO_Contribution();
3938 $contribution->contact_id = $contactId;
3939 $contribution->find();
3940 while ($contribution->fetch()) {
3941 self::deleteContribution($contribution->id);
3942 }
3943 }
3944
3945 /**
3946 * Get options for a given contribution field.
3947 *
3948 * @param string $fieldName
3949 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3950 * @param array $props whatever is known about this dao object.
3951 *
3952 * @return array|bool
3953 * @see CRM_Core_DAO::buildOptions
3954 *
3955 */
3956 public static function buildOptions($fieldName, $context = NULL, $props = []) {
3957 $className = __CLASS__;
3958 $params = [];
3959 if (isset($props['orderColumn'])) {
3960 $params['orderColumn'] = $props['orderColumn'];
3961 }
3962 switch ($fieldName) {
3963 // This field is not part of this object but the api supports it
3964 case 'payment_processor':
3965 $className = 'CRM_Contribute_BAO_ContributionPage';
3966 // Filter results by contribution page
3967 if (!empty($props['contribution_page_id'])) {
3968 $page = civicrm_api('contribution_page', 'getsingle', [
3969 'version' => 3,
3970 'id' => ($props['contribution_page_id']),
3971 ]);
3972 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3973 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3974 }
3975 break;
3976
3977 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3978 case 'honor_type_id':
3979 $className = 'CRM_Contribute_BAO_ContributionSoft';
3980 $fieldName = 'soft_credit_type_id';
3981 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3982 break;
3983
3984 case 'contribution_status_id':
3985 if ($context !== 'validate') {
3986 $params['condition'] = "v.name <> 'Template'";
3987 }
3988 }
3989 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3990 }
3991
3992 /**
3993 * Validate financial type.
3994 *
3995 * @see https://issues.civicrm.org/jira/browse/CRM-13231
3996 *
3997 * @param int $financialTypeId
3998 * Financial Type id.
3999 *
4000 * @param string $relationName
4001 *
4002 * @return array|bool
4003 */
4004 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
4005 $financialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeId, $relationName);
4006
4007 if (!$financialAccount) {
4008 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
4009 }
4010 return FALSE;
4011 }
4012
4013 /**
4014 * @param int $targetCid
4015 * @param $activityType
4016 * @param string $title
4017 * @param int $contributionId
4018 * @param string $totalAmount
4019 * @param string $currency
4020 * @param string $trxn_date
4021 *
4022 * @throws \CRM_Core_Exception
4023 * @throws \CiviCRM_API3_Exception
4024 */
4025 public static function addActivityForPayment($targetCid, $activityType, $title, $contributionId, $totalAmount, $currency, $trxn_date) {
4026 $paymentAmount = CRM_Utils_Money::format($totalAmount, $currency);
4027 $subject = "{$paymentAmount} - Offline {$activityType} for {$title}";
4028 $date = CRM_Utils_Date::isoToMysql($trxn_date);
4029 // source record id would be the contribution id
4030 $srcRecId = $contributionId;
4031
4032 // activity params
4033 $activityParams = [
4034 'source_contact_id' => $targetCid,
4035 'source_record_id' => $srcRecId,
4036 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', $activityType),
4037 'subject' => $subject,
4038 'activity_date_time' => $date,
4039 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
4040 'skipRecentView' => TRUE,
4041 ];
4042
4043 // create activity with target contacts
4044 $session = CRM_Core_Session::singleton();
4045 $id = $session->get('userID');
4046 if ($id) {
4047 $activityParams['source_contact_id'] = $id;
4048 $activityParams['target_contact_id'][] = $targetCid;
4049 }
4050 civicrm_api3('Activity', 'create', $activityParams);
4051 }
4052
4053 /**
4054 * Get list of payments displayed by Contribute_Page_PaymentInfo.
4055 *
4056 * @param int $id
4057 * @param string $component
4058 * @param bool $getTrxnInfo
4059 *
4060 * @return mixed
4061 *
4062 * @throws \CRM_Core_Exception
4063 * @throws \CiviCRM_API3_Exception
4064 */
4065 public static function getPaymentInfo($id, $component = 'contribution', $getTrxnInfo = FALSE) {
4066 // @todo deprecate passing in component - always call with contribution.
4067 if ($component == 'event') {
4068 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
4069
4070 if (!$contributionId) {
4071 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
4072 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
4073 $id = $primaryParticipantId;
4074 }
4075 if (!$contributionId) {
4076 return;
4077 }
4078 }
4079 }
4080 elseif ($component == 'membership') {
4081 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $id, 'contribution_id', 'membership_id');
4082 }
4083 else {
4084 $contributionId = $id;
4085 }
4086
4087 // The balance used to be calculated this way - we really want to remove this 'oldCalculation'
4088 // but need to unpick the whole trxn_id it's returning first.
4089 $oldCalculation = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
4090 $baseTrxnId = !empty($oldCalculation['trxn_id']) ? $oldCalculation['trxn_id'] : NULL;
4091 if (!$baseTrxnId) {
4092 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
4093 $baseTrxnId = $baseTrxnId['financialTrxnId'];
4094 }
4095 $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
4096
4097 $paymentBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionId, $total);
4098
4099 $contribution = civicrm_api3('Contribution', 'getsingle', [
4100 'id' => $contributionId,
4101 'return' => [
4102 'currency',
4103 'is_pay_later',
4104 'contribution_status_id',
4105 'financial_type_id',
4106 ],
4107 ]);
4108
4109 $info['payLater'] = $contribution['is_pay_later'];
4110 $info['contribution_status'] = $contribution['contribution_status'];
4111 $info['currency'] = $contribution['currency'];
4112
4113 $info['total'] = $total;
4114 $info['paid'] = $total - $paymentBalance;
4115 $info['balance'] = $paymentBalance;
4116 $info['id'] = $id;
4117 $info['component'] = $component;
4118 if ($getTrxnInfo && $baseTrxnId) {
4119 $info['transaction'] = self::getContributionTransactionInformation($contributionId, $contribution['financial_type_id']);
4120 }
4121
4122 $info['payment_links'] = self::getContributionPaymentLinks($id, $paymentBalance, $info['contribution_status']);
4123 return $info;
4124 }
4125
4126 /**
4127 * Get the outstanding balance on a contribution.
4128 *
4129 * @param int $contributionId
4130 * @param float $contributionTotal
4131 * Optional amount to override the saved amount paid (e.g if calculating what it WILL be).
4132 *
4133 * @return float
4134 */
4135 public static function getContributionBalance($contributionId, $contributionTotal = NULL) {
4136 if ($contributionTotal === NULL) {
4137 $contributionTotal = CRM_Price_BAO_LineItem::getLineTotal($contributionId);
4138 }
4139
4140 return (float) CRM_Utils_Money::subtractCurrencies(
4141 $contributionTotal,
4142 CRM_Core_BAO_FinancialTrxn::getTotalPayments($contributionId, TRUE),
4143 CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'currency')
4144 );
4145 }
4146
4147 /**
4148 * Get the tax amount (misnamed function).
4149 *
4150 * @param array $params
4151 *
4152 * @return array
4153 * @throws \CiviCRM_API3_Exception
4154 */
4155 protected static function checkTaxAmount($params) {
4156 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
4157
4158 // Update contribution.
4159 if (!empty($params['id'])) {
4160 // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update
4161 // there are no tax implications - early return.
4162 if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) {
4163 return $params;
4164 }
4165 if (empty($params['prevContribution'])) {
4166 $params['prevContribution'] = self::getOriginalContribution($params['id']);
4167 }
4168
4169 foreach (['total_amount', 'financial_type_id', 'fee_amount'] as $field) {
4170 if (!isset($params[$field])) {
4171 if ($field == 'total_amount' && $params['prevContribution']->tax_amount) {
4172 // Tax amount gets added back on later....
4173 $params['total_amount'] = $params['prevContribution']->total_amount -
4174 $params['prevContribution']->tax_amount;
4175 }
4176 else {
4177 $params[$field] = $params['prevContribution']->$field;
4178 if ($params[$field] != $params['prevContribution']->$field) {
4179 }
4180 }
4181 }
4182 }
4183
4184 self::calculateMissingAmountParams($params, $params['id']);
4185 if (!array_key_exists($params['financial_type_id'], $taxRates)) {
4186 // Assign tax Amount on update of contribution
4187 if (!empty($params['prevContribution']->tax_amount)) {
4188 $params['tax_amount'] = 'null';
4189 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
4190 foreach ($params['line_item'] as $setID => $priceField) {
4191 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4192 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4193 }
4194 }
4195 }
4196 }
4197 }
4198
4199 // New Contribution and update of contribution with tax rate financial type
4200 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
4201 empty($params['skipLineItem'])) {
4202 $taxRateParams = $taxRates[$params['financial_type_id']];
4203 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams);
4204 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
4205
4206 // Get Line Item on update of contribution
4207 if (isset($params['id'])) {
4208 CRM_Price_BAO_LineItem::getLineItemArray($params, [$params['id']]);
4209 }
4210 else {
4211 CRM_Price_BAO_LineItem::getLineItemArray($params);
4212 }
4213 foreach ($params['line_item'] as $setID => $priceField) {
4214 foreach ($priceField as $priceFieldID => $priceFieldValue) {
4215 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
4216 }
4217 }
4218 $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount'];
4219 }
4220 elseif (isset($params['api.line_item.create'])) {
4221 // Update total amount of contribution using lineItem
4222 $taxAmountArray = [];
4223 foreach ($params['api.line_item.create'] as $key => $value) {
4224 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
4225 $taxRate = $taxRates[$value['financial_type_id']];
4226 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
4227 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
4228 }
4229 }
4230 $params['tax_amount'] = array_sum($taxAmountArray);
4231 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
4232 }
4233
4234 return $params;
4235 }
4236
4237 /**
4238 * Check financial type validation on update of a contribution.
4239 *
4240 * @param int $financialTypeId
4241 * Value of latest Financial Type.
4242 *
4243 * @param int $contributionId
4244 * Contribution Id.
4245 *
4246 * @param array $errors
4247 * List of errors.
4248 *
4249 * @return void
4250 */
4251 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
4252 if (!empty($financialTypeId)) {
4253 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
4254 if ($oldFinancialTypeId == $financialTypeId) {
4255 return;
4256 }
4257 }
4258 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
4259 $params = [
4260 '1' => [$contributionId, 'Integer'],
4261 ];
4262 $result = CRM_Core_DAO::executeQuery($sql, $params);
4263 if ($result->N > 1) {
4264 $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.');
4265 }
4266 }
4267
4268 /**
4269 * Update related pledge payment payments.
4270 *
4271 * This function has been refactored out of the back office contribution form and may
4272 * still overlap with other functions.
4273 *
4274 * @param string $action
4275 * @param int $pledgePaymentID
4276 * @param int $contributionID
4277 * @param bool $adjustTotalAmount
4278 * @param float $total_amount
4279 * @param float $original_total_amount
4280 * @param int $contribution_status_id
4281 * @param int $original_contribution_status_id
4282 */
4283 public static function updateRelatedPledge(
4284 $action,
4285 $pledgePaymentID,
4286 $contributionID,
4287 $adjustTotalAmount,
4288 $total_amount,
4289 $original_total_amount,
4290 $contribution_status_id,
4291 $original_contribution_status_id
4292 ) {
4293 if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) {
4294 return;
4295 }
4296
4297 if ($pledgePaymentID) {
4298 //store contribution id in payment record.
4299 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
4300 }
4301 else {
4302 $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4303 $contributionID,
4304 'id',
4305 'contribution_id'
4306 );
4307 }
4308
4309 if (!$pledgePaymentID) {
4310 return;
4311 }
4312 $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment',
4313 $contributionID,
4314 'pledge_id',
4315 'contribution_id'
4316 );
4317
4318 $updatePledgePaymentStatus = FALSE;
4319
4320 // If either the status or the amount has changed we update the pledge status.
4321 if ($action & CRM_Core_Action::ADD) {
4322 $updatePledgePaymentStatus = TRUE;
4323 }
4324 elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) ||
4325 ($original_total_amount != $total_amount))
4326 ) {
4327 $updatePledgePaymentStatus = TRUE;
4328 }
4329
4330 if ($updatePledgePaymentStatus) {
4331 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID,
4332 [$pledgePaymentID],
4333 $contribution_status_id,
4334 NULL,
4335 $total_amount,
4336 $adjustTotalAmount
4337 );
4338 }
4339 }
4340
4341 /**
4342 * Is there only one line item attached to the contribution.
4343 *
4344 * @param int $id
4345 * Contribution ID.
4346 *
4347 * @return bool
4348 * @throws \CiviCRM_API3_Exception
4349 */
4350 public static function isSingleLineItem($id) {
4351 $lineItemCount = civicrm_api3('LineItem', 'getcount', ['contribution_id' => $id]);
4352 return ($lineItemCount == 1);
4353 }
4354
4355 /**
4356 * Complete an order.
4357 *
4358 * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
4359 *
4360 * Currently overloaded to complete a transaction & repeat a transaction - fix!
4361 *
4362 * Moving it out of the BaseIPN class is just the first step.
4363 *
4364 * @param array $input
4365 * @param array $ids
4366 * @param \CRM_Contribute_BAO_Contribution $contribution
4367 * @param bool $isPostPaymentCreate
4368 * Is this being called from the payment.create api. If so the api has taken care of financial entities.
4369 * Note that our goal is that this would only ever be called from payment.create and never handle financials (only
4370 * transitioning related elements).
4371 *
4372 * @return array
4373 * @throws \CRM_Core_Exception
4374 * @throws \CiviCRM_API3_Exception
4375 */
4376 public static function completeOrder($input, $ids, $contribution, $isPostPaymentCreate = FALSE) {
4377 $transaction = new CRM_Core_Transaction();
4378 // @todo see if we even need this - it's used further down to create an activity
4379 // but the BAO layer should create that - we just need to add a test to cover it & can
4380 // maybe remove $ids altogether.
4381 $contributionContactID = $ids['related_contact'];
4382 $participantID = $ids['participant'];
4383 $recurringContributionID = $ids['contributionRecur'];
4384
4385 // Unset ids just to make it clear it's not used again.
4386 unset($ids);
4387 // The previous details are used when calculating line items so keep it before any code that 'does something'
4388 if (!empty($contribution->id)) {
4389 $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(['id' => $contribution->id]);
4390 }
4391 $inputContributionWhiteList = [
4392 'fee_amount',
4393 'net_amount',
4394 'trxn_id',
4395 'check_number',
4396 'payment_instrument_id',
4397 'is_test',
4398 'campaign_id',
4399 'receive_date',
4400 'receipt_date',
4401 'contribution_status_id',
4402 'card_type_id',
4403 'pan_truncation',
4404 'financial_type_id',
4405 ];
4406
4407 $paymentProcessorId = $input['payment_processor_id'] ?? NULL;
4408
4409 $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
4410
4411 $contributionParams = array_merge([
4412 'contribution_status_id' => $completedContributionStatusID,
4413 'source' => self::getRecurringContributionDescription($contribution, $participantID),
4414 ], array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)
4415 ));
4416
4417 $contributionParams['payment_processor'] = $paymentProcessorId;
4418
4419 if (empty($contributionParams['payment_instrument_id']) && $paymentProcessorId) {
4420 $contributionParams['payment_instrument_id'] = PaymentProcessor::get(FALSE)->addWhere('id', '=', $paymentProcessorId)->addSelect('payment_instrument_id')->execute()->first()['payment_instrument_id'];
4421 }
4422
4423 if ($recurringContributionID) {
4424 $contributionParams['contribution_recur_id'] = $recurringContributionID;
4425 }
4426 $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
4427
4428 $contributionResult = self::repeatTransaction($contribution, $input, $contributionParams);
4429 $contributionID = (int) $contribution->id;
4430
4431 if ($input['component'] == 'contribute') {
4432 if ($contributionParams['contribution_status_id'] === $completedContributionStatusID) {
4433 self::updateMembershipBasedOnCompletionOfContribution(
4434 $contributionID,
4435 $changeDate
4436 );
4437 }
4438 }
4439 else {
4440 if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
4441 $participantParams['id'] = $participantID;
4442 $participantParams['status_id'] = 'Registered';
4443 civicrm_api3('Participant', 'create', $participantParams);
4444 }
4445 }
4446
4447 $contributionParams['id'] = $contributionID;
4448 $contributionParams['is_post_payment_create'] = $isPostPaymentCreate;
4449
4450 if (!$contributionResult) {
4451 $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
4452 }
4453
4454 // Add new soft credit against current $contribution.
4455 if ($recurringContributionID) {
4456 CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($recurringContributionID, $contributionID);
4457 }
4458
4459 $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
4460
4461 CRM_Core_Error::debug_log_message('Contribution record updated successfully');
4462 $transaction->commit();
4463
4464 // @todo - check if Contribution::create does this, test, remove.
4465 CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contributionID, $recurringContributionID,
4466 $contributionParams['contribution_status_id'], $input['amount']);
4467
4468 // create an activity record
4469 // @todo - check if Contribution::create does this, test, remove.
4470 if ($input['component'] == 'contribute') {
4471 //CRM-4027
4472 $targetContactID = NULL;
4473 if ($contributionContactID) {
4474 $targetContactID = $contribution->contact_id;
4475 $contribution->contact_id = $contributionContactID;
4476 }
4477 CRM_Activity_BAO_Activity::addActivity($contribution, 'Contribution', $targetContactID);
4478 }
4479
4480 if (self::isEmailReceipt($input, $contribution->contribution_page_id, $recurringContributionID)) {
4481 civicrm_api3('Contribution', 'sendconfirmation', [
4482 'id' => $contributionID,
4483 'payment_processor_id' => $paymentProcessorId,
4484 ]);
4485 CRM_Core_Error::debug_log_message("Receipt sent");
4486 }
4487
4488 CRM_Core_Error::debug_log_message("Success: Database updated");
4489 return $contributionResult;
4490 }
4491
4492 /**
4493 * Send receipt from contribution.
4494 *
4495 * Do not call this directly - it is being refactored. use contribution.sendmessage api call.
4496 *
4497 * Note that the compose message part has been moved to contribution
4498 * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it.
4499 *
4500 * @param array $input
4501 * Incoming data from Payment processor.
4502 * @param array $ids
4503 * Related object IDs.
4504 * @param int $contributionID
4505 * @param bool $returnMessageText
4506 * Should text be returned instead of sent. This.
4507 * is because the function is also used to generate pdfs
4508 *
4509 * @return array
4510 * @throws \CRM_Core_Exception
4511 * @throws \CiviCRM_API3_Exception
4512 * @throws \Exception
4513 */
4514 public static function sendMail($input, $ids, $contributionID, $returnMessageText = FALSE) {
4515 $values = [];
4516 $contribution = new CRM_Contribute_BAO_Contribution();
4517 $contribution->id = $contributionID;
4518 if (!$contribution->find(TRUE)) {
4519 throw new CRM_Core_Exception('Contribution does not exist');
4520 }
4521 $contribution->loadRelatedObjects($input, $ids, TRUE);
4522 // set receipt from e-mail and name in value
4523 if (!$returnMessageText) {
4524 list($values['receipt_from_name'], $values['receipt_from_email']) = self::generateFromEmailAndName($input, $contribution);
4525 }
4526 $values['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contribution->contribution_status_id);
4527 $return = $contribution->composeMessageArray($input, $ids, $values, $returnMessageText);
4528 if ((!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) {
4529 civicrm_api3('Contribution', 'create', [
4530 'receipt_date' => 'now',
4531 'id' => $contribution->id,
4532 ]);
4533 }
4534 return $return;
4535 }
4536
4537 /**
4538 * Generate From email and from name in an array values
4539 *
4540 * @param array $input
4541 * @param \CRM_Contribute_BAO_Contribution $contribution
4542 *
4543 * @return array
4544 */
4545 public static function generateFromEmailAndName($input, $contribution) {
4546 // Use input value if supplied.
4547 if (!empty($input['receipt_from_email'])) {
4548 return [
4549 CRM_Utils_Array::value('receipt_from_name', $input, ''),
4550 $input['receipt_from_email'],
4551 ];
4552 }
4553 // if we are still empty see if we can use anything from a contribution page.
4554 $pageValues = [];
4555 if (!empty($contribution->contribution_page_id)) {
4556 $pageValues = civicrm_api3('ContributionPage', 'getsingle', ['id' => $contribution->contribution_page_id]);
4557 }
4558 // if we are still empty see if we can use anything from a contribution page.
4559 if (!empty($pageValues['receipt_from_email'])) {
4560 return [
4561 CRM_Utils_Array::value('receipt_from_name', $pageValues),
4562 $pageValues['receipt_from_email'],
4563 ];
4564 }
4565 // If we are still empty fall back to the domain or logged in user information.
4566 return CRM_Core_BAO_Domain::getDefaultReceiptFrom();
4567 }
4568
4569 /**
4570 * Load related memberships.
4571 *
4572 * @param array $ids
4573 *
4574 * @return array $ids
4575 *
4576 * @throws Exception
4577 * @deprecated
4578 *
4579 * Note that in theory it should be possible to retrieve these from the line_item table
4580 * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail
4581 * as it seems the api is not correctly linking the line items when the contribution is created in the flow
4582 * where the contribution is created in the API, followed by the membership (using the api) followed by the membership
4583 * payment. The membership payment BAO does have code to address this but it doesn't appear to be working.
4584 *
4585 * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918.
4586 *
4587 */
4588 public function loadRelatedMembershipObjects($ids = []) {
4589 $query = "
4590 SELECT membership_id
4591 FROM civicrm_membership_payment
4592 WHERE contribution_id = %1 ";
4593 $params = [1 => [$this->id, 'Integer']];
4594 $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, []);
4595
4596 $dao = CRM_Core_DAO::executeQuery($query, $params);
4597 while ($dao->fetch()) {
4598 if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) {
4599 $ids['membership'][$dao->membership_id] = $dao->membership_id;
4600 }
4601 }
4602
4603 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
4604 foreach ($ids['membership'] as $id) {
4605 if (!empty($id)) {
4606 $membership = new CRM_Member_BAO_Membership();
4607 $membership->id = $id;
4608 if (!$membership->find(TRUE)) {
4609 throw new Exception("Could not find membership record: $id");
4610 }
4611 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
4612 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
4613 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
4614 $this->_relatedObjects['membership'][$membership->id . '_' . $membership->membership_type_id] = $membership;
4615
4616 }
4617 }
4618 }
4619 return $ids;
4620 }
4621
4622 /**
4623 * Get the description (source field) for the recurring contribution.
4624 *
4625 * @param CRM_Contribute_BAO_Contribution $contribution
4626 * @param int|null $participantID
4627 *
4628 * @return string
4629 * @throws \CiviCRM_API3_Exception
4630 * @throws \API_Exception
4631 */
4632 protected static function getRecurringContributionDescription($contribution, $participantID) {
4633 if (!empty($contribution->source)) {
4634 return $contribution->source;
4635 }
4636 elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) {
4637 $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', [
4638 'id' => $contribution->contribution_page_id,
4639 'return' => 'title',
4640 ]);
4641 return ts('Online Contribution') . ': ' . $contributionPageTitle;
4642 }
4643 elseif ($participantID) {
4644 $eventTitle = Participant::get(FALSE)
4645 ->addSelect('event.title')
4646 ->addWhere('id', '=', (int) $participantID)
4647 ->execute()->first()['event.title'];
4648 return ts('Online Event Registration') . ': ' . $eventTitle;
4649 }
4650 elseif (!empty($contribution->contribution_recur_id)) {
4651 return 'recurring contribution';
4652 }
4653 return '';
4654 }
4655
4656 /**
4657 * Function use to store line item proportionally in in entity financial trxn table
4658 *
4659 * @param array $trxnParams
4660 *
4661 * @param int $trxnId
4662 *
4663 * @param float $contributionTotalAmount
4664 *
4665 * @throws \CiviCRM_API3_Exception
4666 */
4667 public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) {
4668 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']);
4669 if (!empty($lineItems)) {
4670 // get financial item
4671 list($ftIds, $taxItems) = self::getLastFinancialItemIds($trxnParams['contribution_id']);
4672 $entityParams = [
4673 'contribution_total_amount' => $contributionTotalAmount,
4674 'trxn_total_amount' => $trxnParams['total_amount'],
4675 'trxn_id' => $trxnId,
4676 ];
4677 self::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
4678 }
4679 }
4680
4681 /**
4682 * Checks if line items total amounts
4683 * match the contribution total amount.
4684 *
4685 * @param array $params
4686 * array of order params.
4687 *
4688 * @throws \API_Exception
4689 */
4690 public static function checkLineItems(&$params) {
4691 $totalAmount = $params['total_amount'] ?? NULL;
4692 $lineItemAmount = 0;
4693
4694 foreach ($params['line_items'] as &$lineItems) {
4695 foreach ($lineItems['line_item'] as &$item) {
4696 if (empty($item['financial_type_id'])) {
4697 $item['financial_type_id'] = $params['financial_type_id'];
4698 }
4699 $lineItemAmount += $item['line_total'] + ($item['tax_amount'] ?? 0.00);
4700 }
4701 }
4702
4703 if (!isset($totalAmount)) {
4704 $params['total_amount'] = $lineItemAmount;
4705 }
4706 else {
4707 $currency = $params['currency'] ?? CRM_Core_Config::singleton()->defaultCurrency;
4708
4709 if (!CRM_Utils_Money::equals($totalAmount, $lineItemAmount, $currency)) {
4710 throw new CRM_Contribute_Exception_CheckLineItemsException();
4711 }
4712 }
4713 }
4714
4715 /**
4716 * Get the financial account for the item associated with the new transaction.
4717 *
4718 * @param array $params
4719 * @param int $default
4720 *
4721 * @return int
4722 */
4723 public static function getFinancialAccountForStatusChangeTrxn($params, $default) {
4724
4725 if (!empty($params['financial_account_id'])) {
4726 return $params['financial_account_id'];
4727 }
4728
4729 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name');
4730 $preferredAccountsRelationships = [
4731 'Refunded' => 'Credit/Contra Revenue Account is',
4732 'Chargeback' => 'Chargeback Account is',
4733 ];
4734
4735 if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) {
4736 $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
4737 return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship(
4738 $financialTypeID,
4739 $preferredAccountsRelationships[$contributionStatus]
4740 );
4741 }
4742
4743 return $default;
4744 }
4745
4746 /**
4747 * ContributionPage values were being imposed onto values.
4748 *
4749 * I have made this explicit and removed the couple (is_recur, is_pay_later) we
4750 * REALLY didn't want superimposed. The rest are left there in their overkill out
4751 * of cautiousness.
4752 *
4753 * The rationale for making this explicit is that it was a case of carefully set values being
4754 * seemingly randonly overwritten without much care. In general I think array randomly setting
4755 * variables en mass is risky.
4756 *
4757 * @param array $values
4758 *
4759 * @return array
4760 */
4761 protected function addContributionPageValuesToValuesHeavyHandedly(&$values) {
4762 $contributionPageValues = [];
4763 CRM_Contribute_BAO_ContributionPage::setValues(
4764 $this->contribution_page_id,
4765 $contributionPageValues
4766 );
4767 $valuesToCopy = [
4768 // These are the values that I believe to be useful.
4769 'id',
4770 'title',
4771 'pay_later_receipt',
4772 'pay_later_text',
4773 'receipt_from_email',
4774 'receipt_from_name',
4775 'receipt_text',
4776 'custom_pre_id',
4777 'custom_post_id',
4778 'honoree_profile_id',
4779 'onbehalf_profile_id',
4780 'honor_block_is_active',
4781 // Kinda might be - but would be on the contribution...
4782 'campaign_id',
4783 'currency',
4784 // Included for 'fear of regression' but can't justify any use for these....
4785 'intro_text',
4786 'payment_processor',
4787 'financial_type_id',
4788 'amount_block_is_active',
4789 'bcc_receipt',
4790 'cc_receipt',
4791 'created_date',
4792 'created_id',
4793 'default_amount_id',
4794 'end_date',
4795 'footer_text',
4796 'goal_amount',
4797 'initial_amount_help_text',
4798 'initial_amount_label',
4799 'intro_text',
4800 'is_allow_other_amount',
4801 'is_billing_required',
4802 'is_confirm_enabled',
4803 'is_credit_card_only',
4804 'is_monetary',
4805 'is_partial_payment',
4806 'is_recur_installments',
4807 'is_recur_interval',
4808 'is_share',
4809 'max_amount',
4810 'min_amount',
4811 'min_initial_amount',
4812 'recur_frequency_unit',
4813 'start_date',
4814 'thankyou_footer',
4815 'thankyou_text',
4816 'thankyou_title',
4817
4818 ];
4819 foreach ($valuesToCopy as $valueToCopy) {
4820 if (isset($contributionPageValues[$valueToCopy])) {
4821 if ($valueToCopy === 'title') {
4822 $values[$valueToCopy] = CRM_Contribute_BAO_Contribution_Utils::getContributionPageTitle($this->contribution_page_id);
4823 }
4824 else {
4825 $values[$valueToCopy] = $contributionPageValues[$valueToCopy];
4826 }
4827 }
4828 }
4829 return $values;
4830 }
4831
4832 /**
4833 * Get values of CiviContribute Settings
4834 * and check if its enabled or not.
4835 * Note: The CiviContribute settings are stored as single entry in civicrm_setting
4836 * in serialized form. Usually this should be stored as flat settings for each form fields
4837 * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute
4838 * settings we will live with an inconsistency because it's too hard to change for now.
4839 * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245
4840 *
4841 *
4842 * @param string $name
4843 *
4844 * @return string
4845 *
4846 */
4847 public static function checkContributeSettings($name) {
4848 $contributeSettings = Civi::settings()->get('contribution_invoice_settings');
4849 return $contributeSettings[$name] ?? NULL;
4850 }
4851
4852 /**
4853 * This function process contribution related objects.
4854 *
4855 * @param int $contributionId
4856 * @param int $statusId
4857 * @param int|null $previousStatusId
4858 *
4859 * @param string $receiveDate
4860 *
4861 * @return null|string
4862 */
4863 public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) {
4864 $statusMsg = NULL;
4865 if (!$contributionId || !$statusId) {
4866 return $statusMsg;
4867 }
4868
4869 $params = [
4870 'contribution_id' => $contributionId,
4871 'contribution_status_id' => $statusId,
4872 'previous_contribution_status_id' => $previousStatusId,
4873 'receive_date' => $receiveDate,
4874 ];
4875
4876 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
4877
4878 if (!is_array($updateResult) ||
4879 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
4880 !is_array($updatedComponents) ||
4881 empty($updatedComponents)
4882 ) {
4883 return $statusMsg;
4884 }
4885
4886 // get the user display name.
4887 $sql = "
4888 SELECT display_name as displayName
4889 FROM civicrm_contact
4890 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
4891 WHERE civicrm_contribution.id = {$contributionId}";
4892 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
4893
4894 // get the status message for user.
4895 foreach ($updatedComponents as $componentName => $updatedStatusId) {
4896
4897 if ($componentName == 'CiviMember') {
4898 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
4899 CRM_Member_PseudoConstant::membershipStatus()
4900 );
4901
4902 $statusNameMsgPart = 'updated';
4903 switch ($updatedStatusName) {
4904 case 'Cancelled':
4905 case 'Expired':
4906 $statusNameMsgPart = $updatedStatusName;
4907 break;
4908 }
4909
4910 $statusMsg .= "<br />" . ts("Membership for %1 has been %2.", [
4911 1 => $userDisplayName,
4912 2 => $statusNameMsgPart,
4913 ]);
4914 }
4915
4916 if ($componentName == 'CiviEvent') {
4917 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
4918 CRM_Event_PseudoConstant::participantStatus()
4919 );
4920 if ($updatedStatusName == 'Cancelled') {
4921 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", [1 => $userDisplayName]);
4922 }
4923 elseif ($updatedStatusName == 'Registered') {
4924 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", [1 => $userDisplayName]);
4925 }
4926 }
4927
4928 if ($componentName == 'CiviPledge') {
4929 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
4930 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
4931 );
4932 if ($updatedStatusName == 'Cancelled') {
4933 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", [1 => $userDisplayName]);
4934 }
4935 elseif ($updatedStatusName == 'Failed') {
4936 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", [1 => $userDisplayName]);
4937 }
4938 elseif ($updatedStatusName == 'Completed') {
4939 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", [1 => $userDisplayName]);
4940 }
4941 }
4942 }
4943
4944 return $statusMsg;
4945 }
4946
4947 /**
4948 * Get the contribution as it is in the database before being updated.
4949 *
4950 * @param int $contributionID
4951 *
4952 * @return \CRM_Contribute_BAO_Contribution|null
4953 */
4954 private static function getOriginalContribution($contributionID) {
4955 return self::getValues(['id' => $contributionID]);
4956 }
4957
4958 /**
4959 * Get the amount for the financial item row.
4960 *
4961 * Helper function to start to break down recordFinancialTransactions for readability.
4962 *
4963 * The logic is more historical than .. logical. Paths other than the deprecated one are tested.
4964 *
4965 * Codewise, several somewhat disimmilar things have been squished into recordFinancialAccounts
4966 * for historical reasons. Going forwards we can hope to add tests & improve readibility
4967 * of that function
4968 *
4969 * @param array $params
4970 * Params as passed to contribution.create
4971 *
4972 * @param string $context
4973 * changeFinancialType| changedAmount
4974 * @param array $lineItemDetails
4975 * Line items.
4976 * @param bool $isARefund
4977 * Is this a refund / negative transaction.
4978 * @param int $previousLineItemTotal
4979 *
4980 * @return float
4981 * @todo move recordFinancialAccounts & helper functions to their own class?
4982 *
4983 */
4984 protected static function getFinancialItemAmountFromParams($params, $context, $lineItemDetails, $isARefund, $previousLineItemTotal) {
4985 if ($context == 'changedAmount') {
4986 $lineTotal = $lineItemDetails['line_total'];
4987 if ($lineTotal != $previousLineItemTotal) {
4988 $lineTotal -= $previousLineItemTotal;
4989 }
4990 return $lineTotal;
4991 }
4992 elseif ($context == 'changeFinancialType') {
4993 return -$lineItemDetails['line_total'];
4994 }
4995 elseif ($context == 'changedStatus') {
4996 $cancelledTaxAmount = 0;
4997 if ($isARefund) {
4998 $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $lineItemDetails, '0.00');
4999 }
5000 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total'] + (float) $cancelledTaxAmount);
5001 }
5002 elseif ($context === NULL) {
5003 // erm, yes because? but, hey, it's tested.
5004 return $lineItemDetails['line_total'];
5005 }
5006 elseif (empty($lineItemDetails['line_total'])) {
5007 // follow legacy code path
5008 Civi::log()
5009 ->warning('Deprecated bit of code, please log a ticket explaining how you got here!', ['civi.tag' => 'deprecated']);
5010 return $params['total_amount'];
5011 }
5012 else {
5013 return self::getMultiplier($params['contribution']->contribution_status_id, $context) * ((float) $lineItemDetails['line_total']);
5014 }
5015 }
5016
5017 /**
5018 * Get the multiplier for adjusting rows.
5019 *
5020 * If we are dealing with a refund or cancellation then it will be a negative
5021 * amount to reflect the negative transaction.
5022 *
5023 * If we are changing Financial Type it will be a negative amount to
5024 * adjust down the old type.
5025 *
5026 * @param int $contribution_status_id
5027 * @param string $context
5028 *
5029 * @return int
5030 */
5031 protected static function getMultiplier($contribution_status_id, $context) {
5032 if ($context == 'changeFinancialType' || self::isContributionStatusNegative($contribution_status_id)) {
5033 return -1;
5034 }
5035 return 1;
5036 }
5037
5038 /**
5039 * Does this transaction reflect a payment instrument change.
5040 *
5041 * @param array $params
5042 * @param array $pendingStatuses
5043 *
5044 * @return bool
5045 */
5046 protected static function isPaymentInstrumentChange(&$params, $pendingStatuses) {
5047 $contributionStatus = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $params['contribution']->contribution_status_id);
5048
5049 if (array_key_exists('payment_instrument_id', $params)) {
5050 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
5051 !CRM_Utils_System::isNull($params['payment_instrument_id'])
5052 ) {
5053 //check if status is changed from Pending to Completed
5054 // do not update payment instrument changes for Pending to Completed
5055 if (!($contributionStatus == 'Completed' &&
5056 in_array($params['prevContribution']->contribution_status_id, $pendingStatuses))
5057 ) {
5058 return TRUE;
5059 }
5060 }
5061 elseif ((!CRM_Utils_System::isNull($params['payment_instrument_id']) &&
5062 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
5063 $params['payment_instrument_id'] != $params['prevContribution']->payment_instrument_id
5064 ) {
5065 return TRUE;
5066 }
5067 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
5068 $params['contribution']->check_number != $params['prevContribution']->check_number
5069 ) {
5070 // another special case when check number is changed, create new financial records
5071 // create financial trxn with negative amount
5072 return TRUE;
5073 }
5074 }
5075 return FALSE;
5076 }
5077
5078 /**
5079 * Update the memberships associated with a contribution if it has been completed.
5080 *
5081 * Note that the way in which $memberships are loaded as objects is pretty messy & I think we could just
5082 * load them in this function. Code clean up would compensate for any minor performance implication.
5083 *
5084 * @param int $contributionID
5085 * @param string $changeDate
5086 *
5087 * @throws \CRM_Core_Exception
5088 * @throws \CiviCRM_API3_Exception
5089 */
5090 public static function updateMembershipBasedOnCompletionOfContribution($contributionID, $changeDate) {
5091 $memberships = self::getRelatedMemberships($contributionID);
5092 foreach ($memberships as $membership) {
5093 $membershipParams = [
5094 'id' => $membership['id'],
5095 'contact_id' => $membership['contact_id'],
5096 'is_test' => $membership['is_test'],
5097 'membership_type_id' => $membership['membership_type_id'],
5098 'membership_activity_status' => 'Completed',
5099 ];
5100
5101 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'],
5102 $membershipParams['membership_type_id'],
5103 $membershipParams['is_test'],
5104 $membershipParams['id']
5105 );
5106
5107 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
5108 // this picks up membership type changes during renewals
5109 // @todo this is almost certainly an obsolete sql call, the pre-change
5110 // membership is accessible via $this->_relatedObjects
5111 $sql = "
5112 SELECT membership_type_id
5113 FROM civicrm_membership_log
5114 WHERE membership_id={$membershipParams['id']}
5115 ORDER BY id DESC
5116 LIMIT 1;";
5117 $dao = CRM_Core_DAO::executeQuery($sql);
5118 if ($dao->fetch()) {
5119 if (!empty($dao->membership_type_id)) {
5120 $membershipParams['membership_type_id'] = $dao->membership_type_id;
5121 }
5122 }
5123 if (empty($membership['end_date']) || (int) $membership['status_id'] !== CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending')) {
5124 // Passing num_terms to the api triggers date calculations, but for pending memberships these may be already calculated.
5125 // sigh - they should be consistent but removing the end date check causes test failures & maybe UI too?
5126 // 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.
5127 // ... except testCompleteTransactionMembershipPriceSetTwoTerms hits this line so the above is obviously not true....
5128 // @todo once apiv4 ships with core switch to that & find sanity.
5129 $membershipParams['num_terms'] = self::getNumTermsByContributionAndMembershipType(
5130 $membershipParams['membership_type_id'],
5131 $contributionID
5132 );
5133 }
5134 // @todo remove all this stuff in favour of letting the api call further down handle in
5135 // (it is a duplication of what the api does).
5136 $dates = array_fill_keys([
5137 'join_date',
5138 'start_date',
5139 'end_date',
5140 ], NULL);
5141 if ($currentMembership) {
5142 /*
5143 * Fixed FOR CRM-4433
5144 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
5145 * when Contribution mode is notify and membership is for renewal )
5146 */
5147 // Test cover for this is in testRepeattransactionRenewMembershipOldMembership
5148 // Be afraid.
5149 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
5150
5151 // @todo - we should pass membership_type_id instead of null here but not
5152 // adding as not sure of testing
5153 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'],
5154 $changeDate, NULL, $membershipParams['num_terms']
5155 );
5156 $dates['join_date'] = $currentMembership['join_date'];
5157 }
5158
5159 //get the status for membership.
5160 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
5161 $dates['end_date'],
5162 $dates['join_date'],
5163 'now',
5164 TRUE,
5165 $membershipParams['membership_type_id'],
5166 $membershipParams
5167 );
5168
5169 unset($dates['end_date']);
5170 $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
5171 //we might be renewing membership,
5172 //so make status override false.
5173 $membershipParams['is_override'] = FALSE;
5174 $membershipParams['status_override_end_date'] = 'null';
5175 civicrm_api3('Membership', 'create', $membershipParams);
5176 }
5177 }
5178
5179 /**
5180 * Get payment links as they relate to a contribution.
5181 *
5182 * If a payment can be made then include a payment link & if a refund is appropriate
5183 * then a refund link.
5184 *
5185 * @param int $id
5186 * @param float $balance
5187 * @param string $contributionStatus
5188 *
5189 * @return array
5190 * $actionLinks Links array containing:
5191 * -url
5192 * -title
5193 */
5194 protected static function getContributionPaymentLinks($id, $balance, $contributionStatus) {
5195 if ($contributionStatus === 'Failed' || !CRM_Core_Permission::check('edit contributions')) {
5196 // In general the balance is the best way to determine if a payment can be added or not,
5197 // but not for Failed contributions, where we don't accept additional payments at the moment.
5198 // (in some cases the contribution is 'Pending' and only the payment is failed. In those we
5199 // do accept more payments agains them.
5200 return [];
5201 }
5202 $actionLinks = [];
5203 $actionLinks[] = [
5204 'url' => CRM_Utils_System::url('civicrm/payment', [
5205 'action' => 'add',
5206 'reset' => 1,
5207 'id' => $id,
5208 'is_refund' => 0,
5209 ]),
5210 'title' => ts('Record Payment'),
5211 ];
5212
5213 if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
5214 $actionLinks[] = [
5215 'url' => CRM_Utils_System::url('civicrm/payment', [
5216 'action' => 'add',
5217 'reset' => 1,
5218 'is_refund' => 0,
5219 'id' => $id,
5220 'mode' => 'live',
5221 ]),
5222 'title' => ts('Submit Credit Card payment'),
5223 ];
5224 }
5225 $actionLinks[] = [
5226 'url' => CRM_Utils_System::url('civicrm/payment', [
5227 'action' => 'add',
5228 'reset' => 1,
5229 'id' => $id,
5230 'is_refund' => 1,
5231 ]),
5232 'title' => ts('Record Refund'),
5233 ];
5234 return $actionLinks;
5235 }
5236
5237 /**
5238 * Get a query to determine the amount donated by the contact/s in the current financial year.
5239 *
5240 * @param array $contactIDs
5241 *
5242 * @return string
5243 */
5244 public static function getAnnualQuery($contactIDs) {
5245 $contactIDs = implode(',', $contactIDs);
5246 $config = CRM_Core_Config::singleton();
5247 $currentMonth = date('m');
5248 $currentDay = date('d');
5249 if (
5250 (int) $config->fiscalYearStart['M'] > $currentMonth ||
5251 (
5252 (int) $config->fiscalYearStart['M'] == $currentMonth &&
5253 (int) $config->fiscalYearStart['d'] > $currentDay
5254 )
5255 ) {
5256 $year = date('Y') - 1;
5257 }
5258 else {
5259 $year = date('Y');
5260 }
5261 $nextYear = $year + 1;
5262
5263 if ($config->fiscalYearStart) {
5264 $newFiscalYearStart = $config->fiscalYearStart;
5265 if ($newFiscalYearStart['M'] < 10) {
5266 // This is just a clumsy way of adding padding.
5267 // @todo next round look for a nicer way.
5268 $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M'];
5269 }
5270 if ($newFiscalYearStart['d'] < 10) {
5271 // This is just a clumsy way of adding padding.
5272 // @todo next round look for a nicer way.
5273 $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d'];
5274 }
5275 $config->fiscalYearStart = $newFiscalYearStart;
5276 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
5277 }
5278 else {
5279 // First of January.
5280 $monthDay = '0101';
5281 }
5282 $startDate = "$year$monthDay";
5283 $endDate = "$nextYear$monthDay";
5284
5285 $whereClauses = [
5286 'contact_id' => 'IN (' . $contactIDs . ')',
5287 'is_test' => ' = 0',
5288 'receive_date' => ['>=' . $startDate, '< ' . $endDate],
5289 ];
5290 $havingClause = 'contribution_status_id = ' . (int) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
5291 CRM_Financial_BAO_FinancialType::addACLClausesToWhereClauses($whereClauses);
5292
5293 $clauses = [];
5294 foreach ($whereClauses as $key => $clause) {
5295 $clauses[] = 'b.' . $key . " " . implode(' AND b.' . $key, (array) $clause);
5296 }
5297 $whereClauseString = implode(' AND ', $clauses);
5298
5299 // See https://github.com/civicrm/civicrm-core/pull/13512 for discussion of how
5300 // this group by + having on contribution_status_id improves performance
5301 $query = "
5302 SELECT COUNT(*) as count,
5303 SUM(total_amount) as amount,
5304 AVG(total_amount) as average,
5305 currency
5306 FROM civicrm_contribution b
5307 WHERE " . $whereClauseString . "
5308 GROUP BY currency, contribution_status_id
5309 HAVING $havingClause
5310 ";
5311 return $query;
5312 }
5313
5314 /**
5315 * Assign Test Value.
5316 *
5317 * @param string $fieldName
5318 * @param array $fieldDef
5319 * @param int $counter
5320 */
5321 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
5322 if ($fieldName == 'tax_amount') {
5323 $this->{$fieldName} = "0.00";
5324 }
5325 elseif ($fieldName == 'net_amount') {
5326 $this->{$fieldName} = "2.00";
5327 }
5328 elseif ($fieldName == 'total_amount') {
5329 $this->{$fieldName} = "3.00";
5330 }
5331 elseif ($fieldName == 'fee_amount') {
5332 $this->{$fieldName} = "1.00";
5333 }
5334 else {
5335 parent::assignTestValues($fieldName, $fieldDef, $counter);
5336 }
5337 }
5338
5339 /**
5340 * Check if contribution has participant/membership payment.
5341 *
5342 * @param int $contributionId
5343 * Contribution ID
5344 *
5345 * @return bool
5346 */
5347 public static function allowUpdateRevenueRecognitionDate($contributionId) {
5348 // get line item for contribution
5349 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId);
5350 // check if line item is for membership or participant
5351 foreach ($lineItems as $items) {
5352 if ($items['entity_table'] == 'civicrm_participant') {
5353 $flag = FALSE;
5354 break;
5355 }
5356 elseif ($items['entity_table'] == 'civicrm_membership') {
5357 $flag = FALSE;
5358 }
5359 else {
5360 $flag = TRUE;
5361 break;
5362 }
5363 }
5364 return $flag;
5365 }
5366
5367 /**
5368 * Create Accounts Receivable financial trxn entry for Completed Contribution.
5369 *
5370 * @param array $trxnParams
5371 * Financial trxn params
5372 * @param array $contributionParams
5373 * Contribution Params
5374 *
5375 * @return null
5376 */
5377 public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) {
5378 if (!Civi::settings()->get('always_post_to_accounts_receivable')) {
5379 return NULL;
5380 }
5381 $statusId = $contributionParams['contribution']->contribution_status_id;
5382 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
5383 $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId];
5384 $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id];
5385 // Return if contribution status is not completed.
5386 if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus)
5387 || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending'
5388 && $contributionParams['prevContribution']->is_pay_later == 0
5389 )))
5390 ) {
5391 return NULL;
5392 }
5393
5394 $params = $trxnParams;
5395 $financialTypeID = !empty($contributionParams['financial_type_id']) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id;
5396 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($financialTypeID, 'Accounts Receivable Account is');
5397 $params['to_financial_account_id'] = $arAccountId;
5398 $params['status_id'] = array_search('Pending', $contributionStatuses);
5399 $params['is_payment'] = FALSE;
5400 $trxn = CRM_Core_BAO_FinancialTrxn::create($params);
5401 self::$_trxnIDs[] = $trxn->id;
5402 $trxnParams['from_financial_account_id'] = $params['to_financial_account_id'];
5403 }
5404
5405 /**
5406 * Calculate financial item amount when contribution is updated.
5407 *
5408 * @param array $params
5409 * contribution params
5410 * @param array $amountParams
5411 *
5412 * @param string $context
5413 *
5414 * @return float
5415 */
5416 public static function calculateFinancialItemAmount($params, $amountParams, $context) {
5417 if (!empty($params['is_quick_config'])) {
5418 $amount = $amountParams['item_amount'];
5419 if (!$amount) {
5420 $amount = $params['total_amount'];
5421 if ($context === NULL) {
5422 $amount -= CRM_Utils_Array::value('tax_amount', $params, 0);
5423 }
5424 }
5425 }
5426 else {
5427 $amount = $amountParams['line_total'];
5428 if ($context == 'changedAmount') {
5429 $amount -= $amountParams['previous_line_total'];
5430 }
5431 $amount *= $amountParams['diff'];
5432 }
5433 return $amount;
5434 }
5435
5436 /**
5437 * Retrieve Sales Tax Financial Accounts.
5438 *
5439 *
5440 * @return array
5441 *
5442 */
5443 public static function getSalesTaxFinancialAccounts() {
5444 $query = "SELECT cfa.id FROM civicrm_entity_financial_account ce
5445 INNER JOIN civicrm_financial_account cfa ON ce.financial_account_id = cfa.id
5446 WHERE `entity_table` = 'civicrm_financial_type' AND cfa.is_tax = 1 AND ce.account_relationship = %1 GROUP BY cfa.id";
5447 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
5448 $queryParams = [1 => [$accountRel, 'Integer']];
5449 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
5450 $financialAccount = [];
5451 while ($dao->fetch()) {
5452 $financialAccount[$dao->id] = $dao->id;
5453 }
5454 return $financialAccount;
5455 }
5456
5457 /**
5458 * Create tax entry in civicrm_entity_financial_trxn table.
5459 *
5460 * @param array $entityParams
5461 *
5462 * @param array $eftParams
5463 *
5464 * @throws \CiviCRM_API3_Exception
5465 */
5466 public static function createProportionalEntry($entityParams, $eftParams) {
5467 $paid = 0;
5468 if ($entityParams['contribution_total_amount'] != 0) {
5469 $paid = $entityParams['line_item_amount'] * ($entityParams['trxn_total_amount'] / $entityParams['contribution_total_amount']);
5470 }
5471 // Record Entity Financial Trxn; CRM-20145
5472 $eftParams['amount'] = $paid;
5473 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
5474 }
5475
5476 /**
5477 * Create array of last financial item id's.
5478 *
5479 * @param int $contributionId
5480 *
5481 * @return array
5482 */
5483 public static function getLastFinancialItemIds($contributionId) {
5484 $sql = "SELECT fi.id, li.price_field_value_id, li.tax_amount, fi.financial_account_id
5485 FROM civicrm_financial_item fi
5486 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
5487 WHERE li.contribution_id = %1";
5488 $dao = CRM_Core_DAO::executeQuery($sql, [
5489 1 => [
5490 $contributionId,
5491 'Integer',
5492 ],
5493 ]);
5494 $ftIds = $taxItems = [];
5495 $salesTaxFinancialAccount = self::getSalesTaxFinancialAccounts();
5496 while ($dao->fetch()) {
5497 /* if sales tax item*/
5498 if (in_array($dao->financial_account_id, $salesTaxFinancialAccount)) {
5499 $taxItems[$dao->price_field_value_id] = [
5500 'financial_item_id' => $dao->id,
5501 'amount' => $dao->tax_amount,
5502 ];
5503 }
5504 else {
5505 $ftIds[$dao->price_field_value_id] = $dao->id;
5506 }
5507 }
5508 return [$ftIds, $taxItems];
5509 }
5510
5511 /**
5512 * Create proportional entries in civicrm_entity_financial_trxn.
5513 *
5514 * @param array $entityParams
5515 *
5516 * @param array $lineItems
5517 *
5518 * @param array $ftIds
5519 *
5520 * @param array $taxItems
5521 *
5522 * @throws \CiviCRM_API3_Exception
5523 */
5524 public static function createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems) {
5525 $eftParams = [
5526 'entity_table' => 'civicrm_financial_item',
5527 'financial_trxn_id' => $entityParams['trxn_id'],
5528 ];
5529 foreach ($lineItems as $key => $value) {
5530 if ($value['qty'] == 0) {
5531 continue;
5532 }
5533 $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']];
5534 $entityParams['line_item_amount'] = $value['line_total'];
5535 self::createProportionalEntry($entityParams, $eftParams);
5536 if (array_key_exists($value['price_field_value_id'], $taxItems)) {
5537 $entityParams['line_item_amount'] = $taxItems[$value['price_field_value_id']]['amount'];
5538 $eftParams['entity_id'] = $taxItems[$value['price_field_value_id']]['financial_item_id'];
5539 self::createProportionalEntry($entityParams, $eftParams);
5540 }
5541 }
5542 }
5543
5544 /**
5545 * Load entities related to the contribution into $this->_relatedObjects.
5546 *
5547 * @param array $ids
5548 *
5549 * @throws \CRM_Core_Exception
5550 */
5551 protected function loadRelatedEntitiesByID($ids) {
5552 $entities = [
5553 'contact' => 'CRM_Contact_BAO_Contact',
5554 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur',
5555 'contributionType' => 'CRM_Financial_BAO_FinancialType',
5556 'financialType' => 'CRM_Financial_BAO_FinancialType',
5557 'contributionPage' => 'CRM_Contribute_BAO_ContributionPage',
5558 ];
5559 foreach ($entities as $entity => $bao) {
5560 if (!empty($ids[$entity])) {
5561 $this->_relatedObjects[$entity] = new $bao();
5562 $this->_relatedObjects[$entity]->id = $ids[$entity];
5563 if (!$this->_relatedObjects[$entity]->find(TRUE)) {
5564 throw new CRM_Core_Exception($entity . ' could not be loaded');
5565 }
5566 }
5567 }
5568 }
5569
5570 /**
5571 * Function to replace contribution tokens.
5572 *
5573 * @param array $contributionIds
5574 *
5575 * @param string $subject
5576 *
5577 * @param array $subjectToken
5578 *
5579 * @param string $text
5580 *
5581 * @param string $html
5582 *
5583 * @param array $messageToken
5584 *
5585 * @param bool $escapeSmarty
5586 *
5587 * @return array
5588 * @throws \CiviCRM_API3_Exception
5589 */
5590 public static function replaceContributionTokens(
5591 $contributionIds,
5592 $subject,
5593 $subjectToken,
5594 $text,
5595 $html,
5596 $messageToken,
5597 $escapeSmarty
5598 ) {
5599 if (empty($contributionIds)) {
5600 return [];
5601 }
5602 $contributionDetails = [];
5603 foreach ($contributionIds as $id) {
5604 $result = self::getContributionTokenValues($id, $messageToken);
5605 $contributionDetails[$result['values'][$result['id']]['contact_id']]['subject'] = CRM_Utils_Token::replaceContributionTokens($subject, $result, FALSE, $subjectToken, FALSE, $escapeSmarty);
5606 $contributionDetails[$result['values'][$result['id']]['contact_id']]['text'] = CRM_Utils_Token::replaceContributionTokens($text, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5607 $contributionDetails[$result['values'][$result['id']]['contact_id']]['html'] = CRM_Utils_Token::replaceContributionTokens($html, $result, FALSE, $messageToken, FALSE, $escapeSmarty);
5608 }
5609 return $contributionDetails;
5610 }
5611
5612 /**
5613 * Get the contribution fields for $id and display labels where
5614 * appropriate (if the token is present).
5615 *
5616 * @param int $id
5617 * @param array $messageToken
5618 * @return array
5619 */
5620 public static function getContributionTokenValues($id, $messageToken) {
5621 if (empty($id)) {
5622 return [];
5623 }
5624 $result = civicrm_api3('Contribution', 'get', ['id' => $id]);
5625 // lab.c.o mail#46 - show labels, not values, for custom fields with option values.
5626 if (!empty($messageToken)) {
5627 foreach ($result['values'][$id] as $fieldName => $fieldValue) {
5628 if (strpos($fieldName, 'custom_') === 0 && array_search($fieldName, $messageToken['contribution']) !== FALSE) {
5629 $result['values'][$id][$fieldName] = CRM_Core_BAO_CustomField::displayValue($result['values'][$id][$fieldName], $fieldName);
5630 }
5631 }
5632 }
5633 return $result;
5634 }
5635
5636 /**
5637 * Get invoice_number for contribution.
5638 *
5639 * @param int $contributionID
5640 *
5641 * @return string
5642 */
5643 public static function getInvoiceNumber($contributionID) {
5644 if ($invoicePrefix = self::checkContributeSettings('invoice_prefix')) {
5645 return $invoicePrefix . $contributionID;
5646 }
5647
5648 return NULL;
5649 }
5650
5651 /**
5652 * Load the values needed for the event message.
5653 *
5654 * @param int $eventID
5655 * @param int $participantID
5656 * @param int|null $contributionID
5657 *
5658 * @return array
5659 * @throws \CRM_Core_Exception
5660 */
5661 protected function loadEventMessageTemplateParams(int $eventID, int $participantID, $contributionID): array {
5662
5663 $eventParams = [
5664 'id' => $eventID,
5665 ];
5666 $values = ['event' => []];
5667
5668 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
5669 // add custom fields for event
5670 $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $eventID);
5671
5672 $eventCustomGroup = [];
5673 foreach ($eventGroupTree as $key => $group) {
5674 if ($key === 'info') {
5675 continue;
5676 }
5677
5678 foreach ($group['fields'] as $k => $customField) {
5679 $groupLabel = $group['title'];
5680 if (!empty($customField['customValue'])) {
5681 foreach ($customField['customValue'] as $customFieldValues) {
5682 $eventCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
5683 }
5684 }
5685 }
5686 }
5687 $values['event']['customGroup'] = $eventCustomGroup;
5688
5689 //get participant details
5690 $participantParams = [
5691 'id' => $participantID,
5692 ];
5693
5694 $values['participant'] = [];
5695
5696 CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds);
5697 // add custom fields for event
5698 $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID);
5699 $participantCustomGroup = [];
5700 foreach ($participantGroupTree as $key => $group) {
5701 if ($key === 'info') {
5702 continue;
5703 }
5704
5705 foreach ($group['fields'] as $k => $customField) {
5706 $groupLabel = $group['title'];
5707 if (!empty($customField['customValue'])) {
5708 foreach ($customField['customValue'] as $customFieldValues) {
5709 $participantCustomGroup[$groupLabel][$customField['label']] = $customFieldValues['data'] ?? NULL;
5710 }
5711 }
5712 }
5713 }
5714 $values['participant']['customGroup'] = $participantCustomGroup;
5715
5716 //get location details
5717 $locationParams = [
5718 'entity_id' => $eventID,
5719 'entity_table' => 'civicrm_event',
5720 ];
5721 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
5722
5723 $ufJoinParams = [
5724 'entity_table' => 'civicrm_event',
5725 'entity_id' => $eventID,
5726 'module' => 'CiviEvent',
5727 ];
5728
5729 list($custom_pre_id,
5730 $custom_post_ids
5731 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
5732
5733 $values['custom_pre_id'] = $custom_pre_id;
5734 $values['custom_post_id'] = $custom_post_ids;
5735
5736 // set lineItem for event contribution
5737 if ($contributionID) {
5738 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($contributionID);
5739 if (!empty($participantIds)) {
5740 foreach ($participantIds as $pIDs) {
5741 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
5742 if (!CRM_Utils_System::isNull($lineItem)) {
5743 $values['lineItem'][] = $lineItem;
5744 }
5745 }
5746 }
5747 }
5748 return $values;
5749 }
5750
5751 }