3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Contribute_BAO_ContributionRecur
extends CRM_Contribute_DAO_ContributionRecur
{
36 * Array with statuses that mark a recurring contribution as inactive.
40 private static $inactiveStatuses = ['Cancelled', 'Chargeback', 'Refunded', 'Completed'];
43 * Create recurring contribution.
45 * @param array $params
46 * (reference ) an assoc array of name/value pairs.
49 * activity contact object
51 public static function create(&$params) {
52 return self
::add($params);
56 * Takes an associative array and creates a contribution object.
58 * the function extract all the params it needs to initialize the create a
59 * contribution object. the params array could contain additional unused name/value
62 * @param array $params
63 * (reference ) an assoc array of name/value pairs.
65 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
66 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
68 public static function add(&$params) {
69 if (!empty($params['id'])) {
70 CRM_Utils_Hook
::pre('edit', 'ContributionRecur', $params['id'], $params);
73 CRM_Utils_Hook
::pre('create', 'ContributionRecur', NULL, $params);
76 // make sure we're not creating a new recurring contribution with the same transaction ID
77 // or invoice ID as an existing recurring contribution
79 if (self
::checkDuplicate($params, $duplicates)) {
80 $error = CRM_Core_Error
::singleton();
81 $d = implode(', ', $duplicates);
82 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
85 "Found matching recurring contribution(s): $d"
90 $recurring = new CRM_Contribute_BAO_ContributionRecur();
91 $recurring->copyValues($params);
92 $recurring->id
= CRM_Utils_Array
::value('id', $params);
94 // set currency for CRM-1496
95 if (empty($params['id']) && !isset($recurring->currency
)) {
96 $config = CRM_Core_Config
::singleton();
97 $recurring->currency
= $config->defaultCurrency
;
101 if (!empty($params['id'])) {
102 CRM_Utils_Hook
::post('edit', 'ContributionRecur', $recurring->id
, $recurring);
105 CRM_Utils_Hook
::post('create', 'ContributionRecur', $recurring->id
, $recurring);
108 if (!empty($params['custom']) &&
109 is_array($params['custom'])
111 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution_recur', $recurring->id
);
118 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
120 * @param array $params
121 * (reference ) an assoc array of name/value pairs.
122 * @param array $duplicates
123 * (reference ) store ids of duplicate contributions.
126 * true if duplicate, false otherwise
128 public static function checkDuplicate($params, &$duplicates) {
129 $id = CRM_Utils_Array
::value('id', $params);
130 $trxn_id = CRM_Utils_Array
::value('trxn_id', $params);
131 $invoice_id = CRM_Utils_Array
::value('invoice_id', $params);
137 $clause[] = "trxn_id = %1";
138 $params[1] = [$trxn_id, 'String'];
142 $clause[] = "invoice_id = %2";
143 $params[2] = [$invoice_id, 'String'];
146 if (empty($clause)) {
150 $clause = implode(' OR ', $clause);
152 $clause = "( $clause ) AND id != %3";
153 $params[3] = [$id, 'Integer'];
156 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
157 $dao = CRM_Core_DAO
::executeQuery($query, $params);
159 while ($dao->fetch()) {
160 $duplicates[] = $dao->id
;
167 * Get the payment processor (array) for a recurring processor.
173 public static function getPaymentProcessor($id) {
174 $paymentProcessorID = self
::getPaymentProcessorID($id);
175 return CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID);
179 * Get the processor object for the recurring contribution record.
183 * @return CRM_Core_Payment|NULL
184 * Returns a processor object or NULL if the processor is disabled.
185 * Note this returns the 'Manual' processor object if no processor is attached
186 * (since it still makes sense to update / cancel
188 public static function getPaymentProcessorObject($id) {
189 $processor = self
::getPaymentProcessor($id);
190 return is_array($processor) ?
$processor['object'] : NULL;
194 * Get the payment processor for the given recurring contribution.
196 * @param int $recurID
199 * Payment processor id. If none found return 0 which represents the
200 * pseudo processor used for pay-later.
202 public static function getPaymentProcessorID($recurID) {
203 $recur = civicrm_api3('ContributionRecur', 'getsingle', [
205 'return' => ['payment_processor_id'],
207 return (int) CRM_Utils_Array
::value('payment_processor_id', $recur, 0);
211 * Get the number of installment done/completed for each recurring contribution.
214 * (reference ) an array of recurring contribution ids.
217 * an array of recurring ids count
219 public static function getCount(&$ids) {
220 $recurID = implode(',', $ids);
224 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
225 FROM civicrm_contribution
226 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
227 GROUP BY contribution_recur_id";
229 $res = CRM_Core_DAO
::executeQuery($query);
231 while ($res->fetch()) {
232 $totalCount[$res->contribution_recur_id
] = $res->commpleted
;
238 * Delete Recurring contribution.
240 * @param int $recurId
244 public static function deleteRecurContribution($recurId) {
250 $recur = new CRM_Contribute_DAO_ContributionRecur();
251 $recur->id
= $recurId;
252 $result = $recur->delete();
258 * Cancel Recurring contribution.
260 * @param array $params
261 * Recur contribution params
265 public static function cancelRecurContribution($params) {
266 if (is_numeric($params)) {
267 CRM_Core_Error
::deprecatedFunctionWarning('You are using a BAO function whose signature has changed. Please use the ContributionRecur.cancel api');
268 $params = ['id' => $params];
270 $recurId = $params['id'];
275 'subject' => !empty($params['membership_id']) ?
ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'),
276 'details' => CRM_Utils_Array
::value('processor_message', $params),
279 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
280 $canceledId = array_search('Cancelled', $contributionStatus);
281 $recur = new CRM_Contribute_DAO_ContributionRecur();
282 $recur->id
= $recurId;
283 $recur->whereAdd("contribution_status_id != $canceledId");
285 if ($recur->find(TRUE)) {
286 $transaction = new CRM_Core_Transaction();
287 $recur->contribution_status_id
= $canceledId;
288 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
289 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
290 $recur->modified_date
= CRM_Utils_Date
::isoToMysql($recur->modified_date
);
291 $recur->cancel_reason
= CRM_Utils_Array
::value('cancel_reason', $params);
292 $recur->cancel_date
= date('YmdHis');
295 $dao = CRM_Contribute_BAO_ContributionRecur
::getSubscriptionDetails($recurId);
296 if ($dao && $dao->recur_id
) {
297 $details = CRM_Utils_Array
::value('details', $activityParams);
298 if ($dao->auto_renew
&& $dao->membership_id
) {
299 // its auto-renewal membership mode
300 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
301 $membershipType = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id
, 'membership_type_id');
302 $membershipType = CRM_Utils_Array
::value($membershipType, $membershipTypes);
304 <br/>' . ts('Automatic renewal of %1 membership cancelled.', [1 => $membershipType]);
307 $details .= '<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', [
309 2 => $dao->frequency_interval
,
310 3 => $dao->frequency_unit
,
314 'source_contact_id' => $dao->contact_id
,
315 'source_record_id' => $dao->recur_id
,
316 'activity_type_id' => 'Cancel Recurring Contribution',
317 'subject' => CRM_Utils_Array
::value('subject', $activityParams, ts('Recurring contribution cancelled')),
318 'details' => $details,
319 'status_id' => 'Completed',
322 $cid = CRM_Core_Session
::singleton()->get('userID');
324 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
325 $activityParams['source_contact_id'] = $cid;
327 civicrm_api3('Activity', 'create', $activityParams);
330 $transaction->commit();
334 // if already cancelled, return true
336 $recur->whereAdd("contribution_status_id = $canceledId");
337 if ($recur->find(TRUE)) {
346 * @param int $entityID
347 * @param string $entity
349 * @return null|Object
351 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
353 SELECT rec.id as recur_id,
354 rec.processor_id as subscription_id,
355 rec.frequency_interval,
363 rec.financial_type_id,
364 rec.next_sched_contribution_date,
365 rec.failure_retry_date,
367 con.id as contribution_id,
368 con.contribution_page_id,
372 if ($entity == 'recur') {
374 FROM civicrm_contribution_recur rec
375 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
376 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
379 elseif ($entity == 'contribution') {
381 FROM civicrm_contribution con
382 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
383 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
386 elseif ($entity == 'membership') {
388 FROM civicrm_membership_payment mp
389 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
390 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
391 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
392 WHERE mp.membership_id = %1";
395 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$entityID, 'Integer']]);
405 * Does the recurring contribution support financial type change.
407 * This is conditional on there being only one line item or if there are no contributions as yet.
409 * (This second is a bit of an unusual condition but might occur in the context of a
415 public static function supportsFinancialTypeChange($id) {
416 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
417 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
418 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
421 $contribution = self
::getTemplateContribution($id);
422 return CRM_Contribute_BAO_Contribution
::isSingleLineItem($contribution['id']);
426 * Get the contribution to be used as the template for later contributions.
428 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
431 * @param array $overrides
432 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
435 * @throws \CiviCRM_API3_Exception
437 public static function getTemplateContribution($id, $overrides = []) {
438 $templateContribution = civicrm_api3('Contribution', 'get', [
439 'contribution_recur_id' => $id,
440 'options' => ['limit' => 1, 'sort' => ['id DESC']],
442 'contribution_test' => '',
444 if ($templateContribution['count']) {
445 $result = array_merge($templateContribution['values'][0], $overrides);
446 $result['line_item'] = CRM_Contribute_BAO_ContributionRecur
::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
452 public static function setSubscriptionContext() {
453 // handle context redirection for subscription url
454 $session = CRM_Core_Session
::singleton();
455 if ($session->get('userID')) {
457 $cid = CRM_Utils_Request
::retrieve('cid', 'Integer');
458 $mid = CRM_Utils_Request
::retrieve('mid', 'Integer');
459 $qfkey = CRM_Utils_Request
::retrieve('key', 'String');
460 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric');
464 $url = CRM_Utils_System
::url('civicrm/contact/view',
465 "reset=1&selectedChild=contribute&cid={$cid}"
470 $url = CRM_Utils_System
::url('civicrm/contact/view',
471 "reset=1&selectedChild=member&cid={$cid}"
476 $url = CRM_Utils_System
::url('civicrm/user', "reset=1&id={$cid}");
483 $url = CRM_Utils_System
::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
487 $url = CRM_Utils_System
::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
492 $session->pushUserContext($url);
498 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
500 * @param array $fields
501 * The input form values.
502 * @param array $files
503 * The uploaded files if any.
504 * @param CRM_Core_Form $self
505 * @param array $errors
507 public static function validateRecurContribution($fields, $files, $self, &$errors) {
508 if (!empty($fields['is_recur'])) {
509 if ($fields['frequency_interval'] <= 0) {
510 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
512 if ($fields['frequency_unit'] == '0') {
513 $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).');
519 * Send start or end notification for recurring payments.
522 * @param CRM_Contribute_BAO_ContributionRecur $recur
523 * @param bool $isFirstOrLastRecurringPayment
525 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
526 if ($isFirstOrLastRecurringPayment) {
527 $autoRenewMembership = FALSE;
529 isset($ids['membership']) && $ids['membership']
531 $autoRenewMembership = TRUE;
534 //send recurring Notification email for user
535 CRM_Contribute_BAO_ContributionPage
::recurringNotify($isFirstOrLastRecurringPayment,
537 $ids['contributionPage'],
545 * Copy custom data of the initial contribution into its recurring contributions.
547 * @param int $recurId
548 * @param int $targetContributionId
550 public static function copyCustomValues($recurId, $targetContributionId) {
551 if ($recurId && $targetContributionId) {
552 // get the initial contribution id of recur id
553 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
555 // if the same contribution is being processed then return
556 if ($sourceContributionId == $targetContributionId) {
559 // check if proper recurring contribution record is being processed
560 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
561 if ($targetConRecurId != $recurId) {
566 $extends = ['Contribution'];
567 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
569 foreach ($groupTree as $groupID => $group) {
570 $table[$groupTree[$groupID]['table_name']] = ['entity_id'];
571 foreach ($group['fields'] as $fieldID => $field) {
572 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
576 foreach ($table as $tableName => $tableColumns) {
577 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
578 $tableColumns[0] = $targetContributionId;
579 $select = 'SELECT ' . implode(', ', $tableColumns);
580 $from = ' FROM ' . $tableName;
581 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
582 $query = $insert . $select . $from . $where;
583 CRM_Core_DAO
::executeQuery($query);
590 * Add soft credit to for recurring payment.
592 * copy soft credit record of first recurring contribution.
593 * and add new soft credit against $targetContributionId
595 * @param int $recurId
596 * @param int $targetContributionId
598 public static function addrecurSoftCredit($recurId, $targetContributionId) {
599 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
600 $soft_contribution->contribution_id
= CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
602 // Check if first recurring contribution has any associated soft credit.
603 if ($soft_contribution->find(TRUE)) {
604 $soft_contribution->contribution_id
= $targetContributionId;
605 unset($soft_contribution->id
);
606 $soft_contribution->save();
611 * Add line items for recurring contribution.
613 * @param int $recurId
614 * @param \CRM_Contribute_BAO_Contribution $contribution
618 public static function addRecurLineItems($recurId, $contribution) {
619 $foundLineItems = FALSE;
621 $lineSets = self
::calculateRecurLineItems($recurId, $contribution->total_amount
, $contribution->financial_type_id
);
622 foreach ($lineSets as $lineItems) {
623 if (!empty($lineItems)) {
624 foreach ($lineItems as $key => $value) {
625 if ($value['entity_table'] == 'civicrm_membership') {
627 // @todo this should be done by virtue of editing the line item as this link
628 // is deprecated. This may be the case but needs testing.
629 civicrm_api3('membership_payment', 'create', [
630 'membership_id' => $value['entity_id'],
631 'contribution_id' => $contribution->id
,
632 'is_transactional' => FALSE,
635 catch (CiviCRM_API3_Exception
$e) {
636 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
637 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
641 $foundLineItems = TRUE;
644 if (!$foundLineItems) {
645 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
651 * Update pledge associated with a recurring contribution.
653 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
655 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
656 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
657 * it should be assumed they
658 * do so with the intention that all payments will be linked
660 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
661 * If not the contribution will also need to be linked to the pledge
663 * @param int $contributionID
664 * @param int $contributionRecurID
665 * @param int $contributionStatusID
666 * @param float $contributionAmount
668 * @throws \CiviCRM_API3_Exception
670 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
671 $returnProperties = ['id', 'pledge_id'];
672 $paymentDetails = $paymentIDs = [];
674 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
675 $paymentDetails, $returnProperties
678 foreach ($paymentDetails as $key => $value) {
679 $paymentIDs[] = $value['id'];
680 $pledgeId = $value['pledge_id'];
684 //payment is not already linked - if it is linked with a pledge we need to create a link.
685 // return if it is not recurring contribution
686 if (!$contributionRecurID) {
690 $relatedContributions = new CRM_Contribute_DAO_Contribution();
691 $relatedContributions->contribution_recur_id
= $contributionRecurID;
692 $relatedContributions->find();
694 while ($relatedContributions->fetch()) {
695 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
696 $paymentDetails, $returnProperties
700 if (empty($paymentDetails)) {
701 // payment is not linked with a pledge and neither are any other contributions on this
705 foreach ($paymentDetails as $key => $value) {
706 $pledgeId = $value['pledge_id'];
709 // we have a pledge now we need to get the oldest unpaid payment
710 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
711 if (empty($paymentDetails['id'])) {
712 // we can assume this pledge is now completed
713 // return now so we don't create a core error & roll back
716 $paymentDetails['contribution_id'] = $contributionID;
717 $paymentDetails['status_id'] = $contributionStatusID;
718 $paymentDetails['actual_amount'] = $contributionAmount;
720 // put contribution against it
721 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
722 $paymentIDs[] = $payment['id'];
725 // update pledge and corresponding payment statuses
726 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
727 NULL, $contributionAmount
732 * @param CRM_Core_Form $form
734 public static function recurringContribution(&$form) {
735 // Recurring contribution fields
736 foreach (self
::getRecurringFields() as $key => $label) {
737 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues
) &&
738 !CRM_Utils_System
::isNull(CRM_Utils_Array
::value($key, $form->_formValues
))
740 $form->assign('contribution_recur_pane_open', TRUE);
743 CRM_Core_Form_Date
::buildDateRange($form, $key, 1, '_low', '_high');
744 // If data has been entered for a recurring field, tell the tpl layer to open the pane
745 if (!empty($form->_formValues
) && !empty($form->_formValues
[$key . '_relative']) ||
!empty($form->_formValues
[$key . '_low']) ||
!empty($form->_formValues
[$key . '_high'])) {
746 $form->assign('contribution_recur_pane_open', TRUE);
751 // If values have been supplied for recurring contribution fields, open the recurring contributions pane.
752 foreach (['contribution_status_id', 'payment_processor_id', 'processor_id', 'trxn_id'] as $fieldName) {
753 if (!empty($form->_formValues
['contribution_recur_' . $fieldName])) {
754 $form->assign('contribution_recur_pane_open', TRUE);
759 // Add field to check if payment is made for recurring contribution
760 $recurringPaymentOptions = [
761 1 => ts('All recurring contributions'),
762 2 => ts('Recurring contributions with at least one payment'),
764 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, ['allowClear' => TRUE]);
765 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
766 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
767 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
768 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
769 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
770 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
772 // Add field for contribution status
773 $form->addSelect('contribution_recur_contribution_status_id',
774 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_PseudoConstant
::contributionStatus()]
777 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
778 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
780 $paymentProcessorOpts = CRM_Contribute_BAO_ContributionRecur
::buildOptions('payment_processor_id', 'get');
781 $form->add('select', 'contribution_recur_payment_processor_id', ts('Payment Processor ID'), $paymentProcessorOpts, FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']);
783 CRM_Core_BAO_Query
::addCustomFormFields($form, ['ContributionRecur']);
788 * Get fields for recurring contributions.
792 public static function getRecurringFields() {
794 'contribution_recur_payment_made' => ts(''),
795 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
796 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
797 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
798 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
799 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
800 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
801 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
806 * Update recurring contribution based on incoming payment.
808 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
810 * @param int $recurringContributionID
811 * @param string $paymentStatus
812 * Payment status - this correlates to the machine name of the contribution status ID ie
815 * @param string $effectiveDate
817 * @throws \CiviCRM_API3_Exception
819 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
821 $effectiveDate = $effectiveDate ?
date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
822 if (!in_array($paymentStatus, ['Completed', 'Failed'])) {
826 'id' => $recurringContributionID,
828 'contribution_status_id',
829 'next_sched_contribution_date',
831 'frequency_interval',
837 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
839 if ($paymentStatus == 'Completed'
840 && CRM_Contribute_PseudoConstant
::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
841 $params['contribution_status_id'] = 'In Progress';
843 if ($paymentStatus == 'Failed') {
844 $params['failure_count'] = $existing['failure_count'];
846 $params['modified_date'] = date('Y-m-d H:i:s');
848 if (!empty($existing['installments']) && self
::isComplete($recurringContributionID, $existing['installments'])) {
849 $params['contribution_status_id'] = 'Completed';
852 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
853 // the scheduled date themselves as core did not previously provide any help.
854 if (empty($existing['next_sched_contribution_date']) ||
strtotime($existing['next_sched_contribution_date']) ==
855 strtotime($effectiveDate)) {
856 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
859 civicrm_api3('ContributionRecur', 'create', $params);
863 * Is this recurring contribution now complete.
865 * Have all the payments expected been received now.
867 * @param int $recurringContributionID
868 * @param int $installments
872 protected static function isComplete($recurringContributionID, $installments) {
873 $paidInstallments = CRM_Core_DAO
::singleValueQuery(
874 'SELECT count(*) FROM civicrm_contribution
875 WHERE contribution_recur_id = %1
876 AND contribution_status_id = ' . CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
877 [1 => [$recurringContributionID, 'Integer']]
879 if ($paidInstallments >= $installments) {
886 * Calculate line items for the relevant recurring calculation.
888 * @param int $recurId
889 * @param string $total_amount
890 * @param int $financial_type_id
894 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
895 $originalContribution = civicrm_api3('Contribution', 'getsingle', [
896 'contribution_recur_id' => $recurId,
897 'contribution_test' => '',
898 'options' => ['limit' => 1],
899 'return' => ['id', 'financial_type_id'],
901 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContribution['id']);
903 if (count($lineItems) == 1) {
904 foreach ($lineItems as $index => $lineItem) {
905 if ($lineItem['financial_type_id'] != $originalContribution['financial_type_id']) {
906 // 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.
907 $financial_type_id = $lineItem['financial_type_id'];
909 if ($financial_type_id) {
910 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
911 $lineItem['financial_type_id'] = $financial_type_id;
913 if ($lineItem['line_total'] != $total_amount) {
914 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
915 // if there is only one line item, and the UI should prevent this situation for those with more than one.
916 $lineItem['line_total'] = $total_amount;
917 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
919 $priceField = new CRM_Price_DAO_PriceField();
920 $priceField->id
= $lineItem['price_field_id'];
921 $priceField->find(TRUE);
922 $lineSets[$priceField->price_set_id
][$lineItem['price_field_id']] = $lineItem;
925 // CRM-19309 if more than one then just pass them through:
926 elseif (count($lineItems) > 1) {
927 foreach ($lineItems as $index => $lineItem) {
928 $lineSets[$index][$lineItem['price_field_id']] = $lineItem;
936 * Returns array with statuses that are considered to make a recurring
937 * contribution inactive.
941 public static function getInactiveStatuses() {
942 return self
::$inactiveStatuses;
946 * Get options for the called BAO object's field.
948 * This function can be overridden by each BAO to add more logic related to context.
949 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
951 * @param string $fieldName
952 * @param string $context
953 * @see CRM_Core_DAO::buildOptionsContext
954 * @param array $props
955 * whatever is known about this bao object.
959 public static function buildOptions($fieldName, $context = NULL, $props = []) {
961 switch ($fieldName) {
962 case 'payment_processor_id':
963 if (isset(\Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'])) {
964 return \Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'];
966 $baoName = 'CRM_Contribute_BAO_ContributionRecur';
967 $props['condition']['test'] = "is_test = 0";
968 $liveProcessors = CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
969 $props['condition']['test'] = "is_test != 0";
970 $testProcessors = CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
971 foreach ($testProcessors as $key => $value) {
972 if ($context === 'validate') {
973 // @fixme: Ideally the names would be different in the civicrm_payment_processor table but they are not.
974 // So we append '_test' to the test one so that we can select the correct processor by name using the ContributionRecur.create API.
975 $testProcessors[$key] = $value . '_test';
978 $testProcessors[$key] = CRM_Core_TestEntity
::appendTestText($value);
981 $allProcessors = $liveProcessors +
$testProcessors;
982 ksort($allProcessors);
983 \Civi
::$statics[__CLASS__
]['buildoptions_payment_processor_id'] = $allProcessors;
984 return $allProcessors;
986 return parent
::buildOptions($fieldName, $context, $props);