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