Merge pull request #10116 from colemanw/CRM-20390
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 (empty($params['id']) && !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 contributions.
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 * Get the payment processor (array) for a recurring processor.
161 *
162 * @param int $id
163 * @param string $mode
164 * - Test or NULL - all other variants are ignored.
165 *
166 * @return array|null
167 */
168 public static function getPaymentProcessor($id, $mode = NULL) {
169 $sql = "
170 SELECT r.payment_processor_id
171 FROM civicrm_contribution_recur r
172 WHERE r.id = %1";
173 $params = array(1 => array($id, 'Integer'));
174 $paymentProcessorID = CRM_Core_DAO::singleValueQuery($sql,
175 $params
176 );
177 if (!$paymentProcessorID) {
178 return NULL;
179 }
180
181 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
182 }
183
184 /**
185 * Get the number of installment done/completed for each recurring contribution.
186 *
187 * @param array $ids
188 * (reference ) an array of recurring contribution ids.
189 *
190 * @return array
191 * an array of recurring ids count
192 */
193 public static function getCount(&$ids) {
194 $recurID = implode(',', $ids);
195 $totalCount = array();
196
197 $query = "
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";
202
203 $res = CRM_Core_DAO::executeQuery($query);
204
205 while ($res->fetch()) {
206 $totalCount[$res->contribution_recur_id] = $res->commpleted;
207 }
208 return $totalCount;
209 }
210
211 /**
212 * Delete Recurring contribution.
213 *
214 * @param int $recurId
215 *
216 * @return bool
217 */
218 public static function deleteRecurContribution($recurId) {
219 $result = FALSE;
220 if (!$recurId) {
221 return $result;
222 }
223
224 $recur = new CRM_Contribute_DAO_ContributionRecur();
225 $recur->id = $recurId;
226 $result = $recur->delete();
227
228 return $result;
229 }
230
231 /**
232 * Cancel Recurring contribution.
233 *
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.
239 *
240 * @param array $activityParams
241 *
242 * @return bool
243 */
244 public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
245 if (!$recurId) {
246 return FALSE;
247 }
248
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");
254
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');
262 $recur->save();
263
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);
272 $details .= '
273 <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
274 }
275 else {
276 $details .= '
277 <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
278 1 => $dao->amount,
279 2 => $dao->frequency_interval,
280 3 => $dao->frequency_unit,
281 ));
282 }
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_OptionGroup::getValue('activity_type',
287 'Cancel Recurring Contribution',
288 'name'
289 ),
290 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
291 'details' => $details,
292 'activity_date_time' => date('YmdHis'),
293 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
294 'Completed',
295 'name'
296 ),
297 );
298 $session = CRM_Core_Session::singleton();
299 $cid = $session->get('userID');
300 if ($cid) {
301 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
302 $activityParams['source_contact_id'] = $cid;
303 }
304 CRM_Activity_BAO_Activity::create($activityParams);
305 }
306
307 // if there are associated objects, cancel them as well
308 if (!$objects) {
309 $transaction->commit();
310 return TRUE;
311 }
312 else {
313 $baseIPN = new CRM_Core_Payment_BaseIPN();
314 return $baseIPN->cancelled($objects, $transaction);
315 }
316 }
317 else {
318 // if already cancelled, return true
319 $recur->whereAdd();
320 $recur->whereAdd("contribution_status_id = $canceledId");
321 if ($recur->find(TRUE)) {
322 return TRUE;
323 }
324 }
325
326 return FALSE;
327 }
328
329 /**
330 * Get list of recurring contribution of contact Ids.
331 *
332 * @param int $contactId
333 * Contact ID.
334 *
335 * @return array
336 * list of recurring contribution fields
337 *
338 */
339 public static function getRecurContributions($contactId) {
340 $params = array();
341 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
342 $recurDAO->contact_id = $contactId;
343 $recurDAO->find();
344 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
345
346 while ($recurDAO->fetch()) {
347 $params[$recurDAO->id]['id'] = $recurDAO->id;
348 $params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
349 $params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
350 $params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
351 $params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
352 $params[$recurDAO->id]['amount'] = $recurDAO->amount;
353 $params[$recurDAO->id]['currency'] = $recurDAO->currency;
354 $params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
355 $params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
356 $params[$recurDAO->id]['installments'] = $recurDAO->installments;
357 $params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
358 $params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
359 $params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
360 $params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
361 }
362
363 return $params;
364 }
365
366 /**
367 * @param int $entityID
368 * @param string $entity
369 *
370 * @return null|Object
371 */
372 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
373 $sql = "
374 SELECT rec.id as recur_id,
375 rec.processor_id as subscription_id,
376 rec.frequency_interval,
377 rec.installments,
378 rec.frequency_unit,
379 rec.amount,
380 rec.is_test,
381 rec.auto_renew,
382 rec.currency,
383 rec.campaign_id,
384 rec.financial_type_id,
385 rec.next_sched_contribution_date,
386 rec.failure_retry_date,
387 rec.cycle_day,
388 con.id as contribution_id,
389 con.contribution_page_id,
390 rec.contact_id,
391 mp.membership_id";
392
393 if ($entity == 'recur') {
394 $sql .= "
395 FROM civicrm_contribution_recur rec
396 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
397 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
398 WHERE rec.id = %1";
399 }
400 elseif ($entity == 'contribution') {
401 $sql .= "
402 FROM civicrm_contribution con
403 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
404 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
405 WHERE con.id = %1";
406 }
407 elseif ($entity == 'membership') {
408 $sql .= "
409 FROM civicrm_membership_payment mp
410 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
411 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
412 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
413 WHERE mp.membership_id = %1";
414 }
415
416 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
417 if ($dao->fetch()) {
418 return $dao;
419 }
420 else {
421 return NULL;
422 }
423 }
424
425 /**
426 * Does the recurring contribution support financial type change.
427 *
428 * This is conditional on there being only one line item or if there are no contributions as yet.
429 *
430 * (This second is a bit of an unusual condition but might occur in the context of a
431 *
432 * @param int $id
433 *
434 * @return bool
435 */
436 public static function supportsFinancialTypeChange($id) {
437 // At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
438 // this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
439 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
440 return FALSE;
441 }
442 $contribution = self::getTemplateContribution($id);
443 return CRM_Contribute_BAO_Contribution::isSingleLineItem($contribution['id']);
444 }
445
446 /**
447 * Get the contribution to be used as the template for later contributions.
448 *
449 * Later we might merge in data stored against the contribution recur record rather than just return the contribution.
450 *
451 * @param int $id
452 * @param array $overrides
453 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
454 *
455 * @return array
456 * @throws \CiviCRM_API3_Exception
457 */
458 public static function getTemplateContribution($id, $overrides = array()) {
459 $templateContribution = civicrm_api3('Contribution', 'get', array(
460 'contribution_recur_id' => $id,
461 'options' => array('limit' => 1, 'sort' => array('id DESC')),
462 'sequential' => 1,
463 'contribution_test' => '',
464 ));
465 if ($templateContribution['count']) {
466 $result = array_merge($templateContribution['values'][0], $overrides);
467 $result['line_item'] = CRM_Contribute_BAO_ContributionRecur::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
468 return $result;
469 }
470 return array();
471 }
472
473 public static function setSubscriptionContext() {
474 // handle context redirection for subscription url
475 $session = CRM_Core_Session::singleton();
476 if ($session->get('userID')) {
477 $url = FALSE;
478 $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
479 $mid = CRM_Utils_Request::retrieve('mid', 'Integer');
480 $qfkey = CRM_Utils_Request::retrieve('key', 'String');
481 $context = CRM_Utils_Request::retrieve('context', 'String');
482 if ($cid) {
483 switch ($context) {
484 case 'contribution':
485 $url = CRM_Utils_System::url('civicrm/contact/view',
486 "reset=1&selectedChild=contribute&cid={$cid}"
487 );
488 break;
489
490 case 'membership':
491 $url = CRM_Utils_System::url('civicrm/contact/view',
492 "reset=1&selectedChild=member&cid={$cid}"
493 );
494 break;
495
496 case 'dashboard':
497 $url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
498 break;
499 }
500 }
501 if ($mid) {
502 switch ($context) {
503 case 'dashboard':
504 $url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
505 break;
506
507 case 'search':
508 $url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
509 break;
510 }
511 }
512 if ($url) {
513 $session->pushUserContext($url);
514 }
515 }
516 }
517
518 /**
519 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
520 *
521 * @param array $fields
522 * The input form values.
523 * @param array $files
524 * The uploaded files if any.
525 * @param CRM_Core_Form $self
526 * @param array $errors
527 */
528 public static function validateRecurContribution($fields, $files, $self, &$errors) {
529 if (!empty($fields['is_recur'])) {
530 if ($fields['frequency_interval'] <= 0) {
531 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
532 }
533 if ($fields['frequency_unit'] == '0') {
534 $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).');
535 }
536 }
537 }
538
539 /**
540 * Send start or end notification for recurring payments.
541 *
542 * @param array $ids
543 * @param CRM_Contribute_BAO_ContributionRecur $recur
544 * @param bool $isFirstOrLastRecurringPayment
545 */
546 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
547 if ($isFirstOrLastRecurringPayment) {
548 $autoRenewMembership = FALSE;
549 if ($recur->id &&
550 isset($ids['membership']) && $ids['membership']
551 ) {
552 $autoRenewMembership = TRUE;
553 }
554
555 //send recurring Notification email for user
556 CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment,
557 $ids['contact'],
558 $ids['contributionPage'],
559 $recur,
560 $autoRenewMembership
561 );
562 }
563 }
564
565 /**
566 * Copy custom data of the initial contribution into its recurring contributions.
567 *
568 * @param int $recurId
569 * @param int $targetContributionId
570 */
571 static public function copyCustomValues($recurId, $targetContributionId) {
572 if ($recurId && $targetContributionId) {
573 // get the initial contribution id of recur id
574 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
575
576 // if the same contribution is being processed then return
577 if ($sourceContributionId == $targetContributionId) {
578 return;
579 }
580 // check if proper recurring contribution record is being processed
581 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
582 if ($targetConRecurId != $recurId) {
583 return;
584 }
585
586 // copy custom data
587 $extends = array('Contribution');
588 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
589 if ($groupTree) {
590 foreach ($groupTree as $groupID => $group) {
591 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
592 foreach ($group['fields'] as $fieldID => $field) {
593 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
594 }
595 }
596
597 foreach ($table as $tableName => $tableColumns) {
598 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
599 $tableColumns[0] = $targetContributionId;
600 $select = 'SELECT ' . implode(', ', $tableColumns);
601 $from = ' FROM ' . $tableName;
602 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
603 $query = $insert . $select . $from . $where;
604 CRM_Core_DAO::executeQuery($query);
605 }
606 }
607 }
608 }
609
610 /**
611 * Add soft credit to for recurring payment.
612 *
613 * copy soft credit record of first recurring contribution.
614 * and add new soft credit against $targetContributionId
615 *
616 * @param int $recurId
617 * @param int $targetContributionId
618 */
619 public static function addrecurSoftCredit($recurId, $targetContributionId) {
620 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
621 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
622
623 // Check if first recurring contribution has any associated soft credit.
624 if ($soft_contribution->find(TRUE)) {
625 $soft_contribution->contribution_id = $targetContributionId;
626 unset($soft_contribution->id);
627 $soft_contribution->save();
628 }
629 }
630
631 /**
632 * Add line items for recurring contribution.
633 *
634 * @param int $recurId
635 * @param $contribution
636 *
637 * @return array
638 */
639 public static function addRecurLineItems($recurId, $contribution) {
640 $foundLineItems = FALSE;
641
642 $lineSets = self::calculateRecurLineItems($recurId, $contribution->total_amount, $contribution->financial_type_id);
643 foreach ($lineSets as $lineItems) {
644 if (!empty($lineItems)) {
645 foreach ($lineItems as $key => $value) {
646 if ($value['entity_table'] == 'civicrm_membership') {
647 try {
648 // @todo this should be done by virtue of editing the line item as this link
649 // is deprecated. This may be the case but needs testing.
650 civicrm_api3('membership_payment', 'create', array(
651 'membership_id' => $value['entity_id'],
652 'contribution_id' => $contribution->id,
653 'is_transactional' => FALSE,
654 ));
655 }
656 catch (CiviCRM_API3_Exception $e) {
657 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
658 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
659 }
660 }
661 }
662 $foundLineItems = TRUE;
663 }
664 }
665 if (!$foundLineItems) {
666 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
667 }
668 return $lineSets;
669 }
670
671 /**
672 * Update pledge associated with a recurring contribution.
673 *
674 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
675 *
676 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
677 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
678 * it should be assumed they
679 * do so with the intention that all payments will be linked
680 *
681 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
682 * If not the contribution will also need to be linked to the pledge
683 *
684 * @param int $contributionID
685 * @param int $contributionRecurID
686 * @param int $contributionStatusID
687 * @param float $contributionAmount
688 *
689 * @throws \CiviCRM_API3_Exception
690 */
691 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
692 $returnProperties = array('id', 'pledge_id');
693 $paymentDetails = $paymentIDs = array();
694
695 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
696 $paymentDetails, $returnProperties
697 )
698 ) {
699 foreach ($paymentDetails as $key => $value) {
700 $paymentIDs[] = $value['id'];
701 $pledgeId = $value['pledge_id'];
702 }
703 }
704 else {
705 //payment is not already linked - if it is linked with a pledge we need to create a link.
706 // return if it is not recurring contribution
707 if (!$contributionRecurID) {
708 return;
709 }
710
711 $relatedContributions = new CRM_Contribute_DAO_Contribution();
712 $relatedContributions->contribution_recur_id = $contributionRecurID;
713 $relatedContributions->find();
714
715 while ($relatedContributions->fetch()) {
716 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
717 $paymentDetails, $returnProperties
718 );
719 }
720
721 if (empty($paymentDetails)) {
722 // payment is not linked with a pledge and neither are any other contributions on this
723 return;
724 }
725
726 foreach ($paymentDetails as $key => $value) {
727 $pledgeId = $value['pledge_id'];
728 }
729
730 // we have a pledge now we need to get the oldest unpaid payment
731 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
732 if (empty($paymentDetails['id'])) {
733 // we can assume this pledge is now completed
734 // return now so we don't create a core error & roll back
735 return;
736 }
737 $paymentDetails['contribution_id'] = $contributionID;
738 $paymentDetails['status_id'] = $contributionStatusID;
739 $paymentDetails['actual_amount'] = $contributionAmount;
740
741 // put contribution against it
742 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
743 $paymentIDs[] = $payment['id'];
744 }
745
746 // update pledge and corresponding payment statuses
747 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
748 NULL, $contributionAmount
749 );
750 }
751
752 /**
753 * @param $form
754 */
755 public static function recurringContribution(&$form) {
756 // Recurring contribution fields
757 foreach (self::getRecurringFields() as $key => $label) {
758 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues) &&
759 !CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
760 ) {
761 $form->assign('contribution_recur_pane_open', TRUE);
762 break;
763 }
764 CRM_Core_Form_Date::buildDateRange($form, $key, 1, '_low', '_high');
765 // If data has been entered for a recurring field, tell the tpl layer to open the pane
766 if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
767 $form->assign('contribution_recur_pane_open', TRUE);
768 break;
769 }
770 }
771
772 // Add field to check if payment is made for recurring contribution
773 $recurringPaymentOptions = array(
774 1 => ts('All recurring contributions'),
775 2 => ts('Recurring contributions with at least one payment'),
776 );
777 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
778 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
779 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
780 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
781 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
782 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
783 CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
784 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
785 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
786
787 CRM_Core_BAO_Query::addCustomFormFields($form, array('ContributionRecur'));
788
789 }
790
791 /**
792 * Get fields for recurring contributions.
793 *
794 * @return array
795 */
796 public static function getRecurringFields() {
797 return array(
798 'contribution_recur_payment_made' => ts(''),
799 'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
800 'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
801 'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
802 'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
803 'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
804 'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
805 'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
806 );
807 }
808
809 /**
810 * Update recurring contribution based on incoming payment.
811 *
812 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
813 *
814 * @param int $recurringContributionID
815 * @param string $paymentStatus
816 * Payment status - this correlates to the machine name of the contribution status ID ie
817 * - Completed
818 * - Failed
819 *
820 * @throws \CiviCRM_API3_Exception
821 */
822 public static function updateOnNewPayment($recurringContributionID, $paymentStatus) {
823 if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
824 return;
825 }
826 $params = array(
827 'id' => $recurringContributionID,
828 'return' => array(
829 'contribution_status_id',
830 'next_sched_contribution_date',
831 'frequency_unit',
832 'frequency_interval',
833 'installments',
834 'failure_count',
835 ),
836 );
837
838 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
839
840 if ($paymentStatus == 'Completed'
841 && CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
842 $params['contribution_status_id'] = 'In Progress';
843 }
844 if ($paymentStatus == 'Failed') {
845 $params['failure_count'] = $existing['failure_count'];
846 }
847 $params['modified_date'] = date('Y-m-d H:i:s');
848
849 if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
850 $params['contribution_status_id'] = 'Completed';
851 }
852 else {
853 // Only update next sched date if it's empty or 'just now' because payment processors may be managing
854 // the scheduled date themselves as core did not previously provide any help.
855 if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) ==
856 strtotime(date('Y-m-d'))) {
857 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit']));
858 }
859 }
860 civicrm_api3('ContributionRecur', 'create', $params);
861 }
862
863 /**
864 * Is this recurring contribution now complete.
865 *
866 * Have all the payments expected been received now.
867 *
868 * @param int $recurringContributionID
869 * @param int $installments
870 *
871 * @return bool
872 */
873 protected static function isComplete($recurringContributionID, $installments) {
874 $paidInstallments = CRM_Core_DAO::singleValueQuery(
875 'SELECT count(*) FROM civicrm_contribution WHERE id = %1',
876 array(1 => array($recurringContributionID, 'Integer'))
877 );
878 if ($paidInstallments >= $installments) {
879 return TRUE;
880 }
881 return FALSE;
882 }
883
884 /**
885 * Calculate line items for the relevant recurring calculation.
886 *
887 * @param int $recurId
888 * @param string $total_amount
889 * @param int $financial_type_id
890 *
891 * @return array
892 */
893 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
894 $originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
895 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
896 $lineSets = array();
897 if (count($lineItems) == 1) {
898 foreach ($lineItems as $index => $lineItem) {
899 if ($financial_type_id) {
900 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
901 $lineItem['financial_type_id'] = $financial_type_id;
902 }
903 if ($lineItem['line_total'] != $total_amount) {
904 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
905 // if there is only one line item, and the UI should prevent this situation for those with more than one.
906 $lineItem['line_total'] = $total_amount;
907 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
908 }
909 $priceField = new CRM_Price_DAO_PriceField();
910 $priceField->id = $lineItem['price_field_id'];
911 $priceField->find(TRUE);
912 $lineSets[$priceField->price_set_id][] = $lineItem;
913 }
914 }
915 // CRM-19309 if more than one then just pass them through:
916 elseif (count($lineItems) > 1) {
917 foreach ($lineItems as $index => $lineItem) {
918 $lineSets[$index][] = $lineItem;
919 }
920 }
921
922 return $lineSets;
923 }
924
925 }