3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 = array('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
78 $duplicates = array();
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
;
99 $result = $recurring->save();
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] = array($trxn_id, 'String');
142 $clause[] = "invoice_id = %2";
143 $params[2] = array($invoice_id, 'String');
146 if (empty($clause)) {
150 $clause = implode(' OR ', $clause);
152 $clause = "( $clause ) AND id != %3";
153 $params[3] = array($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.
170 * @param string $mode
171 * - Test or NULL - all other variants are ignored.
175 public static function getPaymentProcessor($id, $mode = NULL) {
177 SELECT r.payment_processor_id
178 FROM civicrm_contribution_recur r
180 $params = array(1 => array($id, 'Integer'));
181 $paymentProcessorID = CRM_Core_DAO
::singleValueQuery($sql,
184 if (!$paymentProcessorID) {
188 return CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID, $mode);
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);
202 $totalCount = array();
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 int $recurId
242 * Recur contribution id.
243 * @param array $objects
244 * An array of objects that is to be cancelled like.
245 * contribution, membership, event. At least contribution object is a must.
247 * @param array $activityParams
251 public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
256 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
257 $canceledId = array_search('Cancelled', $contributionStatus);
258 $recur = new CRM_Contribute_DAO_ContributionRecur();
259 $recur->id
= $recurId;
260 $recur->whereAdd("contribution_status_id != $canceledId");
262 if ($recur->find(TRUE)) {
263 $transaction = new CRM_Core_Transaction();
264 $recur->contribution_status_id
= $canceledId;
265 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
266 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
267 $recur->modified_date
= CRM_Utils_Date
::isoToMysql($recur->modified_date
);
268 $recur->cancel_date
= date('YmdHis');
271 $dao = CRM_Contribute_BAO_ContributionRecur
::getSubscriptionDetails($recurId);
272 if ($dao && $dao->recur_id
) {
273 $details = CRM_Utils_Array
::value('details', $activityParams);
274 if ($dao->auto_renew
&& $dao->membership_id
) {
275 // its auto-renewal membership mode
276 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
277 $membershipType = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id
, 'membership_type_id');
278 $membershipType = CRM_Utils_Array
::value($membershipType, $membershipTypes);
280 <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
284 <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
286 2 => $dao->frequency_interval
,
287 3 => $dao->frequency_unit
,
290 $activityParams = array(
291 'source_contact_id' => $dao->contact_id
,
292 'source_record_id' => CRM_Utils_Array
::value('source_record_id', $activityParams),
293 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Cancel Recurring Contribution'),
294 'subject' => CRM_Utils_Array
::value('subject', $activityParams, ts('Recurring contribution cancelled')),
295 'details' => $details,
296 'activity_date_time' => date('YmdHis'),
297 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
299 $session = CRM_Core_Session
::singleton();
300 $cid = $session->get('userID');
302 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
303 $activityParams['source_contact_id'] = $cid;
305 // @todo use the api & do less wrangling above
306 CRM_Activity_BAO_Activity
::create($activityParams);
309 // if there are associated objects, cancel them as well
311 $transaction->commit();
315 // @todo - this is bad! Get the function out of the ipn.
316 $baseIPN = new CRM_Core_Payment_BaseIPN();
317 return $baseIPN->cancelled($objects, $transaction);
321 // if already cancelled, return true
323 $recur->whereAdd("contribution_status_id = $canceledId");
324 if ($recur->find(TRUE)) {
333 * @deprecated Get list of recurring contribution of contact Ids.
335 * @param int $contactId
339 * list of recurring contribution fields
342 public static function getRecurContributions($contactId) {
343 CRM_Core_Error
::deprecatedFunctionWarning('ContributionRecur.get API instead');
345 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
346 $recurDAO->contact_id
= $contactId;
348 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
350 while ($recurDAO->fetch()) {
351 $params[$recurDAO->id
]['id'] = $recurDAO->id
;
352 $params[$recurDAO->id
]['contactId'] = $recurDAO->contact_id
;
353 $params[$recurDAO->id
]['start_date'] = $recurDAO->start_date
;
354 $params[$recurDAO->id
]['end_date'] = $recurDAO->end_date
;
355 $params[$recurDAO->id
]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date
;
356 $params[$recurDAO->id
]['amount'] = $recurDAO->amount
;
357 $params[$recurDAO->id
]['currency'] = $recurDAO->currency
;
358 $params[$recurDAO->id
]['frequency_unit'] = $recurDAO->frequency_unit
;
359 $params[$recurDAO->id
]['frequency_interval'] = $recurDAO->frequency_interval
;
360 $params[$recurDAO->id
]['installments'] = $recurDAO->installments
;
361 $params[$recurDAO->id
]['contribution_status_id'] = $recurDAO->contribution_status_id
;
362 $params[$recurDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($recurDAO->contribution_status_id
, $contributionStatus);
363 $params[$recurDAO->id
]['is_test'] = $recurDAO->is_test
;
364 $params[$recurDAO->id
]['payment_processor_id'] = $recurDAO->payment_processor_id
;
371 * @param int $entityID
372 * @param string $entity
374 * @return null|Object
376 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
378 SELECT rec.id as recur_id,
379 rec.processor_id as subscription_id,
380 rec.frequency_interval,
388 rec.financial_type_id,
389 rec.next_sched_contribution_date,
390 rec.failure_retry_date,
392 con.id as contribution_id,
393 con.contribution_page_id,
397 if ($entity == 'recur') {
399 FROM civicrm_contribution_recur rec
400 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
401 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
404 elseif ($entity == 'contribution') {
406 FROM civicrm_contribution con
407 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
408 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
411 elseif ($entity == 'membership') {
413 FROM civicrm_membership_payment mp
414 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
415 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
416 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
417 WHERE mp.membership_id = %1";
420 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($entityID, 'Integer')));
430 * Does the recurring contribution support financial type change.
432 * This is conditional on there being only one line item or if there are no contributions as yet.
434 * (This second is a bit of an unusual condition but might occur in the context of a
440 public static function supportsFinancialTypeChange($id) {
441 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
442 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
443 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
446 $contribution = self
::getTemplateContribution($id);
447 return CRM_Contribute_BAO_Contribution
::isSingleLineItem($contribution['id']);
451 * Get the contribution to be used as the template for later contributions.
453 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
456 * @param array $overrides
457 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
460 * @throws \CiviCRM_API3_Exception
462 public static function getTemplateContribution($id, $overrides = array()) {
463 $templateContribution = civicrm_api3('Contribution', 'get', array(
464 'contribution_recur_id' => $id,
465 'options' => array('limit' => 1, 'sort' => array('id DESC')),
467 'contribution_test' => '',
469 if ($templateContribution['count']) {
470 $result = array_merge($templateContribution['values'][0], $overrides);
471 $result['line_item'] = CRM_Contribute_BAO_ContributionRecur
::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
477 public static function setSubscriptionContext() {
478 // handle context redirection for subscription url
479 $session = CRM_Core_Session
::singleton();
480 if ($session->get('userID')) {
482 $cid = CRM_Utils_Request
::retrieve('cid', 'Integer');
483 $mid = CRM_Utils_Request
::retrieve('mid', 'Integer');
484 $qfkey = CRM_Utils_Request
::retrieve('key', 'String');
485 $context = CRM_Utils_Request
::retrieve('context', 'String');
489 $url = CRM_Utils_System
::url('civicrm/contact/view',
490 "reset=1&selectedChild=contribute&cid={$cid}"
495 $url = CRM_Utils_System
::url('civicrm/contact/view',
496 "reset=1&selectedChild=member&cid={$cid}"
501 $url = CRM_Utils_System
::url('civicrm/user', "reset=1&id={$cid}");
508 $url = CRM_Utils_System
::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
512 $url = CRM_Utils_System
::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
517 $session->pushUserContext($url);
523 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
525 * @param array $fields
526 * The input form values.
527 * @param array $files
528 * The uploaded files if any.
529 * @param CRM_Core_Form $self
530 * @param array $errors
532 public static function validateRecurContribution($fields, $files, $self, &$errors) {
533 if (!empty($fields['is_recur'])) {
534 if ($fields['frequency_interval'] <= 0) {
535 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
537 if ($fields['frequency_unit'] == '0') {
538 $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).');
544 * Send start or end notification for recurring payments.
547 * @param CRM_Contribute_BAO_ContributionRecur $recur
548 * @param bool $isFirstOrLastRecurringPayment
550 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
551 if ($isFirstOrLastRecurringPayment) {
552 $autoRenewMembership = FALSE;
554 isset($ids['membership']) && $ids['membership']
556 $autoRenewMembership = TRUE;
559 //send recurring Notification email for user
560 CRM_Contribute_BAO_ContributionPage
::recurringNotify($isFirstOrLastRecurringPayment,
562 $ids['contributionPage'],
570 * Copy custom data of the initial contribution into its recurring contributions.
572 * @param int $recurId
573 * @param int $targetContributionId
575 static public function copyCustomValues($recurId, $targetContributionId) {
576 if ($recurId && $targetContributionId) {
577 // get the initial contribution id of recur id
578 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
580 // if the same contribution is being processed then return
581 if ($sourceContributionId == $targetContributionId) {
584 // check if proper recurring contribution record is being processed
585 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
586 if ($targetConRecurId != $recurId) {
591 $extends = array('Contribution');
592 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
594 foreach ($groupTree as $groupID => $group) {
595 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
596 foreach ($group['fields'] as $fieldID => $field) {
597 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
601 foreach ($table as $tableName => $tableColumns) {
602 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
603 $tableColumns[0] = $targetContributionId;
604 $select = 'SELECT ' . implode(', ', $tableColumns);
605 $from = ' FROM ' . $tableName;
606 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
607 $query = $insert . $select . $from . $where;
608 CRM_Core_DAO
::executeQuery($query);
615 * Add soft credit to for recurring payment.
617 * copy soft credit record of first recurring contribution.
618 * and add new soft credit against $targetContributionId
620 * @param int $recurId
621 * @param int $targetContributionId
623 public static function addrecurSoftCredit($recurId, $targetContributionId) {
624 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
625 $soft_contribution->contribution_id
= CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
627 // Check if first recurring contribution has any associated soft credit.
628 if ($soft_contribution->find(TRUE)) {
629 $soft_contribution->contribution_id
= $targetContributionId;
630 unset($soft_contribution->id
);
631 $soft_contribution->save();
636 * Add line items for recurring contribution.
638 * @param int $recurId
639 * @param \CRM_Contribute_BAO_Contribution $contribution
643 public static function addRecurLineItems($recurId, $contribution) {
644 $foundLineItems = FALSE;
646 $lineSets = self
::calculateRecurLineItems($recurId, $contribution->total_amount
, $contribution->financial_type_id
);
647 foreach ($lineSets as $lineItems) {
648 if (!empty($lineItems)) {
649 foreach ($lineItems as $key => $value) {
650 if ($value['entity_table'] == 'civicrm_membership') {
652 // @todo this should be done by virtue of editing the line item as this link
653 // is deprecated. This may be the case but needs testing.
654 civicrm_api3('membership_payment', 'create', array(
655 'membership_id' => $value['entity_id'],
656 'contribution_id' => $contribution->id
,
657 'is_transactional' => FALSE,
660 catch (CiviCRM_API3_Exception
$e) {
661 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
662 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
666 $foundLineItems = TRUE;
669 if (!$foundLineItems) {
670 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
676 * Update pledge associated with a recurring contribution.
678 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
680 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
681 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
682 * it should be assumed they
683 * do so with the intention that all payments will be linked
685 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
686 * If not the contribution will also need to be linked to the pledge
688 * @param int $contributionID
689 * @param int $contributionRecurID
690 * @param int $contributionStatusID
691 * @param float $contributionAmount
693 * @throws \CiviCRM_API3_Exception
695 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
696 $returnProperties = array('id', 'pledge_id');
697 $paymentDetails = $paymentIDs = array();
699 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
700 $paymentDetails, $returnProperties
703 foreach ($paymentDetails as $key => $value) {
704 $paymentIDs[] = $value['id'];
705 $pledgeId = $value['pledge_id'];
709 //payment is not already linked - if it is linked with a pledge we need to create a link.
710 // return if it is not recurring contribution
711 if (!$contributionRecurID) {
715 $relatedContributions = new CRM_Contribute_DAO_Contribution();
716 $relatedContributions->contribution_recur_id
= $contributionRecurID;
717 $relatedContributions->find();
719 while ($relatedContributions->fetch()) {
720 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
721 $paymentDetails, $returnProperties
725 if (empty($paymentDetails)) {
726 // payment is not linked with a pledge and neither are any other contributions on this
730 foreach ($paymentDetails as $key => $value) {
731 $pledgeId = $value['pledge_id'];
734 // we have a pledge now we need to get the oldest unpaid payment
735 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
736 if (empty($paymentDetails['id'])) {
737 // we can assume this pledge is now completed
738 // return now so we don't create a core error & roll back
741 $paymentDetails['contribution_id'] = $contributionID;
742 $paymentDetails['status_id'] = $contributionStatusID;
743 $paymentDetails['actual_amount'] = $contributionAmount;
745 // put contribution against it
746 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
747 $paymentIDs[] = $payment['id'];
750 // update pledge and corresponding payment statuses
751 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
752 NULL, $contributionAmount
757 * @param CRM_Core_Form $form
759 public static function recurringContribution(&$form) {
760 // Recurring contribution fields
761 foreach (self
::getRecurringFields() as $key => $label) {
762 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues
) &&
763 !CRM_Utils_System
::isNull(CRM_Utils_Array
::value($key, $form->_formValues
))
765 $form->assign('contribution_recur_pane_open', TRUE);
768 CRM_Core_Form_Date
::buildDateRange($form, $key, 1, '_low', '_high');
769 // If data has been entered for a recurring field, tell the tpl layer to open the pane
770 if (!empty($form->_formValues
) && !empty($form->_formValues
[$key . '_relative']) ||
!empty($form->_formValues
[$key . '_low']) ||
!empty($form->_formValues
[$key . '_high'])) {
771 $form->assign('contribution_recur_pane_open', TRUE);
776 // Add field to check if payment is made for recurring contribution
777 $recurringPaymentOptions = array(
778 1 => ts('All recurring contributions'),
779 2 => ts('Recurring contributions with at least one payment'),
781 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
782 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
783 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
784 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
785 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
786 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
787 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
789 // Add field for contribution status
790 $form->addSelect('contribution_recur_contribution_status_id',
791 array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_PseudoConstant
::contributionStatus())
794 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
795 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
797 CRM_Core_BAO_Query
::addCustomFormFields($form, array('ContributionRecur'));
802 * Get fields for recurring contributions.
806 public static function getRecurringFields() {
808 'contribution_recur_payment_made' => ts(''),
809 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
810 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
811 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
812 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
813 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
814 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
815 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
820 * Update recurring contribution based on incoming payment.
822 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
824 * @param int $recurringContributionID
825 * @param string $paymentStatus
826 * Payment status - this correlates to the machine name of the contribution status ID ie
830 * @throws \CiviCRM_API3_Exception
832 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
834 $effectiveDate = $effectiveDate ?
date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
835 if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
839 'id' => $recurringContributionID,
841 'contribution_status_id',
842 'next_sched_contribution_date',
844 'frequency_interval',
850 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
852 if ($paymentStatus == 'Completed'
853 && CRM_Contribute_PseudoConstant
::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
854 $params['contribution_status_id'] = 'In Progress';
856 if ($paymentStatus == 'Failed') {
857 $params['failure_count'] = $existing['failure_count'];
859 $params['modified_date'] = date('Y-m-d H:i:s');
861 if (!empty($existing['installments']) && self
::isComplete($recurringContributionID, $existing['installments'])) {
862 $params['contribution_status_id'] = 'Completed';
865 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
866 // the scheduled date themselves as core did not previously provide any help.
867 if (empty($existing['next_sched_contribution_date']) ||
strtotime($existing['next_sched_contribution_date']) ==
868 strtotime($effectiveDate)) {
869 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
872 civicrm_api3('ContributionRecur', 'create', $params);
876 * Is this recurring contribution now complete.
878 * Have all the payments expected been received now.
880 * @param int $recurringContributionID
881 * @param int $installments
885 protected static function isComplete($recurringContributionID, $installments) {
886 $paidInstallments = CRM_Core_DAO
::singleValueQuery(
887 'SELECT count(*) FROM civicrm_contribution
888 WHERE contribution_recur_id = %1
889 AND contribution_status_id = ' . CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
890 array(1 => array($recurringContributionID, 'Integer'))
892 if ($paidInstallments >= $installments) {
899 * Calculate line items for the relevant recurring calculation.
901 * @param int $recurId
902 * @param string $total_amount
903 * @param int $financial_type_id
907 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
908 $originalContribution = civicrm_api3('Contribution', 'getsingle', array(
909 'contribution_recur_id' => $recurId,
910 'contribution_test' => '',
911 'options' => ['limit' => 1],
912 'return' => ['id', 'financial_type_id'],
914 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContribution['id']);
916 if (count($lineItems) == 1) {
917 foreach ($lineItems as $index => $lineItem) {
918 if ($lineItem['financial_type_id'] != $originalContribution['financial_type_id']) {
919 // 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.
920 $financial_type_id = $lineItem['financial_type_id'];
922 if ($financial_type_id) {
923 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
924 $lineItem['financial_type_id'] = $financial_type_id;
926 if ($lineItem['line_total'] != $total_amount) {
927 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
928 // if there is only one line item, and the UI should prevent this situation for those with more than one.
929 $lineItem['line_total'] = $total_amount;
930 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
932 $priceField = new CRM_Price_DAO_PriceField();
933 $priceField->id
= $lineItem['price_field_id'];
934 $priceField->find(TRUE);
935 $lineSets[$priceField->price_set_id
][] = $lineItem;
938 // CRM-19309 if more than one then just pass them through:
939 elseif (count($lineItems) > 1) {
940 foreach ($lineItems as $index => $lineItem) {
941 $lineSets[$index][] = $lineItem;
949 * Returns array with statuses that are considered to make a recurring
950 * contribution inacteve.
954 public static function getInactiveStatuses() {
955 return self
::$inactiveStatuses;