b5a94192c47b39f8ed58d972436d434449ba6eb9
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33 class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
34
35 /**
36 * Create recurring contribution.
37 *
38 * @param array $params
39 * (reference ) an assoc array of name/value pairs.
40 *
41 * @return object
42 * activity contact object
43 */
44 public static function create(&$params) {
45 return self::add($params);
46 }
47
48 /**
49 * Takes an associative array and creates a contribution object.
50 *
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
53 * pairs
54 *
55 * @param array $params
56 * (reference ) an assoc array of name/value pairs.
57 *
58 * @return CRM_Contribute_BAO_Contribution
59 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
60 */
61 public static function add(&$params) {
62 if (!empty($params['id'])) {
63 CRM_Utils_Hook::pre('edit', 'ContributionRecur', $params['id'], $params);
64 }
65 else {
66 CRM_Utils_Hook::pre('create', 'ContributionRecur', NULL, $params);
67 }
68
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,
76 'Fatal',
77 array($d),
78 "Found matching recurring contribution(s): $d"
79 );
80 return $error;
81 }
82
83 $recurring = new CRM_Contribute_BAO_ContributionRecur();
84 $recurring->copyValues($params);
85 $recurring->id = CRM_Utils_Array::value('id', $params);
86
87 // set currency for CRM-1496
88 if (!isset($recurring->currency)) {
89 $config = CRM_Core_Config::singleton();
90 $recurring->currency = $config->defaultCurrency;
91 }
92 $result = $recurring->save();
93
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook::post('edit', 'ContributionRecur', $recurring->id, $recurring);
96 }
97 else {
98 CRM_Utils_Hook::post('create', 'ContributionRecur', $recurring->id, $recurring);
99 }
100
101 if (!empty($params['custom']) &&
102 is_array($params['custom'])
103 ) {
104 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution_recur', $recurring->id);
105 }
106
107 return $result;
108 }
109
110 /**
111 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
112 *
113 * @param array $params
114 * (reference ) an assoc array of name/value pairs.
115 * @param array $duplicates
116 * (reference ) store ids of duplicate contribs.
117 *
118 * @return bool
119 * true if duplicate, false otherwise
120 */
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);
125
126 $clause = array();
127 $params = array();
128
129 if ($trxn_id) {
130 $clause[] = "trxn_id = %1";
131 $params[1] = array($trxn_id, 'String');
132 }
133
134 if ($invoice_id) {
135 $clause[] = "invoice_id = %2";
136 $params[2] = array($invoice_id, 'String');
137 }
138
139 if (empty($clause)) {
140 return FALSE;
141 }
142
143 $clause = implode(' OR ', $clause);
144 if ($id) {
145 $clause = "( $clause ) AND id != %3";
146 $params[3] = array($id, 'Integer');
147 }
148
149 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
150 $dao = CRM_Core_DAO::executeQuery($query, $params);
151 $result = FALSE;
152 while ($dao->fetch()) {
153 $duplicates[] = $dao->id;
154 $result = TRUE;
155 }
156 return $result;
157 }
158
159 /**
160 * @param int $id
161 * @param $mode
162 *
163 * @return array|null
164 */
165 public static function getPaymentProcessor($id, $mode) {
166 //FIX ME:
167 $sql = "
168 SELECT r.payment_processor_id
169 FROM civicrm_contribution_recur r
170 WHERE r.id = %1";
171 $params = array(1 => array($id, 'Integer'));
172 $paymentProcessorID = &CRM_Core_DAO::singleValueQuery($sql,
173 $params
174 );
175 if (!$paymentProcessorID) {
176 return NULL;
177 }
178
179 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
180 }
181
182 /**
183 * Get the number of installment done/completed for each recurring contribution
184 *
185 * @param array $ids
186 * (reference ) an array of recurring contribution ids.
187 *
188 * @return array
189 * an array of recurring ids count
190 */
191 public static function getCount(&$ids) {
192 $recurID = implode(',', $ids);
193 $totalCount = array();
194
195 $query = "
196 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
197 FROM civicrm_contribution
198 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
199 GROUP BY contribution_recur_id";
200
201 $res = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
202
203 while ($res->fetch()) {
204 $totalCount[$res->contribution_recur_id] = $res->commpleted;
205 }
206 return $totalCount;
207 }
208
209 /**
210 * Delete Recurring contribution.
211 *
212 * @param int $recurId
213 *
214 * @return bool
215 */
216 public static function deleteRecurContribution($recurId) {
217 $result = FALSE;
218 if (!$recurId) {
219 return $result;
220 }
221
222 $recur = new CRM_Contribute_DAO_ContributionRecur();
223 $recur->id = $recurId;
224 $result = $recur->delete();
225
226 return $result;
227 }
228
229 /**
230 * Cancel Recurring contribution.
231 *
232 * @param int $recurId
233 * Recur contribution id.
234 * @param array $objects
235 * An array of objects that is to be cancelled like.
236 * contribution, membership, event. At least contribution object is a must.
237 *
238 * @param array $activityParams
239 *
240 * @return bool
241 */
242 public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
243 if (!$recurId) {
244 return FALSE;
245 }
246
247 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
248 $canceledId = array_search('Cancelled', $contributionStatus);
249 $recur = new CRM_Contribute_DAO_ContributionRecur();
250 $recur->id = $recurId;
251 $recur->whereAdd("contribution_status_id != $canceledId");
252
253 if ($recur->find(TRUE)) {
254 $transaction = new CRM_Core_Transaction();
255 $recur->contribution_status_id = $canceledId;
256 $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
257 $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
258 $recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
259 $recur->cancel_date = date('YmdHis');
260 $recur->save();
261
262 $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
263 if ($dao && $dao->recur_id) {
264 $details = CRM_Utils_Array::value('details', $activityParams);
265 if ($dao->auto_renew && $dao->membership_id) {
266 // its auto-renewal membership mode
267 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
268 $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
269 $membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
270 $details .= '
271 <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
272 }
273 else {
274 $details .= '
275 <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
276 1 => $dao->amount,
277 2 => $dao->frequency_interval,
278 3 => $dao->frequency_unit,
279 ));
280 }
281 $activityParams = array(
282 'source_contact_id' => $dao->contact_id,
283 'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams),
284 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
285 'Cancel Recurring Contribution',
286 'name'
287 ),
288 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
289 'details' => $details,
290 'activity_date_time' => date('YmdHis'),
291 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
292 'Completed',
293 'name'
294 ),
295 );
296 $session = CRM_Core_Session::singleton();
297 $cid = $session->get('userID');
298 if ($cid) {
299 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
300 $activityParams['source_contact_id'] = $cid;
301 }
302 CRM_Activity_BAO_Activity::create($activityParams);
303 }
304
305 // if there are associated objects, cancel them as well
306 if ($objects == CRM_Core_DAO::$_nullObject) {
307 $transaction->commit();
308 return TRUE;
309 }
310 else {
311 $baseIPN = new CRM_Core_Payment_BaseIPN();
312 return $baseIPN->cancelled($objects, $transaction);
313 }
314 }
315 else {
316 // if already cancelled, return true
317 $recur->whereAdd();
318 $recur->whereAdd("contribution_status_id = $canceledId");
319 if ($recur->find(TRUE)) {
320 return TRUE;
321 }
322 }
323
324 return FALSE;
325 }
326
327 /**
328 * Get list of recurring contribution of contact Ids.
329 *
330 * @param int $contactId
331 * Contact ID.
332 *
333 * @return array
334 * list of recurring contribution fields
335 *
336 */
337 public static function getRecurContributions($contactId) {
338 $params = array();
339 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
340 $recurDAO->contact_id = $contactId;
341 $recurDAO->find();
342 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
343
344 while ($recurDAO->fetch()) {
345 $params[$recurDAO->id]['id'] = $recurDAO->id;
346 $params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
347 $params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
348 $params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
349 $params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
350 $params[$recurDAO->id]['amount'] = $recurDAO->amount;
351 $params[$recurDAO->id]['currency'] = $recurDAO->currency;
352 $params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
353 $params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
354 $params[$recurDAO->id]['installments'] = $recurDAO->installments;
355 $params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
356 $params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
357 $params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
358 $params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
359 }
360
361 return $params;
362 }
363
364 /**
365 * @param int $entityID
366 * @param string $entity
367 *
368 * @return null|Object
369 */
370 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
371 $sql = "
372 SELECT rec.id as recur_id,
373 rec.processor_id as subscription_id,
374 rec.frequency_interval,
375 rec.installments,
376 rec.frequency_unit,
377 rec.amount,
378 rec.is_test,
379 rec.auto_renew,
380 rec.currency,
381 rec.campaign_id,
382 con.id as contribution_id,
383 con.contribution_page_id,
384 rec.contact_id,
385 mp.membership_id";
386
387 if ($entity == 'recur') {
388 $sql .= "
389 FROM civicrm_contribution_recur rec
390 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
391 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
392 WHERE rec.id = %1
393 GROUP BY rec.id";
394 }
395 elseif ($entity == 'contribution') {
396 $sql .= "
397 FROM civicrm_contribution con
398 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
399 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
400 WHERE con.id = %1";
401 }
402 elseif ($entity == 'membership') {
403 $sql .= "
404 FROM civicrm_membership_payment mp
405 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
406 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
407 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
408 WHERE mp.membership_id = %1";
409 }
410
411 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
412 if ($dao->fetch()) {
413 return $dao;
414 }
415 else {
416 return CRM_Core_DAO::$_nullObject;
417 }
418 }
419
420 public static function setSubscriptionContext() {
421 // handle context redirection for subscription url
422 $session = CRM_Core_Session::singleton();
423 if ($session->get('userID')) {
424 $url = FALSE;
425 $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
426 $mid = CRM_Utils_Request::retrieve('mid', 'Integer');
427 $qfkey = CRM_Utils_Request::retrieve('key', 'String');
428 $context = CRM_Utils_Request::retrieve('context', 'String');
429 if ($cid) {
430 switch ($context) {
431 case 'contribution':
432 $url = CRM_Utils_System::url('civicrm/contact/view',
433 "reset=1&selectedChild=contribute&cid={$cid}"
434 );
435 break;
436
437 case 'membership':
438 $url = CRM_Utils_System::url('civicrm/contact/view',
439 "reset=1&selectedChild=member&cid={$cid}"
440 );
441 break;
442
443 case 'dashboard':
444 $url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
445 break;
446 }
447 }
448 if ($mid) {
449 switch ($context) {
450 case 'dashboard':
451 $url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
452 break;
453
454 case 'search':
455 $url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
456 break;
457 }
458 }
459 if ($url) {
460 $session->pushUserContext($url);
461 }
462 }
463 }
464
465 /**
466 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
467 *
468 * @param array $fields
469 * The input form values.
470 * @param array $files
471 * The uploaded files if any.
472 * @param CRM_Core_Form $self
473 * @param array $errors
474 */
475 public static function validateRecurContribution($fields, $files, $self, &$errors) {
476 if (!empty($fields['is_recur'])) {
477 if ($fields['frequency_interval'] <= 0) {
478 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
479 }
480 if ($fields['frequency_unit'] == '0') {
481 $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).');
482 }
483 }
484 }
485
486 /**
487 * Send start or end notification for recurring payments.
488 *
489 * @param array $ids
490 * @param CRM_Contribute_BAO_ContributionRecur $recur
491 * @param bool $isFirstOrLastRecurringPayment
492 */
493 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
494 if ($isFirstOrLastRecurringPayment) {
495 $autoRenewMembership = FALSE;
496 if ($recur->id &&
497 isset($ids['membership']) && $ids['membership']
498 ) {
499 $autoRenewMembership = TRUE;
500 }
501
502 //send recurring Notification email for user
503 CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment,
504 $ids['contact'],
505 $ids['contributionPage'],
506 $recur,
507 $autoRenewMembership
508 );
509 }
510 }
511
512 /**
513 * Copy custom data of the initial contribution into its recurring contributions.
514 *
515 * @param int $recurId
516 * @param int $targetContributionId
517 */
518 static public function copyCustomValues($recurId, $targetContributionId) {
519 if ($recurId && $targetContributionId) {
520 // get the initial contribution id of recur id
521 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
522
523 // if the same contribution is being processed then return
524 if ($sourceContributionId == $targetContributionId) {
525 return;
526 }
527 // check if proper recurring contribution record is being processed
528 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
529 if ($targetConRecurId != $recurId) {
530 return;
531 }
532
533 // copy custom data
534 $extends = array('Contribution');
535 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
536 if ($groupTree) {
537 foreach ($groupTree as $groupID => $group) {
538 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
539 foreach ($group['fields'] as $fieldID => $field) {
540 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
541 }
542 }
543
544 foreach ($table as $tableName => $tableColumns) {
545 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
546 $tableColumns[0] = $targetContributionId;
547 $select = 'SELECT ' . implode(', ', $tableColumns);
548 $from = ' FROM ' . $tableName;
549 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
550 $query = $insert . $select . $from . $where;
551 CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
552 }
553 }
554 }
555 }
556
557 /**
558 * Add soft credit to for recurring payment.
559 *
560 * copy soft credit record of first recurring contribution.
561 * and add new soft credit against $targetContributionId
562 *
563 * @param int $recurId
564 * @param int $targetContributionId
565 */
566 public static function addrecurSoftCredit($recurId, $targetContributionId) {
567 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
568 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
569
570 // Check if first recurring contribution has any associated soft credit.
571 if ($soft_contribution->find(TRUE)) {
572 $soft_contribution->contribution_id = $targetContributionId;
573 unset($soft_contribution->id);
574 $soft_contribution->save();
575 }
576 }
577
578 /**
579 * Add line items for recurring contribution.
580 *
581 * @param int $recurId
582 * @param $contribution
583 *
584 * @return array
585 */
586 public static function addRecurLineItems($recurId, $contribution) {
587 $lineSets = array();
588
589 $originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
590 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
591 if (count($lineItems) == 1) {
592 foreach ($lineItems as $index => $lineItem) {
593 if (isset($contribution->financial_type_id)) {
594 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
595 $lineItems[$index]['financial_type_id'] = $contribution->financial_type_id;
596 }
597 if ($lineItem['line_total'] != $contribution->total_amount) {
598 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
599 // if there is only one line item, and the UI should prevent this situation for those with more than one.
600 $lineItems[$index]['line_total'] = $contribution->total_amount;
601 $lineItems[$index]['unit_price'] = round($contribution->total_amount / $lineItems[$index]['qty'], 2);
602 }
603 }
604 }
605 if (!empty($lineItems)) {
606 foreach ($lineItems as $key => $value) {
607 $priceField = new CRM_Price_DAO_PriceField();
608 $priceField->id = $value['price_field_id'];
609 $priceField->find(TRUE);
610 $lineSets[$priceField->price_set_id][] = $value;
611
612 if ($value['entity_table'] == 'civicrm_membership') {
613 try {
614 civicrm_api3('membership_payment', 'create', array(
615 'membership_id' => $value['entity_id'],
616 'contribution_id' => $contribution->id,
617 ));
618 }
619 catch (CiviCRM_API3_Exception $e) {
620 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
621 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
622 }
623 }
624 }
625 }
626 else {
627 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
628 }
629 return $lineSets;
630 }
631
632 /**
633 * Update pledge associated with a recurring contribution.
634 *
635 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
636 *
637 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
638 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
639 * it should be assumed they
640 * do so with the intention that all payments will be linked
641 *
642 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
643 * If not the contribution will also need to be linked to the pledge
644 *
645 * @param CRM_Contribute_BAO_Contribution $contribution
646 */
647 public static function updateRecurLinkedPledge($contribution) {
648 $returnProperties = array('id', 'pledge_id');
649 $paymentDetails = $paymentIDs = array();
650
651 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id,
652 $paymentDetails, $returnProperties
653 )
654 ) {
655 foreach ($paymentDetails as $key => $value) {
656 $paymentIDs[] = $value['id'];
657 $pledgeId = $value['pledge_id'];
658 }
659 }
660 else {
661 //payment is not already linked - if it is linked with a pledge we need to create a link.
662 // return if it is not recurring contribution
663 if (!$contribution->contribution_recur_id) {
664 return;
665 }
666
667 $relatedContributions = new CRM_Contribute_DAO_Contribution();
668 $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
669 $relatedContributions->find();
670
671 while ($relatedContributions->fetch()) {
672 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
673 $paymentDetails, $returnProperties
674 );
675 }
676
677 if (empty($paymentDetails)) {
678 // payment is not linked with a pledge and neither are any other contributions on this
679 return;
680 }
681
682 foreach ($paymentDetails as $key => $value) {
683 $pledgeId = $value['pledge_id'];
684 }
685
686 // we have a pledge now we need to get the oldest unpaid payment
687 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
688 if (empty($paymentDetails['id'])) {
689 // we can assume this pledge is now completed
690 // return now so we don't create a core error & roll back
691 return;
692 }
693 $paymentDetails['contribution_id'] = $contribution->id;
694 $paymentDetails['status_id'] = $contribution->contribution_status_id;
695 $paymentDetails['actual_amount'] = $contribution->total_amount;
696
697 // put contribution against it
698 $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
699 $paymentIDs[] = $payment->id;
700 }
701
702 // update pledge and corresponding payment statuses
703 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id,
704 NULL, $contribution->total_amount
705 );
706 }
707
708 /**
709 * @param $form
710 */
711 public static function recurringContribution(&$form) {
712 // Recurring contribution fields
713 foreach (self::getRecurringFields() as $key => $label) {
714 if ($key == 'contribution_recur_payment_made' &&
715 !CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
716 ) {
717 $form->assign('contribution_recur_pane_open', TRUE);
718 break;
719 }
720 CRM_Core_Form_Date::buildDateRange($form, $key, 1, '_low', '_high');
721 // If data has been entered for a recurring field, tell the tpl layer to open the pane
722 if (!empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
723 $form->assign('contribution_recur_pane_open', TRUE);
724 break;
725 }
726 }
727
728 // Add field to check if payment is made for recurring contribution
729 $recurringPaymentOptions = array(
730 1 => ts(' All recurring contributions'),
731 2 => ts(' Recurring contributions with at least one payment'),
732 );
733 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
734 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
735 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
736 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
737 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
738 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
739 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
740 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
741 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
742 $contributionRecur = array('ContributionRecur');
743 $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $contributionRecur);
744 if ($groupDetails) {
745 $form->assign('contributeRecurGroupTree', $groupDetails);
746 foreach ($groupDetails as $group) {
747 foreach ($group['fields'] as $field) {
748 $fieldId = $field['id'];
749 $elementName = 'custom_' . $fieldId;
750 CRM_Core_BAO_CustomField::addQuickFormElement($form,
751 $elementName,
752 $fieldId,
753 FALSE, FALSE, TRUE
754 );
755 }
756 }
757 }
758 }
759
760 /**
761 * Get fields for recurring contributions.
762 *
763 * @return array
764 */
765 public static function getRecurringFields() {
766 return array(
767 'contribution_recur_payment_made' => ts(''),
768 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
769 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
770 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
771 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
772 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
773 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
774 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
775 );
776 }
777
778 /**
779 * Update recurring contribution based on incoming payment.
780 *
781 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
782 *
783 * @param int $recurringContributionID
784 * @param string $paymentStatus
785 * Payment status - this correlates to the machine name of the contribution status ID ie
786 * - Completed
787 * - Failed
788 *
789 * @throws \CiviCRM_API3_Exception
790 */
791 public static function updateOnNewPayment($recurringContributionID, $paymentStatus) {
792 if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
793 return;
794 }
795 $params = array(
796 'id' => $recurringContributionID,
797 'return' => array(
798 'contribution_status_id',
799 'next_sched_contribution_date',
800 'frequency_unit',
801 'frequency_interval',
802 'installments',
803 'failure_count',
804 ),
805 );
806
807 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
808
809 if ($paymentStatus == 'Completed'
810 && CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
811 $params['contribution_status_id'] = 'In Progress';
812 }
813 if ($paymentStatus == 'Failed') {
814 $params['failure_count'] = $existing['failure_count'];
815 }
816 $params['modified_date'] = date('Y-m-d H:i:s');
817
818 if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
819 $params['contribution_status_id'] = 'Completed';
820 }
821 else {
822 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
823 // the scheduled date themselves as core did not previously provide any help.
824 if (empty($params['next_sched_contribution_date']) || strtotime($params['next_sched_contribution_date']) ==
825 strtotime(date('Y-m-d'))) {
826 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit']));
827 }
828 }
829 civicrm_api3('ContributionRecur', 'create', $params);
830 }
831
832 /**
833 * Is this recurring contribution now complete.
834 *
835 * Have all the payments expected been received now.
836 *
837 * @param int $recurringContributionID
838 * @param int $installments
839 *
840 * @return bool
841 */
842 protected static function isComplete($recurringContributionID, $installments) {
843 $paidInstallments = CRM_Core_DAO::singleValueQuery(
844 'SELECT count(*) FROM civicrm_contribution WHERE id = %1',
845 array(1 => array($recurringContributionID, 'Integer'))
846 );
847 if ($paidInstallments >= $installments) {
848 return TRUE;
849 }
850 return FALSE;
851 }
852
853 }