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