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 +--------------------------------------------------------------------+
12 use Civi\Api4\Contribution
;
13 use Civi\Api4\ContributionRecur
;
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 class CRM_Contribute_BAO_ContributionRecur
extends CRM_Contribute_DAO_ContributionRecur
{
23 * Create recurring contribution.
25 * @param array $params
26 * (reference ) an assoc array of name/value pairs.
29 * activity contact object
31 public static function create(&$params) {
32 return self
::add($params);
36 * Takes an associative array and creates a contribution object.
38 * the function extract all the params it needs to initialize the create a
39 * contribution object. the params array could contain additional unused name/value
42 * @param array $params
43 * (reference ) an assoc array of name/value pairs.
45 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
46 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
48 public static function add(&$params) {
49 if (!empty($params['id'])) {
50 CRM_Utils_Hook
::pre('edit', 'ContributionRecur', $params['id'], $params);
53 CRM_Utils_Hook
::pre('create', 'ContributionRecur', NULL, $params);
56 // make sure we're not creating a new recurring contribution with the same transaction ID
57 // or invoice ID as an existing recurring contribution
59 if (self
::checkDuplicate($params, $duplicates)) {
60 $error = CRM_Core_Error
::singleton();
61 $d = implode(', ', $duplicates);
62 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
65 "Found matching recurring contribution(s): $d"
70 $recurring = new CRM_Contribute_BAO_ContributionRecur();
71 $recurring->copyValues($params);
72 $recurring->id
= $params['id'] ??
NULL;
74 // set currency for CRM-1496
75 if (empty($params['id']) && !isset($recurring->currency
)) {
76 $config = CRM_Core_Config
::singleton();
77 $recurring->currency
= $config->defaultCurrency
;
81 if (!empty($params['id'])) {
82 CRM_Utils_Hook
::post('edit', 'ContributionRecur', $recurring->id
, $recurring);
85 CRM_Utils_Hook
::post('create', 'ContributionRecur', $recurring->id
, $recurring);
88 if (!empty($params['custom']) &&
89 is_array($params['custom'])
91 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution_recur', $recurring->id
);
98 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
100 * @param array $params
101 * (reference ) an assoc array of name/value pairs.
102 * @param array $duplicates
103 * (reference ) store ids of duplicate contributions.
106 * true if duplicate, false otherwise
108 public static function checkDuplicate($params, &$duplicates) {
109 $id = $params['id'] ??
NULL;
110 $trxn_id = $params['trxn_id'] ??
NULL;
111 $invoice_id = $params['invoice_id'] ??
NULL;
117 $clause[] = "trxn_id = %1";
118 $params[1] = [$trxn_id, 'String'];
122 $clause[] = "invoice_id = %2";
123 $params[2] = [$invoice_id, 'String'];
126 if (empty($clause)) {
130 $clause = implode(' OR ', $clause);
132 $clause = "( $clause ) AND id != %3";
133 $params[3] = [$id, 'Integer'];
136 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
137 $dao = CRM_Core_DAO
::executeQuery($query, $params);
139 while ($dao->fetch()) {
140 $duplicates[] = $dao->id
;
147 * Get the payment processor (array) for a recurring processor.
153 public static function getPaymentProcessor($id) {
154 $paymentProcessorID = self
::getPaymentProcessorID($id);
155 return CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID);
159 * Get the processor object for the recurring contribution record.
163 * @return CRM_Core_Payment|NULL
164 * Returns a processor object or NULL if the processor is disabled.
165 * Note this returns the 'Manual' processor object if no processor is attached
166 * (since it still makes sense to update / cancel
168 public static function getPaymentProcessorObject($id) {
169 CRM_Core_Error
::deprecatedFunctionWarning('Use Civi\Payment\System');
170 $processor = self
::getPaymentProcessor($id);
171 return is_array($processor) ?
$processor['object'] : NULL;
175 * Get the payment processor for the given recurring contribution.
177 * @param int $recurID
180 * Payment processor id. If none found return 0 which represents the
181 * pseudo processor used for pay-later.
183 public static function getPaymentProcessorID($recurID) {
184 $recur = civicrm_api3('ContributionRecur', 'getsingle', [
186 'return' => ['payment_processor_id'],
188 return (int) ($recur['payment_processor_id'] ??
0);
192 * Get the number of installment done/completed for each recurring contribution.
195 * (reference ) an array of recurring contribution ids.
198 * an array of recurring ids count
200 public static function getCount(&$ids) {
201 $recurID = implode(',', $ids);
205 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
206 FROM civicrm_contribution
207 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
208 GROUP BY contribution_recur_id";
210 $res = CRM_Core_DAO
::executeQuery($query);
212 while ($res->fetch()) {
213 $totalCount[$res->contribution_recur_id
] = $res->commpleted
;
219 * Delete Recurring contribution.
221 * @param int $recurId
225 public static function deleteRecurContribution($recurId) {
231 $recur = new CRM_Contribute_DAO_ContributionRecur();
232 $recur->id
= $recurId;
233 $result = $recur->delete();
239 * Cancel Recurring contribution.
241 * @param array $params
242 * Recur contribution params
246 public static function cancelRecurContribution($params) {
247 if (is_numeric($params)) {
248 CRM_Core_Error
::deprecatedFunctionWarning('You are using a BAO function whose signature has changed. Please use the ContributionRecur.cancel api');
249 $params = ['id' => $params];
251 $recurId = $params['id'];
256 'subject' => !empty($params['membership_id']) ?
ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'),
257 'details' => $params['processor_message'] ??
NULL,
260 $cancelledId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Cancelled');
261 $recur = new CRM_Contribute_DAO_ContributionRecur();
262 $recur->id
= $recurId;
263 $recur->whereAdd("contribution_status_id != $cancelledId");
265 if ($recur->find(TRUE)) {
266 $transaction = new CRM_Core_Transaction();
267 $recur->contribution_status_id
= $cancelledId;
268 $recur->cancel_reason
= $params['cancel_reason'] ??
NULL;
269 $recur->cancel_date
= date('YmdHis');
272 // @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
273 $dao = CRM_Contribute_BAO_ContributionRecur
::getSubscriptionDetails($recurId);
274 if ($dao && $dao->recur_id
) {
275 $details = $activityParams['details'] ??
NULL;
276 if ($dao->auto_renew
&& $dao->membership_id
) {
277 // its auto-renewal membership mode
278 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
279 $membershipType = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id
, 'membership_type_id');
280 $membershipType = $membershipTypes[$membershipType] ??
NULL;
282 <br/>' . ts('Automatic renewal of %1 membership cancelled.', [1 => $membershipType]);
285 $details .= '<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', [
287 2 => $dao->frequency_interval
,
288 3 => $dao->frequency_unit
,
292 'source_contact_id' => $dao->contact_id
,
293 'source_record_id' => $dao->recur_id
,
294 'activity_type_id' => 'Cancel Recurring Contribution',
295 'subject' => CRM_Utils_Array
::value('subject', $activityParams, ts('Recurring contribution cancelled')),
296 'details' => $details,
297 'status_id' => 'Completed',
300 $cid = CRM_Core_Session
::singleton()->get('userID');
302 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
303 $activityParams['source_contact_id'] = $cid;
305 civicrm_api3('Activity', 'create', $activityParams);
308 $transaction->commit();
312 // if already cancelled, return true
314 $recur->whereAdd("contribution_status_id = $cancelledId");
315 if ($recur->find(TRUE)) {
324 * @param int $entityID
325 * @param string $entity
327 * @return null|Object
329 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
330 // Note: processor_id used to be aliased as subscription_id so we include it here
331 // both as processor_id and subscription_id for legacy compatibility.
333 SELECT rec.id as recur_id,
334 rec.processor_id as subscription_id,
336 rec.frequency_interval,
344 rec.financial_type_id,
345 rec.next_sched_contribution_date,
346 rec.failure_retry_date,
348 con.id as contribution_id,
349 con.contribution_page_id,
353 if ($entity == 'recur') {
355 FROM civicrm_contribution_recur rec
356 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
357 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
360 elseif ($entity == 'contribution') {
362 FROM civicrm_contribution con
363 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
364 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
367 elseif ($entity == 'membership') {
369 FROM civicrm_membership_payment mp
370 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
371 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
372 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
373 WHERE mp.membership_id = %1";
376 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$entityID, 'Integer']]);
386 * Does the recurring contribution support financial type change.
388 * This is conditional on there being only one line item or if there are no contributions as yet.
390 * (This second is a bit of an unusual condition but might occur in the context of a
396 public static function supportsFinancialTypeChange($id) {
397 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
398 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
399 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
402 $contribution = self
::getTemplateContribution($id);
403 return CRM_Contribute_BAO_Contribution
::isSingleLineItem($contribution['id']);
407 * Create a template contribution based on the first contribution of an
408 * recurring contribution.
409 * When a template contribution already exists this function will not try to create
411 * This way we make sure only one template contribution exists.
415 * @throws \API_Exception
416 * @throws \CiviCRM_API3_Exception
417 * @throws \Civi\API\Exception\UnauthorizedException
418 * @return int|NULL the ID of the newly created template contribution.
420 public static function ensureTemplateContributionExists(int $id) {
421 // Check if a template contribution already exists.
422 $templateContributions = Contribution
::get(FALSE)
423 ->addWhere('contribution_recur_id', '=', $id)
424 ->addWhere('is_template', '=', 1)
425 // we need this line otherwise the is test contribution don't work.
426 ->addWhere('is_test', 'IN', [0, 1])
427 ->addOrderBy('receive_date', 'DESC')
430 if ($templateContributions->count()) {
431 // A template contribution already exists.
432 // Skip the creation of a new one.
433 return $templateContributions->first()['id'];
436 // Retrieve the most recently added contribution
437 $mostRecentContribution = Contribution
::get(FALSE)
438 ->addWhere('contribution_recur_id', '=', $id)
439 ->addWhere('is_template', '=', 0)
440 // we need this line otherwise the is test contribution don't work.
441 ->addWhere('is_test', 'IN', [0, 1])
442 ->addOrderBy('receive_date', 'DESC')
446 if (!$mostRecentContribution) {
447 // No first contribution is found.
451 $order = new CRM_Financial_BAO_Order();
452 $order->setTemplateContributionID($mostRecentContribution['id']);
453 $order->setOverrideFinancialTypeID($overrides['financial_type_id'] ??
NULL);
454 $order->setOverridableFinancialTypeID($mostRecentContribution['financial_type_id']);
455 $order->setOverrideTotalAmount($mostRecentContribution['total_amount'] ??
NULL);
456 $order->setIsPermitOverrideFinancialTypeForMultipleLines(FALSE);
457 $line_items = $order->getLineItems();
458 $mostRecentContribution['line_item'][$order->getPriceSetID()] = $line_items;
460 // If the template contribution was made on-behalf then add the
461 // relevant values to ensure the activity reflects that.
462 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($mostRecentContribution['id']);
464 $templateContributionParams = [];
465 $templateContributionParams['is_test'] = $mostRecentContribution['is_test'];
466 $templateContributionParams['is_template'] = '1';
467 $templateContributionParams['skipRecentView'] = TRUE;
468 $templateContributionParams['contribution_recur_id'] = $id;
469 $templateContributionParams['line_item'] = $mostRecentContribution['line_item'];
470 $templateContributionParams['status_id'] = 'Template';
471 foreach (['contact_id', 'campaign_id', 'financial_type_id', 'currency', 'source', 'amount_level', 'address_id', 'on_behalf', 'source_contact_id', 'tax_amount', 'contribution_page_id', 'total_amount'] as $fieldName) {
472 if (isset($mostRecentContribution[$fieldName])) {
473 $templateContributionParams[$fieldName] = $mostRecentContribution[$fieldName];
476 if (!empty($relatedContact['individual_id'])) {
477 $templateContributionParams['on_behalf'] = TRUE;
478 $templateContributionParams['source_contact_id'] = $relatedContact['individual_id'];
480 $templateContributionParams['source'] = $templateContributionParams['source'] ??
ts('Recurring contribution');
481 $templateContribution = civicrm_api3('Contribution', 'create', $templateContributionParams);
482 $temporaryObject = new CRM_Contribute_BAO_Contribution();
483 $temporaryObject->copyCustomFields($mostRecentContribution['id'], $templateContribution['id']);
484 // Add new soft credit against current $contribution.
485 CRM_Contribute_BAO_ContributionRecur
::addrecurSoftCredit($templateContributionParams['contribution_recur_id'], $templateContribution['id']);
486 return $templateContribution['id'];
490 * Get the contribution to be used as the template for later contributions.
492 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
495 * @param array $overrides
496 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
500 * @throws \API_Exception
502 public static function getTemplateContribution(int $id, $overrides = []): array {
503 $recurFields = ['is_test', 'financial_type_id', 'total_amount', 'campaign_id'];
504 $recurringContribution = ContributionRecur
::get(FALSE)
505 ->addWhere('id', '=', $id)
506 ->setSelect($recurFields)
509 // If financial_type_id or total_amount are set on the
510 // recurring they are overrides, but of lower precedence
511 // than input parameters.
512 // we filter out null, '' and FALSE but not zero - I'm on the fence about zero.
513 $overrides = array_filter(array_merge(
514 // We filter recurringContribution as we only want the fields we asked for
515 // and specifically don't want 'id' added to overrides.
516 array_intersect_key($recurringContribution, array_fill_keys($recurFields, 1)),
520 // First look for new-style template contribution with is_template=1
521 $templateContributions = Contribution
::get(FALSE)
522 ->addWhere('contribution_recur_id', '=', $id)
523 ->addWhere('is_template', '=', 1)
524 ->addWhere('is_test', '=', $recurringContribution['is_test'])
525 ->addOrderBy('id', 'DESC')
528 if (!$templateContributions->count()) {
529 // Fall back to old style template contributions
530 $templateContributions = Contribution
::get(FALSE)
531 ->addWhere('contribution_recur_id', '=', $id)
532 ->addWhere('is_test', '=', $recurringContribution['is_test'])
533 ->addOrderBy('id', 'DESC')
537 if ($templateContributions->count()) {
538 $templateContribution = $templateContributions->first();
539 $order = new CRM_Financial_BAO_Order();
540 $order->setTemplateContributionID($templateContribution['id']);
541 $order->setOverrideFinancialTypeID($overrides['financial_type_id'] ??
NULL);
542 $order->setOverridableFinancialTypeID($templateContribution['financial_type_id']);
543 $order->setOverrideTotalAmount($overrides['total_amount'] ??
NULL);
544 $order->setIsPermitOverrideFinancialTypeForMultipleLines(FALSE);
545 $lineItems = $order->getLineItems();
546 // We only permit the financial type to be overridden for single line items.
547 // Otherwise we need to figure out a whole lot of extra complexity.
548 // It's not UI-possible to alter financial_type_id for recurring contributions
549 // with more than one line item.
550 // The handling of the line items is managed in BAO_Order so this
551 // is whether we should override on the contribution. Arguably the 2 should
553 if (count($lineItems) > 1 && isset($overrides['financial_type_id'])) {
554 unset($overrides['financial_type_id']);
556 $result = array_merge($templateContribution, $overrides);
557 // Line items aren't always written to a contribution, for mystery reasons.
558 // Checking for their existence prevents $order->getPriceSetID returning NULL.
560 $result['line_item'][$order->getPriceSetID()] = $lineItems;
562 // If the template contribution was made on-behalf then add the
563 // relevant values to ensure the activity reflects that.
564 $relatedContact = CRM_Contribute_BAO_Contribution
::getOnbehalfIds($result['id']);
565 if (!empty($relatedContact['individual_id'])) {
566 $result['on_behalf'] = TRUE;
567 $result['source_contact_id'] = $relatedContact['individual_id'];
574 public static function setSubscriptionContext() {
575 // handle context redirection for subscription url
576 $session = CRM_Core_Session
::singleton();
577 if ($session->get('userID')) {
579 $cid = CRM_Utils_Request
::retrieve('cid', 'Integer');
580 $mid = CRM_Utils_Request
::retrieve('mid', 'Integer');
581 $qfkey = CRM_Utils_Request
::retrieve('key', 'String');
582 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric');
586 $url = CRM_Utils_System
::url('civicrm/contact/view',
587 "reset=1&selectedChild=contribute&cid={$cid}"
592 $url = CRM_Utils_System
::url('civicrm/contact/view',
593 "reset=1&selectedChild=member&cid={$cid}"
598 $url = CRM_Utils_System
::url('civicrm/user', "reset=1&id={$cid}");
605 $url = CRM_Utils_System
::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
609 $url = CRM_Utils_System
::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
614 $session->pushUserContext($url);
620 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
622 * @param array $fields
623 * The input form values.
624 * @param array $files
625 * The uploaded files if any.
626 * @param CRM_Core_Form $self
627 * @param array $errors
629 public static function validateRecurContribution($fields, $files, $self, &$errors) {
630 if (!empty($fields['is_recur'])) {
631 if ($fields['frequency_interval'] <= 0) {
632 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
634 if ($fields['frequency_unit'] == '0') {
635 $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).');
641 * Copy custom data of the initial contribution into its recurring contributions.
645 * @param int $recurId
646 * @param int $targetContributionId
648 public static function copyCustomValues($recurId, $targetContributionId) {
649 CRM_Core_Error
::deprecatedFunctionWarning('no alternative');
650 if ($recurId && $targetContributionId) {
651 // get the initial contribution id of recur id
652 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
654 // if the same contribution is being processed then return
655 if ($sourceContributionId == $targetContributionId) {
658 // check if proper recurring contribution record is being processed
659 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
660 if ($targetConRecurId != $recurId) {
665 $extends = ['Contribution'];
666 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
668 foreach ($groupTree as $groupID => $group) {
669 $table[$groupTree[$groupID]['table_name']] = ['entity_id'];
670 foreach ($group['fields'] as $fieldID => $field) {
671 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
675 foreach ($table as $tableName => $tableColumns) {
676 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
677 $tableColumns[0] = $targetContributionId;
678 $select = 'SELECT ' . implode(', ', $tableColumns);
679 $from = ' FROM ' . $tableName;
680 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
681 $query = $insert . $select . $from . $where;
682 CRM_Core_DAO
::executeQuery($query);
689 * Add soft credit to for recurring payment.
691 * copy soft credit record of first recurring contribution.
692 * and add new soft credit against $targetContributionId
694 * @param int $recurId
695 * @param int $targetContributionId
697 public static function addrecurSoftCredit($recurId, $targetContributionId) {
698 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
699 $soft_contribution->contribution_id
= CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
701 // Check if first recurring contribution has any associated soft credit.
702 if ($soft_contribution->find(TRUE)) {
703 $soft_contribution->contribution_id
= $targetContributionId;
704 unset($soft_contribution->id
);
705 $soft_contribution->save();
710 * Add line items for recurring contribution.
712 * @param int $recurId
713 * @param \CRM_Contribute_BAO_Contribution $contribution
716 * @throws \CRM_Core_Exception
717 * @throws \CiviCRM_API3_Exception
719 public static function addRecurLineItems($recurId, $contribution) {
720 $foundLineItems = FALSE;
722 $lineSets = self
::calculateRecurLineItems($recurId, $contribution->total_amount
, $contribution->financial_type_id
);
723 foreach ($lineSets as $lineItems) {
724 if (!empty($lineItems)) {
725 foreach ($lineItems as $key => $value) {
726 if ($value['entity_table'] == 'civicrm_membership') {
728 // @todo this should be done by virtue of editing the line item as this link
729 // is deprecated. This may be the case but needs testing.
730 civicrm_api3('membership_payment', 'create', [
731 'membership_id' => $value['entity_id'],
732 'contribution_id' => $contribution->id
,
733 'is_transactional' => FALSE,
736 catch (CiviCRM_API3_Exception
$e) {
737 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
738 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
742 $foundLineItems = TRUE;
745 if (!$foundLineItems) {
746 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
752 * Update pledge associated with a recurring contribution.
754 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
756 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
757 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
758 * it should be assumed they
759 * do so with the intention that all payments will be linked
761 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
762 * If not the contribution will also need to be linked to the pledge
764 * @param int $contributionID
765 * @param int $contributionRecurID
766 * @param int $contributionStatusID
767 * @param float $contributionAmount
769 * @throws \CiviCRM_API3_Exception
771 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
772 $returnProperties = ['id', 'pledge_id'];
773 $paymentDetails = $paymentIDs = [];
775 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
776 $paymentDetails, $returnProperties
779 foreach ($paymentDetails as $key => $value) {
780 $paymentIDs[] = $value['id'];
781 $pledgeId = $value['pledge_id'];
785 //payment is not already linked - if it is linked with a pledge we need to create a link.
786 // return if it is not recurring contribution
787 if (!$contributionRecurID) {
791 $relatedContributions = new CRM_Contribute_DAO_Contribution();
792 $relatedContributions->contribution_recur_id
= $contributionRecurID;
793 $relatedContributions->find();
795 while ($relatedContributions->fetch()) {
796 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
797 $paymentDetails, $returnProperties
801 if (empty($paymentDetails)) {
802 // payment is not linked with a pledge and neither are any other contributions on this
806 foreach ($paymentDetails as $key => $value) {
807 $pledgeId = $value['pledge_id'];
810 // we have a pledge now we need to get the oldest unpaid payment
811 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
812 if (empty($paymentDetails['id'])) {
813 // we can assume this pledge is now completed
814 // return now so we don't create a core error & roll back
817 $paymentDetails['contribution_id'] = $contributionID;
818 $paymentDetails['status_id'] = $contributionStatusID;
819 $paymentDetails['actual_amount'] = $contributionAmount;
821 // put contribution against it
822 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
823 $paymentIDs[] = $payment['id'];
826 // update pledge and corresponding payment statuses
827 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
828 NULL, $contributionAmount
833 * @param CRM_Core_Form $form
835 public static function recurringContribution(&$form) {
836 // Recurring contribution fields
837 foreach (self
::getRecurringFields() as $key) {
838 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues
) &&
839 !CRM_Utils_System
::isNull(CRM_Utils_Array
::value($key, $form->_formValues
))
841 $form->assign('contribution_recur_pane_open', TRUE);
844 // If data has been entered for a recurring field, tell the tpl layer to open the pane
845 if (!empty($form->_formValues
) && !empty($form->_formValues
[$key . '_relative']) ||
!empty($form->_formValues
[$key . '_low']) ||
!empty($form->_formValues
[$key . '_high'])) {
846 $form->assign('contribution_recur_pane_open', TRUE);
851 // If values have been supplied for recurring contribution fields, open the recurring contributions pane.
852 foreach (['contribution_status_id', 'payment_processor_id', 'processor_id', 'trxn_id'] as $fieldName) {
853 if (!empty($form->_formValues
['contribution_recur_' . $fieldName])) {
854 $form->assign('contribution_recur_pane_open', TRUE);
859 // Add field to check if payment is made for recurring contribution
860 $recurringPaymentOptions = [
861 1 => ts('All recurring contributions'),
862 2 => ts('Recurring contributions with at least one payment'),
864 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, ['allowClear' => TRUE]);
866 // Add field for contribution status
867 $form->addSelect('contribution_recur_contribution_status_id',
868 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_BAO_Contribution
::buildOptions('contribution_status_id', 'search')]
871 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
872 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
874 $paymentProcessorOpts = CRM_Contribute_BAO_ContributionRecur
::buildOptions('payment_processor_id', 'get');
875 $form->add('select', 'contribution_recur_payment_processor_id', ts('Payment Processor ID'), $paymentProcessorOpts, FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']);
877 CRM_Core_BAO_Query
::addCustomFormFields($form, ['ContributionRecur']);
882 * Get the metadata for fields to be included on the search form.
884 * @throws \CiviCRM_API3_Exception
886 public static function getContributionRecurSearchFieldMetadata() {
888 'contribution_recur_start_date',
889 'contribution_recur_next_sched_contribution_date',
890 'contribution_recur_cancel_date',
891 'contribution_recur_end_date',
892 'contribution_recur_create_date',
893 'contribution_recur_modified_date',
894 'contribution_recur_failure_retry_date',
896 $metadata = civicrm_api3('ContributionRecur', 'getfields', [])['values'];
897 return array_intersect_key($metadata, array_flip($fields));
901 * Get fields for recurring contributions.
905 public static function getRecurringFields() {
907 'contribution_recur_payment_made',
908 'contribution_recur_start_date',
909 'contribution_recur_next_sched_contribution_date',
910 'contribution_recur_cancel_date',
911 'contribution_recur_end_date',
912 'contribution_recur_create_date',
913 'contribution_recur_modified_date',
914 'contribution_recur_failure_retry_date',
919 * Update recurring contribution based on incoming payment.
921 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
923 * @param int $recurringContributionID
924 * @param string $paymentStatus
925 * Payment status - this correlates to the machine name of the contribution status ID ie
928 * @param string $effectiveDate
930 * @throws \CiviCRM_API3_Exception
932 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, string $effectiveDate = 'now') {
934 if (!in_array($paymentStatus, ['Completed', 'Failed'])) {
938 'id' => $recurringContributionID,
940 'contribution_status_id',
941 'next_sched_contribution_date',
943 'frequency_interval',
949 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
951 if ($paymentStatus == 'Completed'
952 && CRM_Contribute_PseudoConstant
::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
953 $params['contribution_status_id'] = 'In Progress';
955 if ($paymentStatus == 'Failed') {
956 $params['failure_count'] = $existing['failure_count'];
958 $params['modified_date'] = date('Y-m-d H:i:s');
960 if (!empty($existing['installments']) && self
::isComplete($recurringContributionID, $existing['installments'])) {
961 $params['contribution_status_id'] = 'Completed';
962 $params['next_sched_contribution_date'] = 'null';
965 // Only update next sched date if it's empty or up to 48 hours away because payment processors may be managing
966 // the scheduled date themselves as core did not previously provide any help. This check can possibly be removed
967 // as it's unclear if it actually is helpful...
968 // We should allow payment processors to pass this value into repeattransaction in future.
969 // Note 48 hours is a bit aribtrary but means that we can hopefully ignore the time being potentially
970 // rounded down to midnight.
971 $upperDateToConsiderProcessed = strtotime('+ 48 hours', ($effectiveDate ?
strtotime($effectiveDate) : time()));
972 if (empty($existing['next_sched_contribution_date']) ||
strtotime($existing['next_sched_contribution_date']) <=
973 $upperDateToConsiderProcessed) {
974 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
977 civicrm_api3('ContributionRecur', 'create', $params);
981 * Is this recurring contribution now complete.
983 * Have all the payments expected been received now.
985 * @param int $recurringContributionID
986 * @param int $installments
990 protected static function isComplete($recurringContributionID, $installments) {
991 $paidInstallments = CRM_Core_DAO
::singleValueQuery(
992 'SELECT count(*) FROM civicrm_contribution
993 WHERE contribution_recur_id = %1
994 AND contribution_status_id = ' . CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
995 [1 => [$recurringContributionID, 'Integer']]
997 if ($paidInstallments >= $installments) {
1004 * Calculate line items for the relevant recurring calculation.
1006 * @param int $recurId
1007 * @param string $total_amount
1008 * @param int $financial_type_id
1011 * @throws \CiviCRM_API3_Exception
1013 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
1014 $originalContribution = civicrm_api3('Contribution', 'getsingle', [
1015 'contribution_recur_id' => $recurId,
1016 'contribution_test' => '',
1017 'options' => ['limit' => 1],
1018 'return' => ['id', 'financial_type_id'],
1020 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContribution['id']);
1021 return self
::reformatLineItemsForRepeatContribution($total_amount, $financial_type_id, $lineItems, $originalContribution);
1025 * Returns array with statuses that are considered to make a recurring contribution inactive.
1029 public static function getInactiveStatuses() {
1030 return ['Cancelled', 'Failed', 'Completed'];
1036 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1038 switch ($fieldName) {
1039 case 'payment_processor_id':
1040 if (isset(\Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'])) {
1041 return \Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'];
1043 $baoName = 'CRM_Contribute_BAO_ContributionRecur';
1044 $params['condition']['test'] = "is_test = 0";
1045 $liveProcessors = CRM_Core_PseudoConstant
::get($baoName, $fieldName, $params, $context);
1046 $params['condition']['test'] = "is_test != 0";
1047 $testProcessors = CRM_Core_PseudoConstant
::get($baoName, $fieldName, $params, $context);
1048 foreach ($testProcessors as $key => $value) {
1049 if ($context === 'validate') {
1050 // @fixme: Ideally the names would be different in the civicrm_payment_processor table but they are not.
1051 // So we append '_test' to the test one so that we can select the correct processor by name using the ContributionRecur.create API.
1052 $testProcessors[$key] = $value . '_test';
1055 $testProcessors[$key] = CRM_Core_TestEntity
::appendTestText($value);
1058 $allProcessors = $liveProcessors +
$testProcessors;
1059 ksort($allProcessors);
1060 \Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'] = $allProcessors;
1061 return $allProcessors;
1063 return CRM_Core_PseudoConstant
::get(__CLASS__
, $fieldName, $params, $context);
1067 * Get the from address to use for the recurring contribution.
1069 * This uses the contribution page id, if there is one, or the default domain one.
1072 * Recurring contribution ID.
1077 * @throws \API_Exception
1078 * @throws \CRM_Core_Exception
1080 public static function getRecurFromAddress(int $id): string {
1081 $details = Contribution
::get(FALSE)
1082 ->addWhere('contribution_recur_id', '=', $id)
1083 ->addWhere('contribution_page_id', 'IS NOT NULL')
1084 ->addSelect('contribution_page_id.receipt_from_name', 'contribution_page_id.receipt_from_email')
1085 ->addOrderBy('receive_date', 'DESC')
1086 ->execute()->first();
1087 if (empty($details['contribution_page_id.receipt_from_email'])) {
1088 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1089 return "$domainValues[0] <$domainValues[1]>";
1091 return '"' . $details['contribution_page_id.receipt_from_name'] . '" <' . $details['contribution_page_id.receipt_from_email'] . '>';