dev/core#2231 fix failure to calculate next_scheduled_date
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
18
19 /**
20 * Create recurring contribution.
21 *
22 * @param array $params
23 * (reference ) an assoc array of name/value pairs.
24 *
25 * @return object
26 * activity contact object
27 */
28 public static function create(&$params) {
29 return self::add($params);
30 }
31
32 /**
33 * Takes an associative array and creates a contribution object.
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 *
39 * @param array $params
40 * (reference ) an assoc array of name/value pairs.
41 *
42 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
43 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
44 */
45 public static function add(&$params) {
46 if (!empty($params['id'])) {
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
55 $duplicates = [];
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',
61 [$d],
62 "Found matching recurring contribution(s): $d"
63 );
64 return $error;
65 }
66
67 $recurring = new CRM_Contribute_BAO_ContributionRecur();
68 $recurring->copyValues($params);
69 $recurring->id = $params['id'] ?? NULL;
70
71 // set currency for CRM-1496
72 if (empty($params['id']) && !isset($recurring->currency)) {
73 $config = CRM_Core_Config::singleton();
74 $recurring->currency = $config->defaultCurrency;
75 }
76 $recurring->save();
77
78 if (!empty($params['id'])) {
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
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
91 return $recurring;
92 }
93
94 /**
95 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
96 *
97 * @param array $params
98 * (reference ) an assoc array of name/value pairs.
99 * @param array $duplicates
100 * (reference ) store ids of duplicate contributions.
101 *
102 * @return bool
103 * true if duplicate, false otherwise
104 */
105 public static function checkDuplicate($params, &$duplicates) {
106 $id = $params['id'] ?? NULL;
107 $trxn_id = $params['trxn_id'] ?? NULL;
108 $invoice_id = $params['invoice_id'] ?? NULL;
109
110 $clause = [];
111 $params = [];
112
113 if ($trxn_id) {
114 $clause[] = "trxn_id = %1";
115 $params[1] = [$trxn_id, 'String'];
116 }
117
118 if ($invoice_id) {
119 $clause[] = "invoice_id = %2";
120 $params[2] = [$invoice_id, 'String'];
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";
130 $params[3] = [$id, 'Integer'];
131 }
132
133 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
134 $dao = CRM_Core_DAO::executeQuery($query, $params);
135 $result = FALSE;
136 while ($dao->fetch()) {
137 $duplicates[] = $dao->id;
138 $result = TRUE;
139 }
140 return $result;
141 }
142
143 /**
144 * Get the payment processor (array) for a recurring processor.
145 *
146 * @param int $id
147 *
148 * @return array|null
149 */
150 public static function getPaymentProcessor($id) {
151 $paymentProcessorID = self::getPaymentProcessorID($id);
152 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID);
153 }
154
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 CRM_Core_Error::deprecatedFunctionWarning('Use Civi\Payment\System');
167 $processor = self::getPaymentProcessor($id);
168 return is_array($processor) ? $processor['object'] : NULL;
169 }
170
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,
183 'return' => ['payment_processor_id'],
184 ]);
185 return (int) ($recur['payment_processor_id'] ?? 0);
186 }
187
188 /**
189 * Get the number of installment done/completed for each recurring contribution.
190 *
191 * @param array $ids
192 * (reference ) an array of recurring contribution ids.
193 *
194 * @return array
195 * an array of recurring ids count
196 */
197 public static function getCount(&$ids) {
198 $recurID = implode(',', $ids);
199 $totalCount = [];
200
201 $query = "
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
207 $res = CRM_Core_DAO::executeQuery($query);
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 *
218 * @param int $recurId
219 *
220 * @return bool
221 */
222 public static function deleteRecurContribution($recurId) {
223 $result = FALSE;
224 if (!$recurId) {
225 return $result;
226 }
227
228 $recur = new CRM_Contribute_DAO_ContributionRecur();
229 $recur->id = $recurId;
230 $result = $recur->delete();
231
232 return $result;
233 }
234
235 /**
236 * Cancel Recurring contribution.
237 *
238 * @param array $params
239 * Recur contribution params
240 *
241 * @return bool
242 */
243 public static function cancelRecurContribution($params) {
244 if (is_numeric($params)) {
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'];
249 if (!$recurId) {
250 return FALSE;
251 }
252 $activityParams = [
253 'subject' => !empty($params['membership_id']) ? ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'),
254 'details' => $params['processor_message'] ?? NULL,
255 ];
256
257 $cancelledId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Cancelled');
258 $recur = new CRM_Contribute_DAO_ContributionRecur();
259 $recur->id = $recurId;
260 $recur->whereAdd("contribution_status_id != $cancelledId");
261
262 if ($recur->find(TRUE)) {
263 $transaction = new CRM_Core_Transaction();
264 $recur->contribution_status_id = $cancelledId;
265 $recur->cancel_reason = $params['cancel_reason'] ?? NULL;
266 $recur->cancel_date = date('YmdHis');
267 $recur->save();
268
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
270 $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
271 if ($dao && $dao->recur_id) {
272 $details = $activityParams['details'] ?? NULL;
273 if ($dao->auto_renew && $dao->membership_id) {
274 // its auto-renewal membership mode
275 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
276 $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
277 $membershipType = $membershipTypes[$membershipType] ?? NULL;
278 $details .= '
279 <br/>' . ts('Automatic renewal of %1 membership cancelled.', [1 => $membershipType]);
280 }
281 else {
282 $details .= '<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', [
283 1 => $dao->amount,
284 2 => $dao->frequency_interval,
285 3 => $dao->frequency_unit,
286 ]);
287 }
288 $activityParams = [
289 'source_contact_id' => $dao->contact_id,
290 'source_record_id' => $dao->recur_id,
291 'activity_type_id' => 'Cancel Recurring Contribution',
292 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
293 'details' => $details,
294 'status_id' => 'Completed',
295 ];
296
297 $cid = CRM_Core_Session::singleton()->get('userID');
298 if ($cid) {
299 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
300 $activityParams['source_contact_id'] = $cid;
301 }
302 civicrm_api3('Activity', 'create', $activityParams);
303 }
304
305 $transaction->commit();
306 return TRUE;
307 }
308 else {
309 // if already cancelled, return true
310 $recur->whereAdd();
311 $recur->whereAdd("contribution_status_id = $cancelledId");
312 if ($recur->find(TRUE)) {
313 return TRUE;
314 }
315 }
316
317 return FALSE;
318 }
319
320 /**
321 * @param int $entityID
322 * @param string $entity
323 *
324 * @return null|Object
325 */
326 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
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.
329 $sql = "
330 SELECT rec.id as recur_id,
331 rec.processor_id as subscription_id,
332 rec.processor_id,
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,
340 rec.campaign_id,
341 rec.financial_type_id,
342 rec.next_sched_contribution_date,
343 rec.failure_retry_date,
344 rec.cycle_day,
345 con.id as contribution_id,
346 con.contribution_page_id,
347 rec.contact_id,
348 mp.membership_id";
349
350 if ($entity == 'recur') {
351 $sql .= "
352 FROM civicrm_contribution_recur rec
353 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
354 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
355 WHERE rec.id = %1";
356 }
357 elseif ($entity == 'contribution') {
358 $sql .= "
359 FROM civicrm_contribution con
360 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
361 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
362 WHERE con.id = %1";
363 }
364 elseif ($entity == 'membership') {
365 $sql .= "
366 FROM civicrm_membership_payment mp
367 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
368 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
369 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
370 WHERE mp.membership_id = %1";
371 }
372
373 $dao = CRM_Core_DAO::executeQuery($sql, [1 => [$entityID, 'Integer']]);
374 if ($dao->fetch()) {
375 return $dao;
376 }
377 else {
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
409 * @param array $overrides
410 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
411 *
412 * @return array
413 *
414 * @throws \CiviCRM_API3_Exception
415 * @throws \Civi\API\Exception\UnauthorizedException
416 * @throws \API_Exception
417 */
418 public static function getTemplateContribution($id, $overrides = []) {
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 ]);
424 // First look for new-style template contribution with is_template=1
425 $templateContributions = \Civi\Api4\Contribution::get(FALSE)
426 ->addWhere('contribution_recur_id', '=', $id)
427 ->addWhere('is_template', '=', 1)
428 ->addWhere('is_test', '=', $is_test)
429 ->addOrderBy('id', 'DESC')
430 ->setLimit(1)
431 ->execute();
432 if (!$templateContributions->count()) {
433 // Fall back to old style template contributions
434 $templateContributions = \Civi\Api4\Contribution::get(FALSE)
435 ->addWhere('contribution_recur_id', '=', $id)
436 ->addWhere('is_test', '=', $is_test)
437 ->addOrderBy('id', 'DESC')
438 ->setLimit(1)
439 ->execute();
440 }
441 if ($templateContributions->count()) {
442 $templateContribution = $templateContributions->first();
443 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($templateContribution['id']);
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);
452 $result['line_item'] = self::reformatLineItemsForRepeatContribution($result['total_amount'], $result['financial_type_id'], $lineItems, (array) $templateContribution);
453 return $result;
454 }
455 return [];
456 }
457
458 public static function setSubscriptionContext() {
459 // handle context redirection for subscription url
460 $session = CRM_Core_Session::singleton();
461 if ($session->get('userID')) {
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');
466 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
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 }
502
503 /**
504 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
505 *
506 * @param array $fields
507 * The input form values.
508 * @param array $files
509 * The uploaded files if any.
510 * @param CRM_Core_Form $self
511 * @param array $errors
512 */
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 }
523
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) {
532 CRM_Core_Error::deprecatedFunctionWarning('use CRM_Contribute_BAO_ContributionPage::recurringNotify');
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 *
554 * @deprecated
555 *
556 * @param int $recurId
557 * @param int $targetContributionId
558 */
559 public static function copyCustomValues($recurId, $targetContributionId) {
560 CRM_Core_Error::deprecatedFunctionWarning('no alternative');
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
576 $extends = ['Contribution'];
577 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
578 if ($groupTree) {
579 foreach ($groupTree as $groupID => $group) {
580 $table[$groupTree[$groupID]['table_name']] = ['entity_id'];
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) {
587 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
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;
593 CRM_Core_DAO::executeQuery($query);
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
624 * @param \CRM_Contribute_BAO_Contribution $contribution
625 *
626 * @return array
627 * @throws \CRM_Core_Exception
628 * @throws \CiviCRM_API3_Exception
629 */
630 public static function addRecurLineItems($recurId, $contribution) {
631 $foundLineItems = FALSE;
632
633 $lineSets = self::calculateRecurLineItems($recurId, $contribution->total_amount, $contribution->financial_type_id);
634 foreach ($lineSets as $lineItems) {
635 if (!empty($lineItems)) {
636 foreach ($lineItems as $key => $value) {
637 if ($value['entity_table'] == 'civicrm_membership') {
638 try {
639 // @todo this should be done by virtue of editing the line item as this link
640 // is deprecated. This may be the case but needs testing.
641 civicrm_api3('membership_payment', 'create', [
642 'membership_id' => $value['entity_id'],
643 'contribution_id' => $contribution->id,
644 'is_transactional' => FALSE,
645 ]);
646 }
647 catch (CiviCRM_API3_Exception $e) {
648 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
649 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
650 }
651 }
652 }
653 $foundLineItems = TRUE;
654 }
655 }
656 if (!$foundLineItems) {
657 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
658 }
659 return $lineSets;
660 }
661
662 /**
663 * Update pledge associated with a recurring contribution.
664 *
665 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
666 *
667 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
668 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
669 * it should be assumed they
670 * do so with the intention that all payments will be linked
671 *
672 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
673 * If not the contribution will also need to be linked to the pledge
674 *
675 * @param int $contributionID
676 * @param int $contributionRecurID
677 * @param int $contributionStatusID
678 * @param float $contributionAmount
679 *
680 * @throws \CiviCRM_API3_Exception
681 */
682 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
683 $returnProperties = ['id', 'pledge_id'];
684 $paymentDetails = $paymentIDs = [];
685
686 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
687 $paymentDetails, $returnProperties
688 )
689 ) {
690 foreach ($paymentDetails as $key => $value) {
691 $paymentIDs[] = $value['id'];
692 $pledgeId = $value['pledge_id'];
693 }
694 }
695 else {
696 //payment is not already linked - if it is linked with a pledge we need to create a link.
697 // return if it is not recurring contribution
698 if (!$contributionRecurID) {
699 return;
700 }
701
702 $relatedContributions = new CRM_Contribute_DAO_Contribution();
703 $relatedContributions->contribution_recur_id = $contributionRecurID;
704 $relatedContributions->find();
705
706 while ($relatedContributions->fetch()) {
707 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
708 $paymentDetails, $returnProperties
709 );
710 }
711
712 if (empty($paymentDetails)) {
713 // payment is not linked with a pledge and neither are any other contributions on this
714 return;
715 }
716
717 foreach ($paymentDetails as $key => $value) {
718 $pledgeId = $value['pledge_id'];
719 }
720
721 // we have a pledge now we need to get the oldest unpaid payment
722 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
723 if (empty($paymentDetails['id'])) {
724 // we can assume this pledge is now completed
725 // return now so we don't create a core error & roll back
726 return;
727 }
728 $paymentDetails['contribution_id'] = $contributionID;
729 $paymentDetails['status_id'] = $contributionStatusID;
730 $paymentDetails['actual_amount'] = $contributionAmount;
731
732 // put contribution against it
733 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
734 $paymentIDs[] = $payment['id'];
735 }
736
737 // update pledge and corresponding payment statuses
738 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
739 NULL, $contributionAmount
740 );
741 }
742
743 /**
744 * @param CRM_Core_Form $form
745 */
746 public static function recurringContribution(&$form) {
747 // Recurring contribution fields
748 foreach (self::getRecurringFields() as $key) {
749 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues) &&
750 !CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
751 ) {
752 $form->assign('contribution_recur_pane_open', TRUE);
753 break;
754 }
755 // If data has been entered for a recurring field, tell the tpl layer to open the pane
756 if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
757 $form->assign('contribution_recur_pane_open', TRUE);
758 break;
759 }
760 }
761
762 // If values have been supplied for recurring contribution fields, open the recurring contributions pane.
763 foreach (['contribution_status_id', 'payment_processor_id', 'processor_id', 'trxn_id'] as $fieldName) {
764 if (!empty($form->_formValues['contribution_recur_' . $fieldName])) {
765 $form->assign('contribution_recur_pane_open', TRUE);
766 break;
767 }
768 }
769
770 // Add field to check if payment is made for recurring contribution
771 $recurringPaymentOptions = [
772 1 => ts('All recurring contributions'),
773 2 => ts('Recurring contributions with at least one payment'),
774 ];
775 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, ['allowClear' => TRUE]);
776
777 // Add field for contribution status
778 $form->addSelect('contribution_recur_contribution_status_id',
779 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'search')]
780 );
781
782 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
783 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
784
785 $paymentProcessorOpts = CRM_Contribute_BAO_ContributionRecur::buildOptions('payment_processor_id', 'get');
786 $form->add('select', 'contribution_recur_payment_processor_id', ts('Payment Processor ID'), $paymentProcessorOpts, FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']);
787
788 CRM_Core_BAO_Query::addCustomFormFields($form, ['ContributionRecur']);
789
790 }
791
792 /**
793 * Get the metadata for fields to be included on the search form.
794 *
795 * @throws \CiviCRM_API3_Exception
796 */
797 public static function getContributionRecurSearchFieldMetadata() {
798 $fields = [
799 'contribution_recur_start_date',
800 'contribution_recur_next_sched_contribution_date',
801 'contribution_recur_cancel_date',
802 'contribution_recur_end_date',
803 'contribution_recur_create_date',
804 'contribution_recur_modified_date',
805 'contribution_recur_failure_retry_date',
806 ];
807 $metadata = civicrm_api3('ContributionRecur', 'getfields', [])['values'];
808 return array_intersect_key($metadata, array_flip($fields));
809 }
810
811 /**
812 * Get fields for recurring contributions.
813 *
814 * @return array
815 */
816 public static function getRecurringFields() {
817 return [
818 'contribution_recur_payment_made',
819 'contribution_recur_start_date',
820 'contribution_recur_next_sched_contribution_date',
821 'contribution_recur_cancel_date',
822 'contribution_recur_end_date',
823 'contribution_recur_create_date',
824 'contribution_recur_modified_date',
825 'contribution_recur_failure_retry_date',
826 ];
827 }
828
829 /**
830 * Update recurring contribution based on incoming payment.
831 *
832 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
833 *
834 * @param int $recurringContributionID
835 * @param string $paymentStatus
836 * Payment status - this correlates to the machine name of the contribution status ID ie
837 * - Completed
838 * - Failed
839 * @param string $effectiveDate
840 *
841 * @throws \CiviCRM_API3_Exception
842 */
843 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, string $effectiveDate = 'now') {
844
845 if (!in_array($paymentStatus, ['Completed', 'Failed'])) {
846 return;
847 }
848 $params = [
849 'id' => $recurringContributionID,
850 'return' => [
851 'contribution_status_id',
852 'next_sched_contribution_date',
853 'frequency_unit',
854 'frequency_interval',
855 'installments',
856 'failure_count',
857 ],
858 ];
859
860 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
861
862 if ($paymentStatus == 'Completed'
863 && CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
864 $params['contribution_status_id'] = 'In Progress';
865 }
866 if ($paymentStatus == 'Failed') {
867 $params['failure_count'] = $existing['failure_count'];
868 }
869 $params['modified_date'] = date('Y-m-d H:i:s');
870
871 if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
872 $params['contribution_status_id'] = 'Completed';
873 $params['next_sched_contribution_date'] = 'null';
874 }
875 else {
876 // Only update next sched date if it's empty or up to 48 hours away because payment processors may be managing
877 // the scheduled date themselves as core did not previously provide any help. This check can possibly be removed
878 // as it's unclear if it actually is helpful...
879 // We should allow payment processors to pass this value into repeattransaction in future.
880 // Note 48 hours is a bit aribtrary but means that we can hopefully ignore the time being potentially
881 // rounded down to midnight.
882 $upperDateToConsiderProcessed = strtotime('+ 48 hours', ($effectiveDate ? strtotime($effectiveDate) : time()));
883 if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) <=
884 $upperDateToConsiderProcessed) {
885 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
886 }
887 }
888 civicrm_api3('ContributionRecur', 'create', $params);
889 }
890
891 /**
892 * Is this recurring contribution now complete.
893 *
894 * Have all the payments expected been received now.
895 *
896 * @param int $recurringContributionID
897 * @param int $installments
898 *
899 * @return bool
900 */
901 protected static function isComplete($recurringContributionID, $installments) {
902 $paidInstallments = CRM_Core_DAO::singleValueQuery(
903 'SELECT count(*) FROM civicrm_contribution
904 WHERE contribution_recur_id = %1
905 AND contribution_status_id = ' . CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
906 [1 => [$recurringContributionID, 'Integer']]
907 );
908 if ($paidInstallments >= $installments) {
909 return TRUE;
910 }
911 return FALSE;
912 }
913
914 /**
915 * Calculate line items for the relevant recurring calculation.
916 *
917 * @param int $recurId
918 * @param string $total_amount
919 * @param int $financial_type_id
920 *
921 * @return array
922 * @throws \CiviCRM_API3_Exception
923 */
924 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
925 $originalContribution = civicrm_api3('Contribution', 'getsingle', [
926 'contribution_recur_id' => $recurId,
927 'contribution_test' => '',
928 'options' => ['limit' => 1],
929 'return' => ['id', 'financial_type_id'],
930 ]);
931 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContribution['id']);
932 return self::reformatLineItemsForRepeatContribution($total_amount, $financial_type_id, $lineItems, $originalContribution);
933 }
934
935 /**
936 * Returns array with statuses that are considered to make a recurring contribution inactive.
937 *
938 * @return array
939 */
940 public static function getInactiveStatuses() {
941 return ['Cancelled', 'Failed', 'Completed'];
942 }
943
944 /**
945 * @inheritDoc
946 */
947 public static function buildOptions($fieldName, $context = NULL, $props = []) {
948 $params = [];
949 switch ($fieldName) {
950 case 'payment_processor_id':
951 if (isset(\Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'])) {
952 return \Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'];
953 }
954 $baoName = 'CRM_Contribute_BAO_ContributionRecur';
955 $params['condition']['test'] = "is_test = 0";
956 $liveProcessors = CRM_Core_PseudoConstant::get($baoName, $fieldName, $params, $context);
957 $params['condition']['test'] = "is_test != 0";
958 $testProcessors = CRM_Core_PseudoConstant::get($baoName, $fieldName, $params, $context);
959 foreach ($testProcessors as $key => $value) {
960 if ($context === 'validate') {
961 // @fixme: Ideally the names would be different in the civicrm_payment_processor table but they are not.
962 // So we append '_test' to the test one so that we can select the correct processor by name using the ContributionRecur.create API.
963 $testProcessors[$key] = $value . '_test';
964 }
965 else {
966 $testProcessors[$key] = CRM_Core_TestEntity::appendTestText($value);
967 }
968 }
969 $allProcessors = $liveProcessors + $testProcessors;
970 ksort($allProcessors);
971 \Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'] = $allProcessors;
972 return $allProcessors;
973 }
974 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
975 }
976
977 /**
978 * Reformat line items for getTemplateContribution / repeat contribution.
979 *
980 * This is an extraction and may be subject to further cleanup.
981 *
982 * @param float $total_amount
983 * @param int $financial_type_id
984 * @param array $lineItems
985 * @param array $originalContribution
986 *
987 * @return array
988 */
989 protected static function reformatLineItemsForRepeatContribution($total_amount, $financial_type_id, array $lineItems, array $originalContribution): array {
990 $lineSets = [];
991 if (count($lineItems) == 1) {
992 foreach ($lineItems as $index => $lineItem) {
993 if ($lineItem['financial_type_id'] != $originalContribution['financial_type_id']) {
994 // 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.
995 $financial_type_id = $lineItem['financial_type_id'];
996 }
997 if ($financial_type_id) {
998 // CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
999 $lineItem['financial_type_id'] = $financial_type_id;
1000 }
1001 $taxAmountMatches = FALSE;
1002 if ((!empty($lineItem['tax_amount']) && ($lineItem['line_total'] + $lineItem['tax_amount']) == $total_amount)) {
1003 $taxAmountMatches = TRUE;
1004 }
1005 if ($lineItem['line_total'] != $total_amount && !$taxAmountMatches) {
1006 // We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
1007 // if there is only one line item, and the UI should prevent this situation for those with more than one.
1008 $lineItem['line_total'] = $total_amount;
1009 $lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
1010 }
1011 $priceField = new CRM_Price_DAO_PriceField();
1012 $priceField->id = $lineItem['price_field_id'];
1013 $priceField->find(TRUE);
1014 $lineSets[$priceField->price_set_id][$lineItem['price_field_id']] = $lineItem;
1015 }
1016 }
1017 // CRM-19309 if more than one then just pass them through:
1018 elseif (count($lineItems) > 1) {
1019 foreach ($lineItems as $index => $lineItem) {
1020 $lineSets[$index][$lineItem['price_field_id']] = $lineItem;
1021 }
1022 }
1023 return $lineSets;
1024 }
1025
1026 }