3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
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 * Create recurring contribution.
38 * @param array $params
39 * (reference ) an assoc array of name/value pairs.
42 * activity contact object
44 public static function create(&$params) {
45 return self
::add($params);
49 * Takes an associative array and creates a contribution object.
51 * the function extract all the params it needs to initialize the create a
52 * contribution object. the params array could contain additional unused name/value
55 * @param array $params
56 * (reference ) an assoc array of name/value pairs.
58 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
59 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
61 public static function add(&$params) {
62 if (!empty($params['id'])) {
63 CRM_Utils_Hook
::pre('edit', 'ContributionRecur', $params['id'], $params);
66 CRM_Utils_Hook
::pre('create', 'ContributionRecur', NULL, $params);
69 // make sure we're not creating a new recurring contribution with the same transaction ID
70 // or invoice ID as an existing recurring contribution
71 $duplicates = array();
72 if (self
::checkDuplicate($params, $duplicates)) {
73 $error = CRM_Core_Error
::singleton();
74 $d = implode(', ', $duplicates);
75 $error->push(CRM_Core_Error
::DUPLICATE_CONTRIBUTION
,
78 "Found matching recurring contribution(s): $d"
83 $recurring = new CRM_Contribute_BAO_ContributionRecur();
84 $recurring->copyValues($params);
85 $recurring->id
= CRM_Utils_Array
::value('id', $params);
87 // set currency for CRM-1496
88 if (empty($params['id']) && !isset($recurring->currency
)) {
89 $config = CRM_Core_Config
::singleton();
90 $recurring->currency
= $config->defaultCurrency
;
92 $result = $recurring->save();
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::post('edit', 'ContributionRecur', $recurring->id
, $recurring);
98 CRM_Utils_Hook
::post('create', 'ContributionRecur', $recurring->id
, $recurring);
101 if (!empty($params['custom']) &&
102 is_array($params['custom'])
104 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution_recur', $recurring->id
);
111 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
113 * @param array $params
114 * (reference ) an assoc array of name/value pairs.
115 * @param array $duplicates
116 * (reference ) store ids of duplicate contributions.
119 * true if duplicate, false otherwise
121 public static function checkDuplicate($params, &$duplicates) {
122 $id = CRM_Utils_Array
::value('id', $params);
123 $trxn_id = CRM_Utils_Array
::value('trxn_id', $params);
124 $invoice_id = CRM_Utils_Array
::value('invoice_id', $params);
130 $clause[] = "trxn_id = %1";
131 $params[1] = array($trxn_id, 'String');
135 $clause[] = "invoice_id = %2";
136 $params[2] = array($invoice_id, 'String');
139 if (empty($clause)) {
143 $clause = implode(' OR ', $clause);
145 $clause = "( $clause ) AND id != %3";
146 $params[3] = array($id, 'Integer');
149 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
150 $dao = CRM_Core_DAO
::executeQuery($query, $params);
152 while ($dao->fetch()) {
153 $duplicates[] = $dao->id
;
160 * Get the payment processor (array) for a recurring processor.
163 * @param string $mode
164 * - Test or NULL - all other variants are ignored.
168 public static function getPaymentProcessor($id, $mode = NULL) {
170 SELECT r.payment_processor_id
171 FROM civicrm_contribution_recur r
173 $params = array(1 => array($id, 'Integer'));
174 $paymentProcessorID = CRM_Core_DAO
::singleValueQuery($sql,
177 if (!$paymentProcessorID) {
181 return CRM_Financial_BAO_PaymentProcessor
::getPayment($paymentProcessorID, $mode);
185 * Get the number of installment done/completed for each recurring contribution.
188 * (reference ) an array of recurring contribution ids.
191 * an array of recurring ids count
193 public static function getCount(&$ids) {
194 $recurID = implode(',', $ids);
195 $totalCount = array();
198 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
199 FROM civicrm_contribution
200 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
201 GROUP BY contribution_recur_id";
203 $res = CRM_Core_DAO
::executeQuery($query);
205 while ($res->fetch()) {
206 $totalCount[$res->contribution_recur_id
] = $res->commpleted
;
212 * Delete Recurring contribution.
214 * @param int $recurId
218 public static function deleteRecurContribution($recurId) {
224 $recur = new CRM_Contribute_DAO_ContributionRecur();
225 $recur->id
= $recurId;
226 $result = $recur->delete();
232 * Cancel Recurring contribution.
234 * @param int $recurId
235 * Recur contribution id.
236 * @param array $objects
237 * An array of objects that is to be cancelled like.
238 * contribution, membership, event. At least contribution object is a must.
240 * @param array $activityParams
244 public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
249 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
250 $canceledId = array_search('Cancelled', $contributionStatus);
251 $recur = new CRM_Contribute_DAO_ContributionRecur();
252 $recur->id
= $recurId;
253 $recur->whereAdd("contribution_status_id != $canceledId");
255 if ($recur->find(TRUE)) {
256 $transaction = new CRM_Core_Transaction();
257 $recur->contribution_status_id
= $canceledId;
258 $recur->start_date
= CRM_Utils_Date
::isoToMysql($recur->start_date
);
259 $recur->create_date
= CRM_Utils_Date
::isoToMysql($recur->create_date
);
260 $recur->modified_date
= CRM_Utils_Date
::isoToMysql($recur->modified_date
);
261 $recur->cancel_date
= date('YmdHis');
264 $dao = CRM_Contribute_BAO_ContributionRecur
::getSubscriptionDetails($recurId);
265 if ($dao && $dao->recur_id
) {
266 $details = CRM_Utils_Array
::value('details', $activityParams);
267 if ($dao->auto_renew
&& $dao->membership_id
) {
268 // its auto-renewal membership mode
269 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
270 $membershipType = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id
, 'membership_type_id');
271 $membershipType = CRM_Utils_Array
::value($membershipType, $membershipTypes);
273 <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
277 <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
279 2 => $dao->frequency_interval
,
280 3 => $dao->frequency_unit
,
283 $activityParams = array(
284 'source_contact_id' => $dao->contact_id
,
285 'source_record_id' => CRM_Utils_Array
::value('source_record_id', $activityParams),
286 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Cancel Recurring Contribution'),
287 'subject' => CRM_Utils_Array
::value('subject', $activityParams, ts('Recurring contribution cancelled')),
288 'details' => $details,
289 'activity_date_time' => date('YmdHis'),
290 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
292 $session = CRM_Core_Session
::singleton();
293 $cid = $session->get('userID');
295 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
296 $activityParams['source_contact_id'] = $cid;
298 // @todo use the api & do less wrangling above
299 CRM_Activity_BAO_Activity
::create($activityParams);
302 // if there are associated objects, cancel them as well
304 $transaction->commit();
308 // @todo - this is bad! Get the function out of the ipn.
309 $baseIPN = new CRM_Core_Payment_BaseIPN();
310 return $baseIPN->cancelled($objects, $transaction);
314 // if already cancelled, return true
316 $recur->whereAdd("contribution_status_id = $canceledId");
317 if ($recur->find(TRUE)) {
326 * Get list of recurring contribution of contact Ids.
328 * @param int $contactId
332 * list of recurring contribution fields
335 public static function getRecurContributions($contactId) {
337 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
338 $recurDAO->contact_id
= $contactId;
340 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
342 while ($recurDAO->fetch()) {
343 $params[$recurDAO->id
]['id'] = $recurDAO->id
;
344 $params[$recurDAO->id
]['contactId'] = $recurDAO->contact_id
;
345 $params[$recurDAO->id
]['start_date'] = $recurDAO->start_date
;
346 $params[$recurDAO->id
]['end_date'] = $recurDAO->end_date
;
347 $params[$recurDAO->id
]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date
;
348 $params[$recurDAO->id
]['amount'] = $recurDAO->amount
;
349 $params[$recurDAO->id
]['currency'] = $recurDAO->currency
;
350 $params[$recurDAO->id
]['frequency_unit'] = $recurDAO->frequency_unit
;
351 $params[$recurDAO->id
]['frequency_interval'] = $recurDAO->frequency_interval
;
352 $params[$recurDAO->id
]['installments'] = $recurDAO->installments
;
353 $params[$recurDAO->id
]['contribution_status_id'] = $recurDAO->contribution_status_id
;
354 $params[$recurDAO->id
]['contribution_status'] = CRM_Utils_Array
::value($recurDAO->contribution_status_id
, $contributionStatus);
355 $params[$recurDAO->id
]['is_test'] = $recurDAO->is_test
;
356 $params[$recurDAO->id
]['payment_processor_id'] = $recurDAO->payment_processor_id
;
363 * @param int $entityID
364 * @param string $entity
366 * @return null|Object
368 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
370 SELECT rec.id as recur_id,
371 rec.processor_id as subscription_id,
372 rec.frequency_interval,
380 rec.financial_type_id,
381 rec.next_sched_contribution_date,
382 rec.failure_retry_date,
384 con.id as contribution_id,
385 con.contribution_page_id,
389 if ($entity == 'recur') {
391 FROM civicrm_contribution_recur rec
392 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
393 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
396 elseif ($entity == 'contribution') {
398 FROM civicrm_contribution con
399 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
400 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
403 elseif ($entity == 'membership') {
405 FROM civicrm_membership_payment mp
406 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
407 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
408 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
409 WHERE mp.membership_id = %1";
412 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($entityID, 'Integer')));
422 * Does the recurring contribution support financial type change.
424 * This is conditional on there being only one line item or if there are no contributions as yet.
426 * (This second is a bit of an unusual condition but might occur in the context of a
432 public static function supportsFinancialTypeChange($id) {
433 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
434 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
435 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
438 $contribution = self
::getTemplateContribution($id);
439 return CRM_Contribute_BAO_Contribution
::isSingleLineItem($contribution['id']);
443 * Get the contribution to be used as the template for later contributions.
445 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
448 * @param array $overrides
449 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
452 * @throws \CiviCRM_API3_Exception
454 public static function getTemplateContribution($id, $overrides = array()) {
455 $templateContribution = civicrm_api3('Contribution', 'get', array(
456 'contribution_recur_id' => $id,
457 'options' => array('limit' => 1, 'sort' => array('id DESC')),
459 'contribution_test' => '',
461 if ($templateContribution['count']) {
462 $result = array_merge($templateContribution['values'][0], $overrides);
463 $result['line_item'] = CRM_Contribute_BAO_ContributionRecur
::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
469 public static function setSubscriptionContext() {
470 // handle context redirection for subscription url
471 $session = CRM_Core_Session
::singleton();
472 if ($session->get('userID')) {
474 $cid = CRM_Utils_Request
::retrieve('cid', 'Integer');
475 $mid = CRM_Utils_Request
::retrieve('mid', 'Integer');
476 $qfkey = CRM_Utils_Request
::retrieve('key', 'String');
477 $context = CRM_Utils_Request
::retrieve('context', 'String');
481 $url = CRM_Utils_System
::url('civicrm/contact/view',
482 "reset=1&selectedChild=contribute&cid={$cid}"
487 $url = CRM_Utils_System
::url('civicrm/contact/view',
488 "reset=1&selectedChild=member&cid={$cid}"
493 $url = CRM_Utils_System
::url('civicrm/user', "reset=1&id={$cid}");
500 $url = CRM_Utils_System
::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
504 $url = CRM_Utils_System
::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
509 $session->pushUserContext($url);
515 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
517 * @param array $fields
518 * The input form values.
519 * @param array $files
520 * The uploaded files if any.
521 * @param CRM_Core_Form $self
522 * @param array $errors
524 public static function validateRecurContribution($fields, $files, $self, &$errors) {
525 if (!empty($fields['is_recur'])) {
526 if ($fields['frequency_interval'] <= 0) {
527 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
529 if ($fields['frequency_unit'] == '0') {
530 $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).');
536 * Send start or end notification for recurring payments.
539 * @param CRM_Contribute_BAO_ContributionRecur $recur
540 * @param bool $isFirstOrLastRecurringPayment
542 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
543 if ($isFirstOrLastRecurringPayment) {
544 $autoRenewMembership = FALSE;
546 isset($ids['membership']) && $ids['membership']
548 $autoRenewMembership = TRUE;
551 //send recurring Notification email for user
552 CRM_Contribute_BAO_ContributionPage
::recurringNotify($isFirstOrLastRecurringPayment,
554 $ids['contributionPage'],
562 * Copy custom data of the initial contribution into its recurring contributions.
564 * @param int $recurId
565 * @param int $targetContributionId
567 static public function copyCustomValues($recurId, $targetContributionId) {
568 if ($recurId && $targetContributionId) {
569 // get the initial contribution id of recur id
570 $sourceContributionId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
572 // if the same contribution is being processed then return
573 if ($sourceContributionId == $targetContributionId) {
576 // check if proper recurring contribution record is being processed
577 $targetConRecurId = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
578 if ($targetConRecurId != $recurId) {
583 $extends = array('Contribution');
584 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
586 foreach ($groupTree as $groupID => $group) {
587 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
588 foreach ($group['fields'] as $fieldID => $field) {
589 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
593 foreach ($table as $tableName => $tableColumns) {
594 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
595 $tableColumns[0] = $targetContributionId;
596 $select = 'SELECT ' . implode(', ', $tableColumns);
597 $from = ' FROM ' . $tableName;
598 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
599 $query = $insert . $select . $from . $where;
600 CRM_Core_DAO
::executeQuery($query);
607 * Add soft credit to for recurring payment.
609 * copy soft credit record of first recurring contribution.
610 * and add new soft credit against $targetContributionId
612 * @param int $recurId
613 * @param int $targetContributionId
615 public static function addrecurSoftCredit($recurId, $targetContributionId) {
616 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
617 $soft_contribution->contribution_id
= CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
619 // Check if first recurring contribution has any associated soft credit.
620 if ($soft_contribution->find(TRUE)) {
621 $soft_contribution->contribution_id
= $targetContributionId;
622 unset($soft_contribution->id
);
623 $soft_contribution->save();
628 * Add line items for recurring contribution.
630 * @param int $recurId
631 * @param \CRM_Contribute_BAO_Contribution $contribution
635 public static function addRecurLineItems($recurId, $contribution) {
636 $foundLineItems = FALSE;
638 $lineSets = self
::calculateRecurLineItems($recurId, $contribution->total_amount
, $contribution->financial_type_id
);
639 foreach ($lineSets as $lineItems) {
640 if (!empty($lineItems)) {
641 foreach ($lineItems as $key => $value) {
642 if ($value['entity_table'] == 'civicrm_membership') {
644 // @todo this should be done by virtue of editing the line item as this link
645 // is deprecated. This may be the case but needs testing.
646 civicrm_api3('membership_payment', 'create', array(
647 'membership_id' => $value['entity_id'],
648 'contribution_id' => $contribution->id
,
649 'is_transactional' => FALSE,
652 catch (CiviCRM_API3_Exception
$e) {
653 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
654 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
658 $foundLineItems = TRUE;
661 if (!$foundLineItems) {
662 CRM_Price_BAO_LineItem
::processPriceSet($contribution->id
, $lineSets, $contribution);
668 * Update pledge associated with a recurring contribution.
670 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
672 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
673 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
674 * it should be assumed they
675 * do so with the intention that all payments will be linked
677 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
678 * If not the contribution will also need to be linked to the pledge
680 * @param int $contributionID
681 * @param int $contributionRecurID
682 * @param int $contributionStatusID
683 * @param float $contributionAmount
685 * @throws \CiviCRM_API3_Exception
687 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
688 $returnProperties = array('id', 'pledge_id');
689 $paymentDetails = $paymentIDs = array();
691 if (CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
692 $paymentDetails, $returnProperties
695 foreach ($paymentDetails as $key => $value) {
696 $paymentIDs[] = $value['id'];
697 $pledgeId = $value['pledge_id'];
701 //payment is not already linked - if it is linked with a pledge we need to create a link.
702 // return if it is not recurring contribution
703 if (!$contributionRecurID) {
707 $relatedContributions = new CRM_Contribute_DAO_Contribution();
708 $relatedContributions->contribution_recur_id
= $contributionRecurID;
709 $relatedContributions->find();
711 while ($relatedContributions->fetch()) {
712 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id
,
713 $paymentDetails, $returnProperties
717 if (empty($paymentDetails)) {
718 // payment is not linked with a pledge and neither are any other contributions on this
722 foreach ($paymentDetails as $key => $value) {
723 $pledgeId = $value['pledge_id'];
726 // we have a pledge now we need to get the oldest unpaid payment
727 $paymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($pledgeId);
728 if (empty($paymentDetails['id'])) {
729 // we can assume this pledge is now completed
730 // return now so we don't create a core error & roll back
733 $paymentDetails['contribution_id'] = $contributionID;
734 $paymentDetails['status_id'] = $contributionStatusID;
735 $paymentDetails['actual_amount'] = $contributionAmount;
737 // put contribution against it
738 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
739 $paymentIDs[] = $payment['id'];
742 // update pledge and corresponding payment statuses
743 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
744 NULL, $contributionAmount
749 * @param CRM_Core_Form $form
751 public static function recurringContribution(&$form) {
752 // Recurring contribution fields
753 foreach (self
::getRecurringFields() as $key => $label) {
754 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues
) &&
755 !CRM_Utils_System
::isNull(CRM_Utils_Array
::value($key, $form->_formValues
))
757 $form->assign('contribution_recur_pane_open', TRUE);
760 CRM_Core_Form_Date
::buildDateRange($form, $key, 1, '_low', '_high');
761 // If data has been entered for a recurring field, tell the tpl layer to open the pane
762 if (!empty($form->_formValues
) && !empty($form->_formValues
[$key . '_relative']) ||
!empty($form->_formValues
[$key . '_low']) ||
!empty($form->_formValues
[$key . '_high'])) {
763 $form->assign('contribution_recur_pane_open', TRUE);
768 // Add field to check if payment is made for recurring contribution
769 $recurringPaymentOptions = array(
770 1 => ts('All recurring contributions'),
771 2 => ts('Recurring contributions with at least one payment'),
773 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
774 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
775 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
776 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
777 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
778 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
779 CRM_Core_Form_Date
::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
781 // Add field for contribution status
782 $form->addSelect('contribution_recur_contribution_status_id',
783 array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_PseudoConstant
::contributionStatus())
786 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
787 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
789 CRM_Core_BAO_Query
::addCustomFormFields($form, array('ContributionRecur'));
794 * Get fields for recurring contributions.
798 public static function getRecurringFields() {
800 'contribution_recur_payment_made' => ts(''),
801 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
802 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
803 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
804 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
805 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
806 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
807 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
812 * Update recurring contribution based on incoming payment.
814 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
816 * @param int $recurringContributionID
817 * @param string $paymentStatus
818 * Payment status - this correlates to the machine name of the contribution status ID ie
822 * @throws \CiviCRM_API3_Exception
824 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
826 $effectiveDate = $effectiveDate ?
date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
827 if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
831 'id' => $recurringContributionID,
833 'contribution_status_id',
834 'next_sched_contribution_date',
836 'frequency_interval',
842 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
844 if ($paymentStatus == 'Completed'
845 && CRM_Contribute_PseudoConstant
::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
846 $params['contribution_status_id'] = 'In Progress';
848 if ($paymentStatus == 'Failed') {
849 $params['failure_count'] = $existing['failure_count'];
851 $params['modified_date'] = date('Y-m-d H:i:s');
853 if (!empty($existing['installments']) && self
::isComplete($recurringContributionID, $existing['installments'])) {
854 $params['contribution_status_id'] = 'Completed';
857 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
858 // the scheduled date themselves as core did not previously provide any help.
859 if (empty($existing['next_sched_contribution_date']) ||
strtotime($existing['next_sched_contribution_date']) ==
860 strtotime($effectiveDate)) {
861 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
864 civicrm_api3('ContributionRecur', 'create', $params);
868 * Is this recurring contribution now complete.
870 * Have all the payments expected been received now.
872 * @param int $recurringContributionID
873 * @param int $installments
877 protected static function isComplete($recurringContributionID, $installments) {
878 $paidInstallments = CRM_Core_DAO
::singleValueQuery(
879 'SELECT count(*) FROM civicrm_contribution
880 WHERE contribution_recur_id = %1
881 AND contribution_status_id = ' . CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
882 array(1 => array($recurringContributionID, 'Integer'))
884 if ($paidInstallments >= $installments) {
891 * Calculate line items for the relevant recurring calculation.
893 * @param int $recurId
894 * @param string $total_amount
895 * @param int $financial_type_id
899 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
900 $originalContribution = civicrm_api3('Contribution', 'getsingle', array(
901 'contribution_recur_id' => $recurId,
902 'contribution_test' => '',
903 'options' => ['limit' => 1],
904 'return' => ['id', 'financial_type_id'],
906 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($originalContribution['id']);
908 if (count($lineItems) == 1) {
909 foreach ($lineItems as $index => $lineItem) {
910 if ($lineItem['financial_type_id'] != $originalContribution['financial_type_id']) {
911 // 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.
912 $financial_type_id = $lineItem['financial_type_id'];
914 if ($financial_type_id) {
915 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
916 $lineItem['financial_type_id'] = $financial_type_id;
918 if ($lineItem['line_total'] != $total_amount) {
919 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
920 // if there is only one line item, and the UI should prevent this situation for those with more than one.
921 $lineItem['line_total'] = $total_amount;
922 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
924 $priceField = new CRM_Price_DAO_PriceField();
925 $priceField->id
= $lineItem['price_field_id'];
926 $priceField->find(TRUE);
927 $lineSets[$priceField->price_set_id
][] = $lineItem;
930 // CRM-19309 if more than one then just pass them through:
931 elseif (count($lineItems) > 1) {
932 foreach ($lineItems as $index => $lineItem) {
933 $lineSets[$index][] = $lineItem;