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