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