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