Notice fixes
[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);
07310345
JG
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 }
bd3f952f 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 }
43c8d1dd 569 return $result;
d5828a02 570 }
be2fb01f 571 return [];
6a488035
TO
572 }
573
00be9182 574 public static function setSubscriptionContext() {
6a488035
TO
575 // handle context redirection for subscription url
576 $session = CRM_Core_Session::singleton();
577 if ($session->get('userID')) {
c490a46a
CW
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');
edc80cda 582 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
6a488035
TO
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 }
96025800 618
0223e233
WA
619 /**
620 * CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
ea3ddccf 621 *
0223e233
WA
622 * @param array $fields
623 * The input form values.
624 * @param array $files
625 * The uploaded files if any.
ea3ddccf 626 * @param CRM_Core_Form $self
627 * @param array $errors
0223e233 628 */
577d1236
WA
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 }
0223e233 639
e577770c
EM
640 /**
641 * Copy custom data of the initial contribution into its recurring contributions.
642 *
b2250d14 643 * @deprecated
644 *
e577770c
EM
645 * @param int $recurId
646 * @param int $targetContributionId
647 */
1330f57a 648 public static function copyCustomValues($recurId, $targetContributionId) {
eb1e4326 649 CRM_Core_Error::deprecatedFunctionWarning('no alternative');
e577770c
EM
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
be2fb01f 665 $extends = ['Contribution'];
e577770c
EM
666 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
667 if ($groupTree) {
668 foreach ($groupTree as $groupID => $group) {
be2fb01f 669 $table[$groupTree[$groupID]['table_name']] = ['entity_id'];
e577770c
EM
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) {
d4721930 676 $insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
e577770c
EM
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;
33621c4f 682 CRM_Core_DAO::executeQuery($query);
e577770c
EM
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
81716ddb 713 * @param \CRM_Contribute_BAO_Contribution $contribution
e577770c
EM
714 *
715 * @return array
d486b01e
PN
716 * @throws \CRM_Core_Exception
717 * @throws \CiviCRM_API3_Exception
e577770c
EM
718 */
719 public static function addRecurLineItems($recurId, $contribution) {
43c8d1dd 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.
be2fb01f 730 civicrm_api3('membership_payment', 'create', [
43c8d1dd 731 'membership_id' => $value['entity_id'],
732 'contribution_id' => $contribution->id,
0e0da23f 733 'is_transactional' => FALSE,
be2fb01f 734 ]);
43c8d1dd 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 }
e577770c
EM
740 }
741 }
43c8d1dd 742 $foundLineItems = TRUE;
e577770c
EM
743 }
744 }
43c8d1dd 745 if (!$foundLineItems) {
e577770c
EM
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 *
294cc627 764 * @param int $contributionID
765 * @param int $contributionRecurID
766 * @param int $contributionStatusID
767 * @param float $contributionAmount
768 *
769 * @throws \CiviCRM_API3_Exception
e577770c 770 */
294cc627 771 public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
be2fb01f
CW
772 $returnProperties = ['id', 'pledge_id'];
773 $paymentDetails = $paymentIDs = [];
e577770c 774
294cc627 775 if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
e577770c
EM
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
294cc627 787 if (!$contributionRecurID) {
e577770c
EM
788 return;
789 }
790
791 $relatedContributions = new CRM_Contribute_DAO_Contribution();
294cc627 792 $relatedContributions->contribution_recur_id = $contributionRecurID;
e577770c
EM
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 }
294cc627 817 $paymentDetails['contribution_id'] = $contributionID;
818 $paymentDetails['status_id'] = $contributionStatusID;
819 $paymentDetails['actual_amount'] = $contributionAmount;
e577770c
EM
820
821 // put contribution against it
294cc627 822 $payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
823 $paymentIDs[] = $payment['id'];
e577770c
EM
824 }
825
826 // update pledge and corresponding payment statuses
294cc627 827 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
828 NULL, $contributionAmount
e577770c
EM
829 );
830 }
831
24782d26 832 /**
a7494d96
EM
833 * Recurring contribution fields.
834 *
835 * @param CRM_Contribute_Form_Search $form
836 *
837 * @throws \CRM_Core_Exception
24782d26 838 */
a7494d96
EM
839 public static function recurringContribution($form): void {
840 // This assignment may be overwritten.
841 $form->assign('contribution_recur_pane_open', FALSE);
1157f03f 842 foreach (self::getRecurringFields() as $key) {
a7494d96 843 if ($key === 'contribution_recur_payment_made' && !empty($form->_formValues) &&
24782d26 844 !CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
845 ) {
846 $form->assign('contribution_recur_pane_open', TRUE);
847 break;
848 }
24782d26 849 // If data has been entered for a recurring field, tell the tpl layer to open the pane
55feaf27 850 if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
24782d26 851 $form->assign('contribution_recur_pane_open', TRUE);
852 break;
853 }
854 }
855
64127e03 856 // If values have been supplied for recurring contribution fields, open the recurring contributions pane.
be2fb01f 857 foreach (['contribution_status_id', 'payment_processor_id', 'processor_id', 'trxn_id'] as $fieldName) {
64127e03
MWMC
858 if (!empty($form->_formValues['contribution_recur_' . $fieldName])) {
859 $form->assign('contribution_recur_pane_open', TRUE);
860 break;
861 }
862 }
863
24782d26 864 // Add field to check if payment is made for recurring contribution
be2fb01f 865 $recurringPaymentOptions = [
c6021c27
ML
866 1 => ts('All recurring contributions'),
867 2 => ts('Recurring contributions with at least one payment'),
be2fb01f
CW
868 ];
869 $form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, ['allowClear' => TRUE]);
5af1389d
VH
870
871 // Add field for contribution status
872 $form->addSelect('contribution_recur_contribution_status_id',
c0aaecf9 873 ['entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'search')]
5af1389d
VH
874 );
875
24782d26 876 $form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
877 $form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
86a0d21e 878
46e67587 879 $paymentProcessorOpts = CRM_Contribute_BAO_ContributionRecur::buildOptions('payment_processor_id', 'get');
5951bdaa
MWMC
880 $form->add('select', 'contribution_recur_payment_processor_id', ts('Payment Processor ID'), $paymentProcessorOpts, FALSE, ['class' => 'crm-select2', 'multiple' => 'multiple']);
881
be2fb01f 882 CRM_Core_BAO_Query::addCustomFormFields($form, ['ContributionRecur']);
86a0d21e 883
24782d26 884 }
885
1157f03f
SL
886 /**
887 * Get the metadata for fields to be included on the search form.
888 *
889 * @throws \CiviCRM_API3_Exception
890 */
891 public static function getContributionRecurSearchFieldMetadata() {
892 $fields = [
893 'contribution_recur_start_date',
894 'contribution_recur_next_sched_contribution_date',
895 'contribution_recur_cancel_date',
896 'contribution_recur_end_date',
897 'contribution_recur_create_date',
898 'contribution_recur_modified_date',
899 'contribution_recur_failure_retry_date',
900 ];
901 $metadata = civicrm_api3('ContributionRecur', 'getfields', [])['values'];
902 return array_intersect_key($metadata, array_flip($fields));
903 }
904
24782d26 905 /**
906 * Get fields for recurring contributions.
907 *
908 * @return array
909 */
910 public static function getRecurringFields() {
be2fb01f 911 return [
1157f03f
SL
912 'contribution_recur_payment_made',
913 'contribution_recur_start_date',
914 'contribution_recur_next_sched_contribution_date',
915 'contribution_recur_cancel_date',
916 'contribution_recur_end_date',
917 'contribution_recur_create_date',
918 'contribution_recur_modified_date',
919 'contribution_recur_failure_retry_date',
be2fb01f 920 ];
24782d26 921 }
922
91259407 923 /**
924 * Update recurring contribution based on incoming payment.
925 *
926 * Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
927 *
928 * @param int $recurringContributionID
929 * @param string $paymentStatus
930 * Payment status - this correlates to the machine name of the contribution status ID ie
931 * - Completed
932 * - Failed
1330f57a 933 * @param string $effectiveDate
91259407 934 *
935 * @throws \CiviCRM_API3_Exception
936 */
070c2e00 937 public static function updateOnNewPayment($recurringContributionID, $paymentStatus, string $effectiveDate = 'now') {
46f459f2 938
be2fb01f 939 if (!in_array($paymentStatus, ['Completed', 'Failed'])) {
91259407 940 return;
941 }
be2fb01f 942 $params = [
91259407 943 'id' => $recurringContributionID,
be2fb01f 944 'return' => [
91259407 945 'contribution_status_id',
946 'next_sched_contribution_date',
947 'frequency_unit',
948 'frequency_interval',
949 'installments',
950 'failure_count',
be2fb01f
CW
951 ],
952 ];
91259407 953
954 $existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
955
956 if ($paymentStatus == 'Completed'
957 && CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
958 $params['contribution_status_id'] = 'In Progress';
959 }
960 if ($paymentStatus == 'Failed') {
961 $params['failure_count'] = $existing['failure_count'];
962 }
963 $params['modified_date'] = date('Y-m-d H:i:s');
964
965 if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
966 $params['contribution_status_id'] = 'Completed';
605665c7 967 $params['next_sched_contribution_date'] = 'null';
91259407 968 }
969 else {
605665c7 970 // Only update next sched date if it's empty or up to 48 hours away because payment processors may be managing
971 // the scheduled date themselves as core did not previously provide any help. This check can possibly be removed
972 // as it's unclear if it actually is helpful...
973 // We should allow payment processors to pass this value into repeattransaction in future.
974 // Note 48 hours is a bit aribtrary but means that we can hopefully ignore the time being potentially
975 // rounded down to midnight.
976 $upperDateToConsiderProcessed = strtotime('+ 48 hours', ($effectiveDate ? strtotime($effectiveDate) : time()));
977 if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) <=
978 $upperDateToConsiderProcessed) {
050e11d5 979 $params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
91259407 980 }
981 }
982 civicrm_api3('ContributionRecur', 'create', $params);
983 }
984
985 /**
986 * Is this recurring contribution now complete.
987 *
988 * Have all the payments expected been received now.
989 *
990 * @param int $recurringContributionID
991 * @param int $installments
992 *
993 * @return bool
994 */
995 protected static function isComplete($recurringContributionID, $installments) {
996 $paidInstallments = CRM_Core_DAO::singleValueQuery(
28cfbff7 997 'SELECT count(*) FROM civicrm_contribution
050e11d5 998 WHERE contribution_recur_id = %1
999 AND contribution_status_id = ' . CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
be2fb01f 1000 [1 => [$recurringContributionID, 'Integer']]
91259407 1001 );
1002 if ($paidInstallments >= $installments) {
1003 return TRUE;
1004 }
1005 return FALSE;
1006 }
1007
43c8d1dd 1008 /**
1009 * Calculate line items for the relevant recurring calculation.
1010 *
1011 * @param int $recurId
1012 * @param string $total_amount
1013 * @param int $financial_type_id
1014 *
1015 * @return array
d486b01e 1016 * @throws \CiviCRM_API3_Exception
43c8d1dd 1017 */
1018 public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
be2fb01f 1019 $originalContribution = civicrm_api3('Contribution', 'getsingle', [
1330f57a
SL
1020 'contribution_recur_id' => $recurId,
1021 'contribution_test' => '',
1022 'options' => ['limit' => 1],
1023 'return' => ['id', 'financial_type_id'],
be2fb01f 1024 ]);
2b0de476 1025 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContribution['id']);
d486b01e 1026 return self::reformatLineItemsForRepeatContribution($total_amount, $financial_type_id, $lineItems, $originalContribution);
43c8d1dd 1027 }
1028
c2047803 1029 /**
c50eadbe 1030 * Returns array with statuses that are considered to make a recurring contribution inactive.
c2047803
CR
1031 *
1032 * @return array
1033 */
1034 public static function getInactiveStatuses() {
c50eadbe 1035 return ['Cancelled', 'Failed', 'Completed'];
c2047803
CR
1036 }
1037
46e67587 1038 /**
39868387 1039 * @inheritDoc
46e67587 1040 */
be2fb01f 1041 public static function buildOptions($fieldName, $context = NULL, $props = []) {
39868387 1042 $params = [];
46e67587
MWMC
1043 switch ($fieldName) {
1044 case 'payment_processor_id':
1045 if (isset(\Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'])) {
1046 return \Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'];
1047 }
1048 $baoName = 'CRM_Contribute_BAO_ContributionRecur';
39868387
CW
1049 $params['condition']['test'] = "is_test = 0";
1050 $liveProcessors = CRM_Core_PseudoConstant::get($baoName, $fieldName, $params, $context);
1051 $params['condition']['test'] = "is_test != 0";
1052 $testProcessors = CRM_Core_PseudoConstant::get($baoName, $fieldName, $params, $context);
46e67587
MWMC
1053 foreach ($testProcessors as $key => $value) {
1054 if ($context === 'validate') {
1055 // @fixme: Ideally the names would be different in the civicrm_payment_processor table but they are not.
1056 // So we append '_test' to the test one so that we can select the correct processor by name using the ContributionRecur.create API.
1057 $testProcessors[$key] = $value . '_test';
1058 }
1059 else {
1060 $testProcessors[$key] = CRM_Core_TestEntity::appendTestText($value);
1061 }
1062 }
1063 $allProcessors = $liveProcessors + $testProcessors;
1064 ksort($allProcessors);
1065 \Civi::$statics[__CLASS__]['buildoptions_payment_processor_id'] = $allProcessors;
1066 return $allProcessors;
1067 }
39868387 1068 return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
46e67587
MWMC
1069 }
1070
8159df5f
EM
1071 /**
1072 * Get the from address to use for the recurring contribution.
1073 *
1074 * This uses the contribution page id, if there is one, or the default domain one.
1075 *
1076 * @param int $id
1077 * Recurring contribution ID.
1078 *
1079 * @internal
1080 *
1081 * @return string
1082 * @throws \API_Exception
1083 * @throws \CRM_Core_Exception
1084 */
1085 public static function getRecurFromAddress(int $id): string {
1086 $details = Contribution::get(FALSE)
1087 ->addWhere('contribution_recur_id', '=', $id)
1088 ->addWhere('contribution_page_id', 'IS NOT NULL')
1089 ->addSelect('contribution_page_id.receipt_from_name', 'contribution_page_id.receipt_from_email')
1090 ->addOrderBy('receive_date', 'DESC')
1091 ->execute()->first();
1092 if (empty($details['contribution_page_id.receipt_from_email'])) {
1093 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
1094 return "$domainValues[0] <$domainValues[1]>";
1095 }
1096 return '"' . $details['contribution_page_id.receipt_from_name'] . '" <' . $details['contribution_page_id.receipt_from_email'] . '>';
1097 }
1098
6a488035 1099}