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