Remove deprecated function
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
2a750a39 12use Civi\Api4\Contribution;
13use Civi\Api4\ContributionRecur;
14
6a488035
TO
15/**
16 *
17 * @package CRM
ca5cec67 18 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
19 */
20class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
21
22 /**
fe482240 23 * Create recurring contribution.
6a488035 24 *
014c4014
TO
25 * @param array $params
26 * (reference ) an assoc array of name/value pairs.
6a488035 27 *
a6c01b45
CW
28 * @return object
29 * activity contact object
6a488035 30 */
00be9182 31 public static function create(&$params) {
6a488035
TO
32 return self::add($params);
33 }
34
35 /**
fe482240 36 * Takes an associative array and creates a contribution object.
6a488035
TO
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 *
014c4014
TO
42 * @param array $params
43 * (reference ) an assoc array of name/value pairs.
fd31fa4c 44 *
81716ddb 45 * @return \CRM_Contribute_BAO_ContributionRecur|\CRM_Core_Error
6a488035
TO
46 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
47 */
00be9182 48 public static function add(&$params) {
a7488080 49 if (!empty($params['id'])) {
6a488035
TO
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
be2fb01f 58 $duplicates = [];
6a488035
TO
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',
be2fb01f 64 [$d],
6a488035
TO
65 "Found matching recurring contribution(s): $d"
66 );
67 return $error;
68 }
69
70 $recurring = new CRM_Contribute_BAO_ContributionRecur();
71 $recurring->copyValues($params);
9c1bc317 72 $recurring->id = $params['id'] ?? NULL;
6a488035
TO
73
74 // set currency for CRM-1496
8f7b45b0 75 if (empty($params['id']) && !isset($recurring->currency)) {
6a488035
TO
76 $config = CRM_Core_Config::singleton();
77 $recurring->currency = $config->defaultCurrency;
78 }
e06814a5 79 $recurring->save();
6a488035 80
a7488080 81 if (!empty($params['id'])) {
6a488035
TO
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
95974e8e
DG
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
e06814a5 94 return $recurring;
6a488035
TO
95 }
96
97 /**
fe482240 98 * Check if there is a recurring contribution with the same trxn_id or invoice_id.
6a488035 99 *
014c4014
TO
100 * @param array $params
101 * (reference ) an assoc array of name/value pairs.
102 * @param array $duplicates
c0f62075 103 * (reference ) store ids of duplicate contributions.
6a488035 104 *
e7483cbe 105 * @return bool
a6c01b45 106 * true if duplicate, false otherwise
6a488035 107 */
00be9182 108 public static function checkDuplicate($params, &$duplicates) {
9c1bc317
CW
109 $id = $params['id'] ?? NULL;
110 $trxn_id = $params['trxn_id'] ?? NULL;
111 $invoice_id = $params['invoice_id'] ?? NULL;
6a488035 112
be2fb01f
CW
113 $clause = [];
114 $params = [];
6a488035
TO
115
116 if ($trxn_id) {
117 $clause[] = "trxn_id = %1";
be2fb01f 118 $params[1] = [$trxn_id, 'String'];
6a488035
TO
119 }
120
121 if ($invoice_id) {
122 $clause[] = "invoice_id = %2";
be2fb01f 123 $params[2] = [$invoice_id, 'String'];
6a488035
TO
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";
be2fb01f 133 $params[3] = [$id, 'Integer'];
6a488035
TO
134 }
135
353ffa53
TO
136 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
137 $dao = CRM_Core_DAO::executeQuery($query, $params);
6a488035
TO
138 $result = FALSE;
139 while ($dao->fetch()) {
140 $duplicates[] = $dao->id;
141 $result = TRUE;
142 }
143 return $result;
144 }
145
186c9c17 146 /**
c0f62075 147 * Get the payment processor (array) for a recurring processor.
148 *
100fef9d 149 * @param int $id
186c9c17
EM
150 *
151 * @return array|null
152 */
87011153 153 public static function getPaymentProcessor($id) {
1a18d24f 154 $paymentProcessorID = self::getPaymentProcessorID($id);
87011153 155 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID);
156 }
6a488035 157
87011153 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) {
4790df8a 169 CRM_Core_Error::deprecatedFunctionWarning('Use Civi\Payment\System');
87011153 170 $processor = self::getPaymentProcessor($id);
171 return is_array($processor) ? $processor['object'] : NULL;
6a488035
TO
172 }
173
1a18d24f 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,
1330f57a 186 'return' => ['payment_processor_id'],
1a18d24f 187 ]);
2975f0aa 188 return (int) ($recur['payment_processor_id'] ?? 0);
1a18d24f 189 }
190
6a488035 191 /**
c0f62075 192 * Get the number of installment done/completed for each recurring contribution.
6a488035 193 *
014c4014
TO
194 * @param array $ids
195 * (reference ) an array of recurring contribution ids.
6a488035 196 *
a6c01b45
CW
197 * @return array
198 * an array of recurring ids count
6a488035 199 */
00be9182 200 public static function getCount(&$ids) {
6a488035 201 $recurID = implode(',', $ids);
be2fb01f 202 $totalCount = [];
6a488035 203
d5828a02 204 $query = "
6a488035
TO
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
33621c4f 210 $res = CRM_Core_DAO::executeQuery($query);
6a488035
TO
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 *
100fef9d 221 * @param int $recurId
da6b46f4 222 *
ca26cb52 223 * @return bool
6a488035 224 */
00be9182 225 public static function deleteRecurContribution($recurId) {
6a488035
TO
226 $result = FALSE;
227 if (!$recurId) {
228 return $result;
229 }
230
353ffa53 231 $recur = new CRM_Contribute_DAO_ContributionRecur();
6a488035 232 $recur->id = $recurId;
353ffa53 233 $result = $recur->delete();
6a488035
TO
234
235 return $result;
236 }
237
238 /**
239 * Cancel Recurring contribution.
240 *
9cfc631e 241 * @param array $params
242 * Recur contribution params
6a488035 243 *
ca26cb52 244 * @return bool
6a488035 245 */
3d3449ce 246 public static function cancelRecurContribution($params) {
c3d06508 247 if (is_numeric($params)) {
9cfc631e 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'];
6a488035
TO
252 if (!$recurId) {
253 return FALSE;
254 }
3d3449ce 255 $activityParams = [
256 'subject' => !empty($params['membership_id']) ? ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'),
6b409353 257 'details' => $params['processor_message'] ?? NULL,
3d3449ce 258 ];
6a488035 259
c50eadbe 260 $cancelledId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', 'Cancelled');
353ffa53
TO
261 $recur = new CRM_Contribute_DAO_ContributionRecur();
262 $recur->id = $recurId;
c50eadbe 263 $recur->whereAdd("contribution_status_id != $cancelledId");
6a488035
TO
264
265 if ($recur->find(TRUE)) {
266 $transaction = new CRM_Core_Transaction();
c50eadbe 267 $recur->contribution_status_id = $cancelledId;
9c1bc317 268 $recur->cancel_reason = $params['cancel_reason'] ?? NULL;
6a488035
TO
269 $recur->cancel_date = date('YmdHis');
270 $recur->save();
271
e143136a 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
6a488035 273 $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
bbf58b03 274 if ($dao && $dao->recur_id) {
9c1bc317 275 $details = $activityParams['details'] ?? NULL;
6a488035
TO
276 if ($dao->auto_renew && $dao->membership_id) {
277 // its auto-renewal membership mode
278 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
353ffa53 279 $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
9c1bc317 280 $membershipType = $membershipTypes[$membershipType] ?? NULL;
6a488035 281 $details .= '
be2fb01f 282<br/>' . ts('Automatic renewal of %1 membership cancelled.', [1 => $membershipType]);
6a488035
TO
283 }
284 else {
3d3449ce 285 $details .= '<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', [
1330f57a
SL
286 1 => $dao->amount,
287 2 => $dao->frequency_interval,
288 3 => $dao->frequency_unit,
289 ]);
6a488035 290 }
be2fb01f 291 $activityParams = [
6a488035 292 'source_contact_id' => $dao->contact_id,
fa413ad2 293 'source_record_id' => $dao->recur_id,
3d3449ce 294 'activity_type_id' => 'Cancel Recurring Contribution',
6a488035
TO
295 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
296 'details' => $details,
3d3449ce 297 'status_id' => 'Completed',
be2fb01f 298 ];
3d3449ce 299
300 $cid = CRM_Core_Session::singleton()->get('userID');
6a488035
TO
301 if ($cid) {
302 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
303 $activityParams['source_contact_id'] = $cid;
304 }
3d3449ce 305 civicrm_api3('Activity', 'create', $activityParams);
6a488035
TO
306 }
307
9d9d13dd 308 $transaction->commit();
309 return TRUE;
6a488035
TO
310 }
311 else {
312 // if already cancelled, return true
313 $recur->whereAdd();
c50eadbe 314 $recur->whereAdd("contribution_status_id = $cancelledId");
6a488035
TO
315 if ($recur->find(TRUE)) {
316 return TRUE;
317 }
318 }
319
320 return FALSE;
321 }
322
186c9c17 323 /**
100fef9d 324 * @param int $entityID
186c9c17
EM
325 * @param string $entity
326 *
327 * @return null|Object
328 */
00be9182 329 public static function getSubscriptionDetails($entityID, $entity = 'recur') {
d0f696ac
MW
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.
6a488035 332 $sql = "
d5828a02
DL
333SELECT rec.id as recur_id,
334 rec.processor_id as subscription_id,
d0f696ac 335 rec.processor_id,
6a488035
TO
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,
7083dc2a 343 rec.campaign_id,
467fe956 344 rec.financial_type_id,
0c6c47a5 345 rec.next_sched_contribution_date,
346 rec.failure_retry_date,
347 rec.cycle_day,
467fe956 348 con.id as contribution_id,
6a488035 349 con.contribution_page_id,
f0a7bcb5 350 rec.contact_id,
6a488035
TO
351 mp.membership_id";
352
353 if ($entity == 'recur') {
354 $sql .= "
d5828a02 355 FROM civicrm_contribution_recur rec
f0a7bcb5 356LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
6a488035 357LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
0ee5581e 358 WHERE rec.id = %1";
6a488035
TO
359 }
360 elseif ($entity == 'contribution') {
361 $sql .= "
362 FROM civicrm_contribution con
d5828a02 363INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
6a488035
TO
364LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
365 WHERE con.id = %1";
366 }
367 elseif ($entity == 'membership') {
368 $sql .= "
d5828a02
DL
369 FROM civicrm_membership_payment mp
370INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
6a488035
TO
371INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
372INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
373 WHERE mp.membership_id = %1";
374 }
375
be2fb01f 376 $dao = CRM_Core_DAO::executeQuery($sql, [1 => [$entityID, 'Integer']]);
6a488035
TO
377 if ($dao->fetch()) {
378 return $dao;
379 }
d5828a02 380 else {
467fe956 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
7d238e35
JJ
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
467fe956 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
43c8d1dd 495 * @param array $overrides
496 * Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
467fe956 497 *
498 * @return array
562e4fb8 499 *
562e4fb8 500 * @throws \API_Exception
467fe956 501 */
2a750a39 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
f306dbeb 520 // First look for new-style template contribution with is_template=1
2a750a39 521 $templateContributions = Contribution::get(FALSE)
e6e23728 522 ->addWhere('contribution_recur_id', '=', $id)
f306dbeb 523 ->addWhere('is_template', '=', 1)
2a750a39 524 ->addWhere('is_test', '=', $recurringContribution['is_test'])
e6e23728
AS
525 ->addOrderBy('id', 'DESC')
526 ->setLimit(1)
527 ->execute();
f306dbeb
AS
528 if (!$templateContributions->count()) {
529 // Fall back to old style template contributions
2a750a39 530 $templateContributions = Contribution::get(FALSE)
f306dbeb 531 ->addWhere('contribution_recur_id', '=', $id)
2a750a39 532 ->addWhere('is_test', '=', $recurringContribution['is_test'])
f306dbeb
AS
533 ->addOrderBy('id', 'DESC')
534 ->setLimit(1)
535 ->execute();
536 }
e6e23728
AS
537 if ($templateContributions->count()) {
538 $templateContribution = $templateContributions->first();
4df23f2a
EM
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();
fa839a68 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.
4df23f2a
EM
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.
fa839a68 553 if (count($lineItems) > 1 && isset($overrides['financial_type_id'])) {
554 unset($overrides['financial_type_id']);
555 }
556 $result = array_merge($templateContribution, $overrides);
4df23f2a 557 $result['line_item'][$order->getPriceSetID()] = $lineItems;
bd3f952f 558 // If the template contribution was made on-behalf then add the
559 // relevant values to ensure the activity reflects that.
560 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($result['id']);
561 if (!empty($relatedContact['individual_id'])) {
562 $result['on_behalf'] = TRUE;
563 $result['source_contact_id'] = $relatedContact['individual_id'];
564 }
43c8d1dd 565 return $result;
d5828a02 566 }
be2fb01f 567 return [];
6a488035
TO
568 }
569
00be9182 570 public static function setSubscriptionContext() {
6a488035
TO
571 // handle context redirection for subscription url
572 $session = CRM_Core_Session::singleton();
573 if ($session->get('userID')) {
c490a46a
CW
574 $url = FALSE;
575 $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
576 $mid = CRM_Utils_Request::retrieve('mid', 'Integer');
577 $qfkey = CRM_Utils_Request::retrieve('key', 'String');
edc80cda 578 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
6a488035
TO
579 if ($cid) {
580 switch ($context) {
581 case 'contribution':
582 $url = CRM_Utils_System::url('civicrm/contact/view',
583 "reset=1&selectedChild=contribute&cid={$cid}"
584 );
585 break;
586
587 case 'membership':
588 $url = CRM_Utils_System::url('civicrm/contact/view',
589 "reset=1&selectedChild=member&cid={$cid}"
590 );
591 break;
592
593 case 'dashboard':
594 $url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
595 break;
596 }
597 }
598 if ($mid) {
599 switch ($context) {
600 case 'dashboard':
601 $url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
602 break;
603
604 case 'search':
605 $url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
606 break;
607 }
608 }
609 if ($url) {
610 $session->pushUserContext($url);
611 }
612 }
613 }
96025800 614
0223e233
WA
615 /**
616 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
ea3ddccf 617 *
0223e233
WA
618 * @param array $fields
619 * The input form values.
620 * @param array $files
621 * The uploaded files if any.
ea3ddccf 622 * @param CRM_Core_Form $self
623 * @param array $errors
0223e233 624 */
577d1236
WA
625 public static function validateRecurContribution($fields, $files, $self, &$errors) {
626 if (!empty($fields['is_recur'])) {
627 if ($fields['frequency_interval'] <= 0) {
628 $errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
629 }
630 if ($fields['frequency_unit'] == '0') {
631 $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).');
632 }
633 }
634 }
0223e233 635
e577770c
EM
636 /**
637 * Copy custom data of the initial contribution into its recurring contributions.
638 *
b2250d14 639 * @deprecated
640 *
e577770c
EM
641 * @param int $recurId
642 * @param int $targetContributionId
643 */
1330f57a 644 public static function copyCustomValues($recurId, $targetContributionId) {
eb1e4326 645 CRM_Core_Error::deprecatedFunctionWarning('no alternative');
e577770c
EM
646 if ($recurId && $targetContributionId) {
647 // get the initial contribution id of recur id
648 $sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
649
650 // if the same contribution is being processed then return
651 if ($sourceContributionId == $targetContributionId) {
652 return;
653 }
654 // check if proper recurring contribution record is being processed
655 $targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
656 if ($targetConRecurId != $recurId) {
657 return;
658 }
659
660 // copy custom data
be2fb01f 661 $extends = ['Contribution'];
e577770c
EM
662 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
663 if ($groupTree) {
664 foreach ($groupTree as $groupID => $group) {
be2fb01f 665 $table[$groupTree[$groupID]['table_name']] = ['entity_id'];
e577770c
EM
666 foreach ($group['fields'] as $fieldID => $field) {
667 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
668 }
669 }
670
671 foreach ($table as $tableName => $tableColumns) {
d4721930 672 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
e577770c
EM
673 $tableColumns[0] = $targetContributionId;
674 $select = 'SELECT ' . implode(', ', $tableColumns);
675 $from = ' FROM ' . $tableName;
676 $where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
677 $query = $insert . $select . $from . $where;
33621c4f 678 CRM_Core_DAO::executeQuery($query);
e577770c
EM
679 }
680 }
681 }
682 }
683
684 /**
685 * Add soft credit to for recurring payment.
686 *
687 * copy soft credit record of first recurring contribution.
688 * and add new soft credit against $targetContributionId
689 *
690 * @param int $recurId
691 * @param int $targetContributionId
692 */
693 public static function addrecurSoftCredit($recurId, $targetContributionId) {
694 $soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
695 $soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
696
697 // Check if first recurring contribution has any associated soft credit.
698 if ($soft_contribution->find(TRUE)) {
699 $soft_contribution->contribution_id = $targetContributionId;
700 unset($soft_contribution->id);
701 $soft_contribution->save();
702 }
703 }
704
705 /**
706 * Add line items for recurring contribution.
707 *
708 * @param int $recurId
81716ddb 709 * @param \CRM_Contribute_BAO_Contribution $contribution
e577770c
EM
710 *
711 * @return array
d486b01e
PN
712 * @throws \CRM_Core_Exception
713 * @throws \CiviCRM_API3_Exception
e577770c
EM
714 */
715 public static function addRecurLineItems($recurId, $contribution) {
43c8d1dd 716 $foundLineItems = FALSE;
717
718 $lineSets = self::calculateRecurLineItems($recurId, $contribution->total_amount, $contribution->financial_type_id);
719 foreach ($lineSets as $lineItems) {
720 if (!empty($lineItems)) {
721 foreach ($lineItems as $key => $value) {
722 if ($value['entity_table'] == 'civicrm_membership') {
723 try {
724 // @todo this should be done by virtue of editing the line item as this link
725 // is deprecated. This may be the case but needs testing.
be2fb01f 726 civicrm_api3('membership_payment', 'create', [
43c8d1dd 727 'membership_id' => $value['entity_id'],
728 'contribution_id' => $contribution->id,
0e0da23f 729 'is_transactional' => FALSE,
be2fb01f 730 ]);
43c8d1dd 731 }
732 catch (CiviCRM_API3_Exception $e) {
733 // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
734 // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
735 }
e577770c
EM
736 }
737 }
43c8d1dd 738 $foundLineItems = TRUE;
e577770c
EM
739 }
740 }
43c8d1dd 741 if (!$foundLineItems) {
e577770c
EM
742 CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
743 }
744 return $lineSets;
745 }
746
747 /**
748 * Update pledge associated with a recurring contribution.
749 *
750 * If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
751 *
752 * If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
753 * should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
754 * it should be assumed they
755 * do so with the intention that all payments will be linked
756 *
757 * The pledge payment record should already exist & will need to be updated with the new contribution ID.
758 * If not the contribution will also need to be linked to the pledge
759 *
294cc627 760 * @param int $contributionID
761 * @param int $contributionRecurID
762 * @param int $contributionStatusID
763 * @param float $contributionAmount
764 *
765 * @throws \CiviCRM_API3_Exception
e577770c 766 */
294cc627 767 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
be2fb01f
CW
768 $returnProperties = ['id', 'pledge_id'];
769 $paymentDetails = $paymentIDs = [];
e577770c 770
294cc627 771 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
e577770c
EM
772 $paymentDetails, $returnProperties
773 )
774 ) {
775 foreach ($paymentDetails as $key => $value) {
776 $paymentIDs[] = $value['id'];
777 $pledgeId = $value['pledge_id'];
778 }
779 }
780 else {
781 //payment is not already linked - if it is linked with a pledge we need to create a link.
782 // return if it is not recurring contribution
294cc627 783 if (!$contributionRecurID) {
e577770c
EM
784 return;
785 }
786
787 $relatedContributions = new CRM_Contribute_DAO_Contribution();
294cc627 788 $relatedContributions->contribution_recur_id = $contributionRecurID;
e577770c
EM
789 $relatedContributions->find();
790
791 while ($relatedContributions->fetch()) {
792 CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
793 $paymentDetails, $returnProperties
794 );
795 }
796
797 if (empty($paymentDetails)) {
798 // payment is not linked with a pledge and neither are any other contributions on this
799 return;
800 }
801
802 foreach ($paymentDetails as $key => $value) {
803 $pledgeId = $value['pledge_id'];
804 }
805
806 // we have a pledge now we need to get the oldest unpaid payment
807 $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
808 if (empty($paymentDetails['id'])) {
809 // we can assume this pledge is now completed
810 // return now so we don't create a core error & roll back
811 return;
812 }
294cc627 813 $paymentDetails['contribution_id'] = $contributionID;
814 $paymentDetails['status_id'] = $contributionStatusID;
815 $paymentDetails['actual_amount'] = $contributionAmount;
e577770c
EM
816
817 // put contribution against it
294cc627 818 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
819 $paymentIDs[] = $payment['id'];
e577770c
EM
820 }
821
822 // update pledge and corresponding payment statuses
294cc627 823 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
824 NULL, $contributionAmount
e577770c
EM
825 );
826 }
827
24782d26 828 /**
81716ddb 829 * @param CRM_Core_Form $form
24782d26 830 */
831 public static function recurringContribution(&$form) {
832 // Recurring contribution fields
1157f03f 833 foreach (self::getRecurringFields() as $key) {
55feaf27 834 if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues) &&
24782d26 835 !CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
836 ) {
837 $form->assign('contribution_recur_pane_open', TRUE);
838 break;
839 }
24782d26 840 // If data has been entered for a recurring field, tell the tpl layer to open the pane
55feaf27 841 if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
24782d26 842 $form->assign('contribution_recur_pane_open', TRUE);
843 break;
844 }
845 }
846
64127e03 847 // If values have been supplied for recurring contribution fields, open the recurring contributions pane.
be2fb01f 848 foreach (['contribution_status_id', 'payment_processor_id', 'processor_id', 'trxn_id'] as $fieldName) {
64127e03
MWMC
849 if (!empty($form->_formValues['contribution_recur_' . $fieldName])) {
850 $form->assign('contribution_recur_pane_open', TRUE);
851 break;
852 }
853 }
854
24782d26 855 // Add field to check if payment is made for recurring contribution
be2fb01f 856 $recurringPaymentOptions = [
c6021c27
ML
857 1 => ts('All recurring contributions'),
858 2 => ts('Recurring contributions with at least one payment'),
be2fb01f
CW
859 ];
860 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, ['allowClear' => TRUE]);
5af1389d
VH
861
862 // Add field for contribution status
863 $form->addSelect('contribution_recur_contribution_status_id',
c0aaecf9 864 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'search')]
5af1389d
VH
865 );
866
24782d26 867 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
868 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
86a0d21e 869
46e67587 870 $paymentProcessorOpts = CRM_Contribute_BAO_ContributionRecur::buildOptions('payment_processor_id', 'get');
5951bdaa
MWMC
871 $form->add('select', 'contribution_recur_payment_processor_id', ts('Payment Processor ID'), $paymentProcessorOpts, FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']);
872
be2fb01f 873 CRM_Core_BAO_Query::addCustomFormFields($form, ['ContributionRecur']);
86a0d21e 874
24782d26 875 }
876
1157f03f
SL
877 /**
878 * Get the metadata for fields to be included on the search form.
879 *
880 * @throws \CiviCRM_API3_Exception
881 */
882 public static function getContributionRecurSearchFieldMetadata() {
883 $fields = [
884 'contribution_recur_start_date',
885 'contribution_recur_next_sched_contribution_date',
886 'contribution_recur_cancel_date',
887 'contribution_recur_end_date',
888 'contribution_recur_create_date',
889 'contribution_recur_modified_date',
890 'contribution_recur_failure_retry_date',
891 ];
892 $metadata = civicrm_api3('ContributionRecur', 'getfields', [])['values'];
893 return array_intersect_key($metadata, array_flip($fields));
894 }
895
24782d26 896 /**
897 * Get fields for recurring contributions.
898 *
899 * @return array
900 */
901 public static function getRecurringFields() {
be2fb01f 902 return [
1157f03f
SL
903 'contribution_recur_payment_made',
904 'contribution_recur_start_date',
905 'contribution_recur_next_sched_contribution_date',
906 'contribution_recur_cancel_date',
907 'contribution_recur_end_date',
908 'contribution_recur_create_date',
909 'contribution_recur_modified_date',
910 'contribution_recur_failure_retry_date',
be2fb01f 911 ];
24782d26 912 }
913
91259407 914 /**
915 * Update recurring contribution based on incoming payment.
916 *
917 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
918 *
919 * @param int $recurringContributionID
920 * @param string $paymentStatus
921 * Payment status - this correlates to the machine name of the contribution status ID ie
922 * - Completed
923 * - Failed
1330f57a 924 * @param string $effectiveDate
91259407 925 *
926 * @throws \CiviCRM_API3_Exception
927 */
070c2e00 928 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, string $effectiveDate = 'now') {
46f459f2 929
be2fb01f 930 if (!in_array($paymentStatus, ['Completed', 'Failed'])) {
91259407 931 return;
932 }
be2fb01f 933 $params = [
91259407 934 'id' => $recurringContributionID,
be2fb01f 935 'return' => [
91259407 936 'contribution_status_id',
937 'next_sched_contribution_date',
938 'frequency_unit',
939 'frequency_interval',
940 'installments',
941 'failure_count',
be2fb01f
CW
942 ],
943 ];
91259407 944
945 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
946
947 if ($paymentStatus == 'Completed'
948 && CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
949 $params['contribution_status_id'] = 'In Progress';
950 }
951 if ($paymentStatus == 'Failed') {
952 $params['failure_count'] = $existing['failure_count'];
953 }
954 $params['modified_date'] = date('Y-m-d H:i:s');
955
956 if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
957 $params['contribution_status_id'] = 'Completed';
605665c7 958 $params['next_sched_contribution_date'] = 'null';
91259407 959 }
960 else {
605665c7 961 // Only update next sched date if it's empty or up to 48 hours away because payment processors may be managing
962 // the scheduled date themselves as core did not previously provide any help. This check can possibly be removed
963 // as it's unclear if it actually is helpful...
964 // We should allow payment processors to pass this value into repeattransaction in future.
965 // Note 48 hours is a bit aribtrary but means that we can hopefully ignore the time being potentially
966 // rounded down to midnight.
967 $upperDateToConsiderProcessed = strtotime('+ 48 hours', ($effectiveDate ? strtotime($effectiveDate) : time()));
968 if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) <=
969 $upperDateToConsiderProcessed) {
050e11d5 970 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
91259407 971 }
972 }
973 civicrm_api3('ContributionRecur', 'create', $params);
974 }
975
976 /**
977 * Is this recurring contribution now complete.
978 *
979 * Have all the payments expected been received now.
980 *
981 * @param int $recurringContributionID
982 * @param int $installments
983 *
984 * @return bool
985 */
986 protected static function isComplete($recurringContributionID, $installments) {
987 $paidInstallments = CRM_Core_DAO::singleValueQuery(
28cfbff7 988 'SELECT count(*) FROM civicrm_contribution
050e11d5 989 WHERE contribution_recur_id = %1
990 AND contribution_status_id = ' . CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
be2fb01f 991 [1 => [$recurringContributionID, 'Integer']]
91259407 992 );
993 if ($paidInstallments >= $installments) {
994 return TRUE;
995 }
996 return FALSE;
997 }
998
43c8d1dd 999 /**
1000 * Calculate line items for the relevant recurring calculation.
1001 *
1002 * @param int $recurId
1003 * @param string $total_amount
1004 * @param int $financial_type_id
1005 *
1006 * @return array
d486b01e 1007 * @throws \CiviCRM_API3_Exception
43c8d1dd 1008 */
1009 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
be2fb01f 1010 $originalContribution = civicrm_api3('Contribution', 'getsingle', [
1330f57a
SL
1011 'contribution_recur_id' => $recurId,
1012 'contribution_test' => '',
1013 'options' => ['limit' => 1],
1014 'return' => ['id', 'financial_type_id'],
be2fb01f 1015 ]);
2b0de476 1016 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContribution['id']);
d486b01e 1017 return self::reformatLineItemsForRepeatContribution($total_amount, $financial_type_id, $lineItems, $originalContribution);
43c8d1dd 1018 }
1019
c2047803 1020 /**
c50eadbe 1021 * Returns array with statuses that are considered to make a recurring contribution inactive.
c2047803
CR
1022 *
1023 * @return array
1024 */
1025 public static function getInactiveStatuses() {
c50eadbe 1026 return ['Cancelled', 'Failed', 'Completed'];
c2047803
CR
1027 }
1028
46e67587 1029 /**
39868387 1030 * @inheritDoc
46e67587 1031 */
be2fb01f 1032 public static function buildOptions($fieldName, $context = NULL, $props = []) {
39868387 1033 $params = [];
46e67587
MWMC
1034 switch ($fieldName) {
1035 case 'payment_processor_id':
1036 if (isset(\Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'])) {
1037 return \Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'];
1038 }
1039 $baoName = 'CRM_Contribute_BAO_ContributionRecur';
39868387
CW
1040 $params['condition']['test'] = "is_test = 0";
1041 $liveProcessors = CRM_Core_PseudoConstant::get($baoName, $fieldName, $params, $context);
1042 $params['condition']['test'] = "is_test != 0";
1043 $testProcessors = CRM_Core_PseudoConstant::get($baoName, $fieldName, $params, $context);
46e67587
MWMC
1044 foreach ($testProcessors as $key => $value) {
1045 if ($context === 'validate') {
1046 // @fixme: Ideally the names would be different in the civicrm_payment_processor table but they are not.
1047 // So we append '_test' to the test one so that we can select the correct processor by name using the ContributionRecur.create API.
1048 $testProcessors[$key] = $value . '_test';
1049 }
1050 else {
1051 $testProcessors[$key] = CRM_Core_TestEntity::appendTestText($value);
1052 }
1053 }
1054 $allProcessors = $liveProcessors + $testProcessors;
1055 ksort($allProcessors);
1056 \Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'] = $allProcessors;
1057 return $allProcessors;
1058 }
39868387 1059 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
46e67587
MWMC
1060 }
1061
6a488035 1062}