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