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