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