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