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