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