3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Contribute_BAO_ContributionRecur
extends CRM_Contribute_DAO_ContributionRecur
{
20 * Create recurring contribution.
22 * @param array $params
23 * (reference ) an assoc array of name/value pairs.
26 * activity contact object
28 public static function create(&$params) {
29 return self
::add($params);
33 * Takes an associative array and creates a contribution object.
35 * the function extract all the params it needs to initialize the create a
36 * contribution object. the params array could contain additional unused name/value
39 * @param array $params
40 * (reference ) an assoc array of name/value pairs.
42 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
43 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
45 public static function add(&$params) {
46 if (!empty($params['id'])) {
47 CRM_Utils_Hook
::pre('edit', 'ContributionRecur', $params['id'], $params);
50 CRM_Utils_Hook
::pre('create', 'ContributionRecur', NULL, $params);
53 // make sure we're not creating a new recurring contribution with the same transaction ID
54 // or invoice ID as an existing recurring contribution
56 if (self
::checkDuplicate($params, $duplicates)) {
57 $error = CRM_Core_Error
::singleton();
58 $d = implode(', ', $duplicates);
59 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
62 "Found matching recurring contribution(s): $d"
67 $recurring = new CRM_Contribute_BAO_ContributionRecur();
68 $recurring->copyValues($params);
69 $recurring->id
= $params['id'] ??
NULL;
71 // set currency for CRM-1496
72 if (empty($params['id']) && !isset($recurring->currency
)) {
73 $config = CRM_Core_Config
::singleton();
74 $recurring->currency
= $config->defaultCurrency
;
78 if (!empty($params['id'])) {
79 CRM_Utils_Hook
::post('edit', 'ContributionRecur', $recurring->id
, $recurring);
82 CRM_Utils_Hook
::post('create', 'ContributionRecur', $recurring->id
, $recurring);
85 if (!empty($params['custom']) &&
86 is_array($params['custom'])
88 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution_recur', $recurring->id
);
95 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
97 * @param array $params
98 * (reference ) an assoc array of name/value pairs.
99 * @param array $duplicates
100 * (reference ) store ids of duplicate contributions.
103 * true if duplicate, false otherwise
105 public static function checkDuplicate($params, &$duplicates) {
106 $id = $params['id'] ??
NULL;
107 $trxn_id = $params['trxn_id'] ??
NULL;
108 $invoice_id = $params['invoice_id'] ??
NULL;
114 $clause[] = "trxn_id = %1";
115 $params[1] = [$trxn_id, 'String'];
119 $clause[] = "invoice_id = %2";
120 $params[2] = [$invoice_id, 'String'];
123 if (empty($clause)) {
127 $clause = implode(' OR ', $clause);
129 $clause = "( $clause ) AND id != %3";
130 $params[3] = [$id, 'Integer'];
133 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
134 $dao = CRM_Core_DAO
::executeQuery($query, $params);
136 while ($dao->fetch()) {
137 $duplicates[] = $dao->id
;
144 * Get the payment processor (array) for a recurring processor.
150 public static function getPaymentProcessor($id) {
151 $paymentProcessorID = self
::getPaymentProcessorID($id);
152 return CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID);
156 * Get the processor object for the recurring contribution record.
160 * @return CRM_Core_Payment|NULL
161 * Returns a processor object or NULL if the processor is disabled.
162 * Note this returns the 'Manual' processor object if no processor is attached
163 * (since it still makes sense to update / cancel
165 public static function getPaymentProcessorObject($id) {
166 $processor = self
::getPaymentProcessor($id);
167 return is_array($processor) ?
$processor['object'] : NULL;
171 * Get the payment processor for the given recurring contribution.
173 * @param int $recurID
176 * Payment processor id. If none found return 0 which represents the
177 * pseudo processor used for pay-later.
179 public static function getPaymentProcessorID($recurID) {
180 $recur = civicrm_api3('ContributionRecur', 'getsingle', [
182 'return' => ['payment_processor_id'],
184 return (int) ($recur['payment_processor_id'] ??
0);
188 * Get the number of installment done/completed for each recurring contribution.
191 * (reference ) an array of recurring contribution ids.
194 * an array of recurring ids count
196 public static function getCount(&$ids) {
197 $recurID = implode(',', $ids);
201 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
202 FROM civicrm_contribution
203 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
204 GROUP BY contribution_recur_id";
206 $res = CRM_Core_DAO
::executeQuery($query);
208 while ($res->fetch()) {
209 $totalCount[$res->contribution_recur_id
] = $res->commpleted
;
215 * Delete Recurring contribution.
217 * @param int $recurId
221 public static function deleteRecurContribution($recurId) {
227 $recur = new CRM_Contribute_DAO_ContributionRecur();
228 $recur->id
= $recurId;
229 $result = $recur->delete();
235 * Cancel Recurring contribution.
237 * @param array $params
238 * Recur contribution params
242 public static function cancelRecurContribution($params) {
243 if (is_numeric($params)) {
244 CRM_Core_Error
::deprecatedFunctionWarning('You are using a BAO function whose signature has changed. Please use the ContributionRecur.cancel api');
245 $params = ['id' => $params];
247 $recurId = $params['id'];
252 'subject' => !empty($params['membership_id']) ?
ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'),
253 'details' => $params['processor_message'] ??
NULL,
256 $cancelledId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Cancelled');
257 $recur = new CRM_Contribute_DAO_ContributionRecur();
258 $recur->id
= $recurId;
259 $recur->whereAdd("contribution_status_id != $cancelledId");
261 if ($recur->find(TRUE)) {
262 $transaction = new CRM_Core_Transaction();
263 $recur->contribution_status_id
= $cancelledId;
264 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
265 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
266 $recur->modified_date
= CRM_Utils_Date
::isoToMysql($recur->modified_date
);
267 $recur->cancel_reason
= $params['cancel_reason'] ??
NULL;
268 $recur->cancel_date
= date('YmdHis');
271 // @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
272 $dao = CRM_Contribute_BAO_ContributionRecur
::getSubscriptionDetails($recurId);
273 if ($dao && $dao->recur_id
) {
274 $details = $activityParams['details'] ??
NULL;
275 if ($dao->auto_renew
&& $dao->membership_id
) {
276 // its auto-renewal membership mode
277 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
278 $membershipType = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id
, 'membership_type_id');
279 $membershipType = $membershipTypes[$membershipType] ??
NULL;
281 <br/>' . ts('Automatic renewal of %1 membership cancelled.', [1 => $membershipType]);
284 $details .= '<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', [
286 2 => $dao->frequency_interval
,
287 3 => $dao->frequency_unit
,
291 'source_contact_id' => $dao->contact_id
,
292 'source_record_id' => $dao->recur_id
,
293 'activity_type_id' => 'Cancel Recurring Contribution',
294 'subject' => CRM_Utils_Array
::value('subject', $activityParams, ts('Recurring contribution cancelled')),
295 'details' => $details,
296 'status_id' => 'Completed',
299 $cid = CRM_Core_Session
::singleton()->get('userID');
301 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
302 $activityParams['source_contact_id'] = $cid;
304 civicrm_api3('Activity', 'create', $activityParams);
307 $transaction->commit();
311 // if already cancelled, return true
313 $recur->whereAdd("contribution_status_id = $cancelledId");
314 if ($recur->find(TRUE)) {
323 * @param int $entityID
324 * @param string $entity
326 * @return null|Object
328 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
330 SELECT rec.id as recur_id,
331 rec.processor_id as subscription_id,
332 rec.frequency_interval,
340 rec.financial_type_id,
341 rec.next_sched_contribution_date,
342 rec.failure_retry_date,
344 con.id as contribution_id,
345 con.contribution_page_id,
349 if ($entity == 'recur') {
351 FROM civicrm_contribution_recur rec
352 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
353 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
356 elseif ($entity == 'contribution') {
358 FROM civicrm_contribution con
359 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
360 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
363 elseif ($entity == 'membership') {
365 FROM civicrm_membership_payment mp
366 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
367 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
368 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
369 WHERE mp.membership_id = %1";
372 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$entityID, 'Integer']]);
382 * Does the recurring contribution support financial type change.
384 * This is conditional on there being only one line item or if there are no contributions as yet.
386 * (This second is a bit of an unusual condition but might occur in the context of a
392 public static function supportsFinancialTypeChange($id) {
393 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
394 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
395 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
398 $contribution = self
::getTemplateContribution($id);
399 return CRM_Contribute_BAO_Contribution
::isSingleLineItem($contribution['id']);
403 * Get the contribution to be used as the template for later contributions.
405 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
408 * @param array $overrides
409 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
413 * @throws \CiviCRM_API3_Exception
414 * @throws \Civi\API\Exception\UnauthorizedException
415 * @throws \API_Exception
417 public static function getTemplateContribution($id, $overrides = []) {
418 // use api3 because api4 doesn't handle ContributionRecur yet...
419 $is_test = civicrm_api3('ContributionRecur', 'getvalue', [
420 'return' => "is_test",
423 // First look for new-style template contribution with is_template=1
424 $templateContributions = \Civi\Api4\Contribution
::get()
425 ->setCheckPermissions(FALSE)
426 ->addWhere('contribution_recur_id', '=', $id)
427 ->addWhere('is_template', '=', 1)
428 ->addWhere('is_test', '=', $is_test)
429 ->addOrderBy('id', 'DESC')
432 if (!$templateContributions->count()) {
433 // Fall back to old style template contributions
434 $templateContributions = \Civi\Api4\Contribution
::get()
435 ->setCheckPermissions(FALSE)
436 ->addWhere('contribution_recur_id', '=', $id)
437 ->addWhere('is_test', '=', $is_test)
438 ->addOrderBy('id', 'DESC')
442 if ($templateContributions->count()) {
443 $templateContribution = $templateContributions->first();
444 $result = array_merge($templateContribution, $overrides);
445 $result['line_item'] = CRM_Contribute_BAO_ContributionRecur
::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
451 public static function setSubscriptionContext() {
452 // handle context redirection for subscription url
453 $session = CRM_Core_Session
::singleton();
454 if ($session->get('userID')) {
456 $cid = CRM_Utils_Request
::retrieve('cid', 'Integer');
457 $mid = CRM_Utils_Request
::retrieve('mid', 'Integer');
458 $qfkey = CRM_Utils_Request
::retrieve('key', 'String');
459 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric');
463 $url = CRM_Utils_System
::url('civicrm/contact/view',
464 "reset=1&selectedChild=contribute&cid={$cid}"
469 $url = CRM_Utils_System
::url('civicrm/contact/view',
470 "reset=1&selectedChild=member&cid={$cid}"
475 $url = CRM_Utils_System
::url('civicrm/user', "reset=1&id={$cid}");
482 $url = CRM_Utils_System
::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
486 $url = CRM_Utils_System
::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
491 $session->pushUserContext($url);
497 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
499 * @param array $fields
500 * The input form values.
501 * @param array $files
502 * The uploaded files if any.
503 * @param CRM_Core_Form $self
504 * @param array $errors
506 public static function validateRecurContribution($fields, $files, $self, &$errors) {
507 if (!empty($fields['is_recur'])) {
508 if ($fields['frequency_interval'] <= 0) {
509 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
511 if ($fields['frequency_unit'] == '0') {
512 $errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
518 * Send start or end notification for recurring payments.
521 * @param CRM_Contribute_BAO_ContributionRecur $recur
522 * @param bool $isFirstOrLastRecurringPayment
524 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
525 if ($isFirstOrLastRecurringPayment) {
526 $autoRenewMembership = FALSE;
528 isset($ids['membership']) && $ids['membership']
530 $autoRenewMembership = TRUE;
533 //send recurring Notification email for user
534 CRM_Contribute_BAO_ContributionPage
::recurringNotify($isFirstOrLastRecurringPayment,
536 $ids['contributionPage'],
544 * Copy custom data of the initial contribution into its recurring contributions.
546 * @param int $recurId
547 * @param int $targetContributionId
549 public static function copyCustomValues($recurId, $targetContributionId) {
550 if ($recurId && $targetContributionId) {
551 // get the initial contribution id of recur id
552 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
554 // if the same contribution is being processed then return
555 if ($sourceContributionId == $targetContributionId) {
558 // check if proper recurring contribution record is being processed
559 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
560 if ($targetConRecurId != $recurId) {
565 $extends = ['Contribution'];
566 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
568 foreach ($groupTree as $groupID => $group) {
569 $table[$groupTree[$groupID]['table_name']] = ['entity_id'];
570 foreach ($group['fields'] as $fieldID => $field) {
571 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
575 foreach ($table as $tableName => $tableColumns) {
576 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
577 $tableColumns[0] = $targetContributionId;
578 $select = 'SELECT ' . implode(', ', $tableColumns);
579 $from = ' FROM ' . $tableName;
580 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
581 $query = $insert . $select . $from . $where;
582 CRM_Core_DAO
::executeQuery($query);
589 * Add soft credit to for recurring payment.
591 * copy soft credit record of first recurring contribution.
592 * and add new soft credit against $targetContributionId
594 * @param int $recurId
595 * @param int $targetContributionId
597 public static function addrecurSoftCredit($recurId, $targetContributionId) {
598 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
599 $soft_contribution->contribution_id
= CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
601 // Check if first recurring contribution has any associated soft credit.
602 if ($soft_contribution->find(TRUE)) {
603 $soft_contribution->contribution_id
= $targetContributionId;
604 unset($soft_contribution->id
);
605 $soft_contribution->save();
610 * Add line items for recurring contribution.
612 * @param int $recurId
613 * @param \CRM_Contribute_BAO_Contribution $contribution
617 public static function addRecurLineItems($recurId, $contribution) {
618 $foundLineItems = FALSE;
620 $lineSets = self
::calculateRecurLineItems($recurId, $contribution->total_amount
, $contribution->financial_type_id
);
621 foreach ($lineSets as $lineItems) {
622 if (!empty($lineItems)) {
623 foreach ($lineItems as $key => $value) {
624 if ($value['entity_table'] == 'civicrm_membership') {
626 // @todo this should be done by virtue of editing the line item as this link
627 // is deprecated. This may be the case but needs testing.
628 civicrm_api3('membership_payment', 'create', [
629 'membership_id' => $value['entity_id'],
630 'contribution_id' => $contribution->id
,
631 'is_transactional' => FALSE,
634 catch (CiviCRM_API3_Exception
$e) {
635 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
636 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
640 $foundLineItems = TRUE;
643 if (!$foundLineItems) {
644 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
650 * Update pledge associated with a recurring contribution.
652 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
654 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
655 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
656 * it should be assumed they
657 * do so with the intention that all payments will be linked
659 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
660 * If not the contribution will also need to be linked to the pledge
662 * @param int $contributionID
663 * @param int $contributionRecurID
664 * @param int $contributionStatusID
665 * @param float $contributionAmount
667 * @throws \CiviCRM_API3_Exception
669 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
670 $returnProperties = ['id', 'pledge_id'];
671 $paymentDetails = $paymentIDs = [];
673 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
674 $paymentDetails, $returnProperties
677 foreach ($paymentDetails as $key => $value) {
678 $paymentIDs[] = $value['id'];
679 $pledgeId = $value['pledge_id'];
683 //payment is not already linked - if it is linked with a pledge we need to create a link.
684 // return if it is not recurring contribution
685 if (!$contributionRecurID) {
689 $relatedContributions = new CRM_Contribute_DAO_Contribution();
690 $relatedContributions->contribution_recur_id
= $contributionRecurID;
691 $relatedContributions->find();
693 while ($relatedContributions->fetch()) {
694 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
695 $paymentDetails, $returnProperties
699 if (empty($paymentDetails)) {
700 // payment is not linked with a pledge and neither are any other contributions on this
704 foreach ($paymentDetails as $key => $value) {
705 $pledgeId = $value['pledge_id'];
708 // we have a pledge now we need to get the oldest unpaid payment
709 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
710 if (empty($paymentDetails['id'])) {
711 // we can assume this pledge is now completed
712 // return now so we don't create a core error & roll back
715 $paymentDetails['contribution_id'] = $contributionID;
716 $paymentDetails['status_id'] = $contributionStatusID;
717 $paymentDetails['actual_amount'] = $contributionAmount;
719 // put contribution against it
720 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
721 $paymentIDs[] = $payment['id'];
724 // update pledge and corresponding payment statuses
725 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
726 NULL, $contributionAmount
731 * @param CRM_Core_Form $form
733 public static function recurringContribution(&$form) {
734 // Recurring contribution fields
735 foreach (self
::getRecurringFields() as $key) {
736 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues
) &&
737 !CRM_Utils_System
::isNull(CRM_Utils_Array
::value($key, $form->_formValues
))
739 $form->assign('contribution_recur_pane_open', TRUE);
742 // If data has been entered for a recurring field, tell the tpl layer to open the pane
743 if (!empty($form->_formValues
) && !empty($form->_formValues
[$key . '_relative']) ||
!empty($form->_formValues
[$key . '_low']) ||
!empty($form->_formValues
[$key . '_high'])) {
744 $form->assign('contribution_recur_pane_open', TRUE);
749 // If values have been supplied for recurring contribution fields, open the recurring contributions pane.
750 foreach (['contribution_status_id', 'payment_processor_id', 'processor_id', 'trxn_id'] as $fieldName) {
751 if (!empty($form->_formValues
['contribution_recur_' . $fieldName])) {
752 $form->assign('contribution_recur_pane_open', TRUE);
757 // Add field to check if payment is made for recurring contribution
758 $recurringPaymentOptions = [
759 1 => ts('All recurring contributions'),
760 2 => ts('Recurring contributions with at least one payment'),
762 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, ['allowClear' => TRUE]);
764 // Add field for contribution status
765 $form->addSelect('contribution_recur_contribution_status_id',
766 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search')]
769 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
770 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
772 $paymentProcessorOpts = CRM_Contribute_BAO_ContributionRecur
::buildOptions('payment_processor_id', 'get');
773 $form->add('select', 'contribution_recur_payment_processor_id', ts('Payment Processor ID'), $paymentProcessorOpts, FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']);
775 CRM_Core_BAO_Query
::addCustomFormFields($form, ['ContributionRecur']);
780 * Get the metadata for fields to be included on the search form.
782 * @throws \CiviCRM_API3_Exception
784 public static function getContributionRecurSearchFieldMetadata() {
786 'contribution_recur_start_date',
787 'contribution_recur_next_sched_contribution_date',
788 'contribution_recur_cancel_date',
789 'contribution_recur_end_date',
790 'contribution_recur_create_date',
791 'contribution_recur_modified_date',
792 'contribution_recur_failure_retry_date',
794 $metadata = civicrm_api3('ContributionRecur', 'getfields', [])['values'];
795 return array_intersect_key($metadata, array_flip($fields));
799 * Get fields for recurring contributions.
803 public static function getRecurringFields() {
805 'contribution_recur_payment_made',
806 'contribution_recur_start_date',
807 'contribution_recur_next_sched_contribution_date',
808 'contribution_recur_cancel_date',
809 'contribution_recur_end_date',
810 'contribution_recur_create_date',
811 'contribution_recur_modified_date',
812 'contribution_recur_failure_retry_date',
817 * Update recurring contribution based on incoming payment.
819 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
821 * @param int $recurringContributionID
822 * @param string $paymentStatus
823 * Payment status - this correlates to the machine name of the contribution status ID ie
826 * @param string $effectiveDate
828 * @throws \CiviCRM_API3_Exception
830 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
832 $effectiveDate = $effectiveDate ?
date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
833 if (!in_array($paymentStatus, ['Completed', 'Failed'])) {
837 'id' => $recurringContributionID,
839 'contribution_status_id',
840 'next_sched_contribution_date',
842 'frequency_interval',
848 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
850 if ($paymentStatus == 'Completed'
851 && CRM_Contribute_PseudoConstant
::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
852 $params['contribution_status_id'] = 'In Progress';
854 if ($paymentStatus == 'Failed') {
855 $params['failure_count'] = $existing['failure_count'];
857 $params['modified_date'] = date('Y-m-d H:i:s');
859 if (!empty($existing['installments']) && self
::isComplete($recurringContributionID, $existing['installments'])) {
860 $params['contribution_status_id'] = 'Completed';
863 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
864 // the scheduled date themselves as core did not previously provide any help.
865 if (empty($existing['next_sched_contribution_date']) ||
strtotime($existing['next_sched_contribution_date']) ==
866 strtotime($effectiveDate)) {
867 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
870 civicrm_api3('ContributionRecur', 'create', $params);
874 * Is this recurring contribution now complete.
876 * Have all the payments expected been received now.
878 * @param int $recurringContributionID
879 * @param int $installments
883 protected static function isComplete($recurringContributionID, $installments) {
884 $paidInstallments = CRM_Core_DAO
::singleValueQuery(
885 'SELECT count(*) FROM civicrm_contribution
886 WHERE contribution_recur_id = %1
887 AND contribution_status_id = ' . CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
888 [1 => [$recurringContributionID, 'Integer']]
890 if ($paidInstallments >= $installments) {
897 * Calculate line items for the relevant recurring calculation.
899 * @param int $recurId
900 * @param string $total_amount
901 * @param int $financial_type_id
905 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
906 $originalContribution = civicrm_api3('Contribution', 'getsingle', [
907 'contribution_recur_id' => $recurId,
908 'contribution_test' => '',
909 'options' => ['limit' => 1],
910 'return' => ['id', 'financial_type_id'],
912 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContribution['id']);
914 if (count($lineItems) == 1) {
915 foreach ($lineItems as $index => $lineItem) {
916 if ($lineItem['financial_type_id'] != $originalContribution['financial_type_id']) {
917 // CRM-20685, Repeattransaction produces incorrect Financial Type ID (in specific circumstance) - if number of lineItems = 1, So this conditional will set the financial_type_id as the original if line_item and contribution comes with different data.
918 $financial_type_id = $lineItem['financial_type_id'];
920 if ($financial_type_id) {
921 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
922 $lineItem['financial_type_id'] = $financial_type_id;
924 $taxAmountMatches = FALSE;
925 if ((!empty($lineItem['tax_amount']) && ($lineItem['line_total'] +
$lineItem['tax_amount']) == $total_amount)) {
926 $taxAmountMatches = TRUE;
928 if ($lineItem['line_total'] != $total_amount && !$taxAmountMatches) {
929 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
930 // if there is only one line item, and the UI should prevent this situation for those with more than one.
931 $lineItem['line_total'] = $total_amount;
932 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
934 $priceField = new CRM_Price_DAO_PriceField();
935 $priceField->id
= $lineItem['price_field_id'];
936 $priceField->find(TRUE);
937 $lineSets[$priceField->price_set_id
][$lineItem['price_field_id']] = $lineItem;
940 // CRM-19309 if more than one then just pass them through:
941 elseif (count($lineItems) > 1) {
942 foreach ($lineItems as $index => $lineItem) {
943 $lineSets[$index][$lineItem['price_field_id']] = $lineItem;
951 * Returns array with statuses that are considered to make a recurring contribution inactive.
955 public static function getInactiveStatuses() {
956 return ['Cancelled', 'Failed', 'Completed'];
962 public static function buildOptions($fieldName, $context = NULL, $props = []) {
964 switch ($fieldName) {
965 case 'payment_processor_id':
966 if (isset(\Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'])) {
967 return \Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'];
969 $baoName = 'CRM_Contribute_BAO_ContributionRecur';
970 $params['condition']['test'] = "is_test = 0";
971 $liveProcessors = CRM_Core_PseudoConstant
::get($baoName, $fieldName, $params, $context);
972 $params['condition']['test'] = "is_test != 0";
973 $testProcessors = CRM_Core_PseudoConstant
::get($baoName, $fieldName, $params, $context);
974 foreach ($testProcessors as $key => $value) {
975 if ($context === 'validate') {
976 // @fixme: Ideally the names would be different in the civicrm_payment_processor table but they are not.
977 // So we append '_test' to the test one so that we can select the correct processor by name using the ContributionRecur.create API.
978 $testProcessors[$key] = $value . '_test';
981 $testProcessors[$key] = CRM_Core_TestEntity
::appendTestText($value);
984 $allProcessors = $liveProcessors +
$testProcessors;
985 ksort($allProcessors);
986 \Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'] = $allProcessors;
987 return $allProcessors;
989 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);