3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
33 class CRM_Pledge_BAO_PledgePayment
extends CRM_Pledge_DAO_PledgePayment
{
38 public function __construct() {
39 parent
::__construct();
43 * Get pledge payment details.
45 * @param int $pledgeId
49 * associated array of pledge payment details
51 public static function getPledgePayments($pledgeId) {
53 SELECT civicrm_pledge_payment.id id,
60 civicrm_pledge_payment.currency,
61 civicrm_option_value.name as status,
62 civicrm_option_value.label as label,
63 civicrm_contribution.id as contribution_id
64 FROM civicrm_pledge_payment
66 LEFT JOIN civicrm_contribution ON civicrm_pledge_payment.contribution_id = civicrm_contribution.id
67 LEFT JOIN civicrm_option_group ON ( civicrm_option_group.name = 'contribution_status' )
68 LEFT JOIN civicrm_option_value ON ( civicrm_pledge_payment.status_id = civicrm_option_value.value AND
69 civicrm_option_group.id = civicrm_option_value.option_group_id )
73 $params[1] = array($pledgeId, 'Integer');
74 $payment = CRM_Core_DAO
::executeQuery($query, $params);
76 $paymentDetails = array();
77 while ($payment->fetch()) {
78 $paymentDetails[$payment->id
]['scheduled_amount'] = $payment->scheduled_amount
;
79 $paymentDetails[$payment->id
]['scheduled_date'] = $payment->scheduled_date
;
80 $paymentDetails[$payment->id
]['reminder_date'] = $payment->reminder_date
;
81 $paymentDetails[$payment->id
]['reminder_count'] = $payment->reminder_count
;
82 $paymentDetails[$payment->id
]['total_amount'] = $payment->actual_amount
;
83 $paymentDetails[$payment->id
]['receive_date'] = $payment->receive_date
;
84 $paymentDetails[$payment->id
]['status'] = $payment->status
;
85 $paymentDetails[$payment->id
]['label'] = $payment->label
;
86 $paymentDetails[$payment->id
]['id'] = $payment->id
;
87 $paymentDetails[$payment->id
]['contribution_id'] = $payment->contribution_id
;
88 $paymentDetails[$payment->id
]['currency'] = $payment->currency
;
91 return $paymentDetails;
95 * @param array $params
99 public static function create($params) {
100 $transaction = new CRM_Core_Transaction();
101 $overdueStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_PledgePayment', 'status_id', 'Overdue');
102 $pendingStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_PledgePayment', 'status_id', 'Pending');
104 //calculate the scheduled date for every installment
105 $now = date('Ymd') . '000000';
106 $statues = $prevScheduledDate = array();
107 $prevScheduledDate[1] = CRM_Utils_Date
::processDate($params['scheduled_date']);
109 if (CRM_Utils_Date
::overdue($prevScheduledDate[1], $now)) {
110 $statues[1] = $overdueStatusID;
113 $statues[1] = $pendingStatusId;
116 for ($i = 1; $i < $params['installments']; $i++
) {
117 $prevScheduledDate[$i +
1] = self
::calculateNextScheduledDate($params, $i);
118 if (CRM_Utils_Date
::overdue($prevScheduledDate[$i +
1], $now)) {
119 $statues[$i +
1] = $overdueStatusID;
122 $statues[$i +
1] = $pendingStatusId;
126 if ($params['installment_amount']) {
127 $params['scheduled_amount'] = $params['installment_amount'];
130 $params['scheduled_amount'] = round(($params['amount'] / $params['installments']), 2);
133 for ($i = 1; $i <= $params['installments']; $i++
) {
134 // calculate the scheduled amount for every installment.
135 if ($i == $params['installments']) {
136 $params['scheduled_amount'] = $params['amount'] - ($i - 1) * $params['scheduled_amount'];
138 if (!isset($params['contribution_id']) && $params['installments'] > 1) {
139 $params['status_id'] = $statues[$i];
142 $params['scheduled_date'] = $prevScheduledDate[$i];
143 $payment = self
::add($params);
144 if (is_a($payment, 'CRM_Core_Error')) {
145 $transaction->rollback();
149 // we should add contribution id to only first payment record
150 if (isset($params['contribution_id'])) {
151 unset($params['contribution_id']);
152 unset($params['actual_amount']);
156 // update pledge status
157 self
::updatePledgePaymentStatus($params['pledge_id']);
159 $transaction->commit();
164 * Add pledge payment.
166 * @param array $params
167 * Associate array of field.
169 * @return CRM_Pledge_DAO_PledgePayment
172 public static function add($params) {
173 if (!empty($params['id'])) {
174 CRM_Utils_Hook
::pre('edit', 'PledgePayment', $params['id'], $params);
177 CRM_Utils_Hook
::pre('create', 'PledgePayment', NULL, $params);
180 $payment = new CRM_Pledge_DAO_PledgePayment();
181 $payment->copyValues($params);
183 // set currency for CRM-1496
184 if (!isset($payment->currency
)) {
185 $payment->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
188 $result = $payment->save();
190 if (!empty($params['id'])) {
191 CRM_Utils_Hook
::post('edit', 'PledgePayment', $payment->id
, $payment);
194 CRM_Utils_Hook
::post('create', 'PledgePayment', $payment->id
, $payment);
201 * Retrieve DB object based on input parameters.
203 * It also stores all the retrieved values in the default array.
205 * @param array $params
206 * (reference ) an assoc array of name/value pairs.
207 * @param array $defaults
208 * (reference ) an assoc array to hold the flattened values.
210 * @return CRM_Pledge_BAO_PledgePayment
212 public static function retrieve(&$params, &$defaults) {
213 $payment = new CRM_Pledge_BAO_PledgePayment();
214 $payment->copyValues($params);
215 if ($payment->find(TRUE)) {
216 CRM_Core_DAO
::storeValues($payment, $defaults);
223 * Delete pledge payment.
230 public static function del($id) {
231 $payment = new CRM_Pledge_DAO_PledgePayment();
233 if ($payment->find()) {
236 CRM_Utils_Hook
::pre('delete', 'PledgePayment', $id, $payment);
238 $result = $payment->delete();
240 CRM_Utils_Hook
::post('delete', 'PledgePayment', $id, $payment);
250 * Delete all pledge payments.
257 public static function deletePayments($id) {
258 if (!CRM_Utils_Rule
::positiveInteger($id)) {
262 $transaction = new CRM_Core_Transaction();
264 $payment = new CRM_Pledge_DAO_PledgePayment();
265 $payment->pledge_id
= $id;
267 if ($payment->find()) {
268 while ($payment->fetch()) {
269 //also delete associated contribution.
270 if ($payment->contribution_id
) {
271 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
273 self
::del($payment->id
);
277 $transaction->commit();
283 * On delete contribution record update associated pledge payment and pledge.
285 * @param int $contributionID
290 public static function resetPledgePayment($contributionID) {
292 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
294 $transaction = new CRM_Core_Transaction();
296 $payment = new CRM_Pledge_DAO_PledgePayment();
297 $payment->contribution_id
= $contributionID;
298 if ($payment->find(TRUE)) {
299 $payment->contribution_id
= 'null';
300 $payment->status_id
= array_search('Pending', $allStatus);
301 $payment->scheduled_date
= NULL;
302 $payment->reminder_date
= NULL;
303 $payment->scheduled_amount
= $payment->actual_amount
;
304 $payment->actual_amount
= 'null';
307 //update pledge status.
308 $pledgeID = $payment->pledge_id
;
309 $pledgeStatusID = self
::calculatePledgeStatus($pledgeID);
310 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'status_id', $pledgeStatusID);
315 $transaction->commit();
320 * Update Pledge Payment Status.
322 * @param int $pledgeID
324 * @param array $paymentIDs
325 * , ids of pledge payment(s) to update.
326 * @param int $paymentStatusID
327 * , payment status to set.
328 * @param int $pledgeStatusID
329 * Pledge status to change (if needed).
330 * @param float|int $actualAmount , actual amount being paid
331 * @param bool $adjustTotalAmount
332 * , is amount being paid different from scheduled amount?.
333 * @param bool $isScriptUpdate
334 * , is function being called from bin script?.
337 * $newStatus, updated status id (or 0)
339 public static function updatePledgePaymentStatus(
342 $paymentStatusID = NULL,
343 $pledgeStatusID = NULL,
345 $adjustTotalAmount = FALSE,
346 $isScriptUpdate = FALSE
348 $totalAmountClause = '';
349 $paymentContributionId = NULL;
350 $editScheduled = FALSE;
353 $allStatus = CRM_Core_OptionGroup
::values('pledge_status',
354 FALSE, FALSE, FALSE, NULL, 'name', TRUE
357 // if we get do not get contribution id means we are editing the scheduled payment.
358 if (!empty($paymentIDs)) {
359 $editScheduled = FALSE;
360 $payments = implode(',', $paymentIDs);
361 $paymentContributionId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
367 if (!$paymentContributionId) {
368 $editScheduled = TRUE;
372 // if payment ids are passed, we update payment table first, since payments statuses are not dependent on pledge status
373 if ((!empty($paymentIDs) ||
$pledgeStatusID == array_search('Cancelled', $allStatus)) && (!$editScheduled ||
$isScriptUpdate)) {
374 if ($pledgeStatusID == array_search('Cancelled', $allStatus)) {
375 $paymentStatusID = $pledgeStatusID;
378 self
::updatePledgePayments($pledgeID, $paymentStatusID, $paymentIDs, $actualAmount, $paymentContributionId, $isScriptUpdate);
380 if (!empty($paymentIDs) && $actualAmount) {
381 $payments = implode(',', $paymentIDs);
382 $pledgeScheduledAmount = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
388 $pledgeStatusId = self
::calculatePledgeStatus($pledgeID);
389 // Actual Pledge Amount
390 $actualPledgeAmount = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
395 // while editing scheduled we need to check if we are editing last pending
396 $lastPending = FALSE;
397 if (!$paymentContributionId) {
398 $checkPendingCount = self
::getOldestPledgePayment($pledgeID, 2);
399 if ($checkPendingCount['count'] == 1) {
404 // check if this is the last payment and adjust the actual amount.
405 if ($pledgeStatusId && $pledgeStatusId == array_search('Completed', $allStatus) ||
$lastPending) {
406 // last scheduled payment
407 if ($actualAmount >= $pledgeScheduledAmount) {
408 $adjustTotalAmount = TRUE;
410 elseif (!$adjustTotalAmount) {
411 // actual amount is less than the scheduled amount, so enter new pledge payment record
412 $pledgeFrequencyUnit = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_unit', 'id');
413 $pledgeFrequencyInterval = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_interval', 'id');
414 $pledgeScheduledDate = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_date', 'id');
415 $scheduled_date = CRM_Utils_Date
::processDate($pledgeScheduledDate);
416 $date['year'] = (int) substr($scheduled_date, 0, 4);
417 $date['month'] = (int) substr($scheduled_date, 4, 2);
418 $date['day'] = (int) substr($scheduled_date, 6, 2);
419 $newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
420 $ScheduledDate = CRM_Utils_Date
::format(CRM_Utils_Date
::intervalAdd($pledgeFrequencyUnit,
421 $pledgeFrequencyInterval, $newDate
423 $pledgeParams = array(
424 'status_id' => array_search('Pending', $allStatus),
425 'pledge_id' => $pledgeID,
426 'scheduled_amount' => ($pledgeScheduledAmount - $actualAmount),
427 'scheduled_date' => $ScheduledDate,
429 $payment = self
::add($pledgeParams);
430 // while editing schedule, after adding a new pledge payemnt update the scheduled amount of the current payment
431 if (!$paymentContributionId) {
432 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_amount', $actualAmount);
436 elseif (!$adjustTotalAmount) {
437 // not last schedule amount and also not selected to adjust Total
438 $paymentContributionId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment',
443 self
::adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId, $payments, $paymentStatusID);
444 // while editing schedule, after adding a new pledge payemnt update the scheduled amount of the current payment
445 if (!$paymentContributionId) {
446 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_amount', $actualAmount);
448 // after adjusting all payments check if the actual amount was greater than the actual remaining amount , if so then update the total pledge amount.
449 $pledgeStatusId = self
::calculatePledgeStatus($pledgeID);
451 SELECT sum( civicrm_pledge_payment.actual_amount )
452 FROM civicrm_pledge_payment
453 WHERE civicrm_pledge_payment.pledge_id = %1
454 AND civicrm_pledge_payment.status_id = 1
456 $totalPaidParams = array(1 => array($pledgeID, 'Integer'));
457 $totalPaidAmount = CRM_Core_DAO
::singleValueQuery($balanceQuery, $totalPaidParams);
458 $remainingTotalAmount = ($actualPledgeAmount - $totalPaidAmount);
459 if (($pledgeStatusId && $pledgeStatusId == array_search('Completed', $allStatus)) && (($actualAmount > $remainingTotalAmount) ||
($actualAmount >= $actualPledgeAmount))) {
460 $totalAmountClause = ", civicrm_pledge.amount = {$totalPaidAmount}";
463 if ($adjustTotalAmount) {
464 $newTotalAmount = ($actualPledgeAmount +
($actualAmount - $pledgeScheduledAmount));
465 $totalAmountClause = ", civicrm_pledge.amount = {$newTotalAmount}";
466 if (!$paymentContributionId) {
467 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $payments, 'scheduled_amount', $actualAmount);
472 $cancelDateClause = $endDateClause = NULL;
473 // update pledge and payment status if status is Completed/Cancelled.
474 if ($pledgeStatusID && $pledgeStatusID == array_search('Cancelled', $allStatus)) {
475 $paymentStatusID = $pledgeStatusID;
476 $cancelDateClause = ", civicrm_pledge.cancel_date = CURRENT_TIMESTAMP ";
480 $pledgeStatusID = self
::calculatePledgeStatus($pledgeID);
483 if ($pledgeStatusID == array_search('Completed', $allStatus)) {
484 $endDateClause = ", civicrm_pledge.end_date = CURRENT_TIMESTAMP ";
487 // update pledge status
489 UPDATE civicrm_pledge
490 SET civicrm_pledge.status_id = %1
491 {$cancelDateClause} {$endDateClause} {$totalAmountClause}
492 WHERE civicrm_pledge.id = %2
496 1 => array($pledgeStatusID, 'Integer'),
497 2 => array($pledgeID, 'Integer'),
500 $dao = CRM_Core_DAO
::executeQuery($query, $params);
502 return $pledgeStatusID;
506 * Calculate the base scheduled date. This function effectively 'rounds' the $params['scheduled_date'] value
507 * to the first payment date with respect to the frequency day - ie. if payments are on the 15th of the month the date returned
508 * will be the 15th of the relevant month. Then to calculate the payments you can use intervalAdd ie.
509 * CRM_Utils_Date::intervalAdd( $params['frequency_unit'], $i * ($params['frequency_interval']) , calculateBaseScheduledDate( &$params )))
511 * @param array $params
514 * Next scheduled date as an array
516 public static function calculateBaseScheduleDate(&$params) {
518 $scheduled_date = CRM_Utils_Date
::processDate($params['scheduled_date']);
519 $date['year'] = (int) substr($scheduled_date, 0, 4);
520 $date['month'] = (int) substr($scheduled_date, 4, 2);
521 $date['day'] = (int) substr($scheduled_date, 6, 2);
522 // calculation of schedule date according to frequency day of period
523 // frequency day is not applicable for daily installments
524 if ($params['frequency_unit'] != 'day' && $params['frequency_unit'] != 'year') {
525 if ($params['frequency_unit'] != 'week') {
526 // CRM-18316: To calculate pledge scheduled dates at the end of a month.
527 $date['day'] = $params['frequency_day'];
528 $lastDayOfMonth = date('t', mktime(0, 0, 0, $date['month'], 1, $date['year']));
529 if ($lastDayOfMonth < $date['day']) {
530 $date['day'] = $lastDayOfMonth;
533 elseif ($params['frequency_unit'] == 'week') {
535 // for week calculate day of week ie. Sunday,Monday etc. as next payment date
536 $dayOfWeek = date('w', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
537 $frequencyDay = $params['frequency_day'] - $dayOfWeek;
539 $scheduleDate = explode("-", date('n-j-Y', mktime(0, 0, 0, $date['month'],
540 $date['day'] +
$frequencyDay, $date['year']
542 $date['month'] = $scheduleDate[0];
543 $date['day'] = $scheduleDate[1];
544 $date['year'] = $scheduleDate[2];
547 $newdate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
552 * Calculate next scheduled pledge payment date. Function calculates next pledge payment date.
554 * @param array $params
555 * must include frequency unit & frequency interval
556 * @param int $paymentNo
557 * number of payment in sequence (e.g. 1 for first calculated payment (treat initial payment as 0)
558 * @param string $basePaymentDate
559 * date to calculate payments from. This would normally be the
560 * first day of the pledge (default) & is calculated off the 'scheduled date' param. Returned date will
561 * be equal to basePaymentDate normalised to fit the 'pledge pattern' + number of installments
566 public static function calculateNextScheduledDate(&$params, $paymentNo, $basePaymentDate = NULL) {
567 $interval = $paymentNo * ($params['frequency_interval']);
568 if (!$basePaymentDate) {
569 $basePaymentDate = self
::calculateBaseScheduleDate($params);
572 //CRM-18316 - change $basePaymentDate for the end dates of the month eg: 29, 30 or 31.
573 if ($params['frequency_unit'] == 'month' && in_array($params['frequency_day'], array(29, 30, 31))) {
574 $frequency = $params['frequency_day'];
575 extract(date_parse($basePaymentDate));
576 $lastDayOfMonth = date('t', mktime($hour, $minute, $second, $month +
$interval, 1, $year));
577 // Take the last day in case the current month is Feb or frequency_day is set to 31.
578 if (in_array($lastDayOfMonth, array(28, 29)) ||
$frequency == 31) {
582 $basePaymentDate = array(
589 return CRM_Utils_Date
::format(
590 CRM_Utils_Date
::intervalAdd(
591 $params['frequency_unit'],
599 * Calculate the pledge status.
601 * @param int $pledgeId
605 * $statusId calculated status id of pledge
607 public static function calculatePledgeStatus($pledgeId) {
608 $paymentStatusTypes = CRM_Pledge_BAO_PledgePayment
::buildOptions('status_id');
609 $pledgeStatusTypes = CRM_Pledge_BAO_Pledge
::buildOptions('status_id');
611 //return if the pledge is cancelled.
612 $currentPledgeStatusId = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'status_id', 'id', TRUE);
613 if ($currentPledgeStatusId == array_search('Cancelled', $pledgeStatusTypes)) {
614 return $currentPledgeStatusId;
617 // retrieve all pledge payments for this particular pledge
618 $allPledgePayments = $allStatus = array();
619 $returnProperties = array('status_id');
620 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $pledgeId, $allPledgePayments, $returnProperties);
622 // build pledge payment statuses
623 foreach ($allPledgePayments as $key => $value) {
624 $allStatus[$value['id']] = $paymentStatusTypes[$value['status_id']];
627 if (array_search('Overdue', $allStatus)) {
628 $statusId = array_search('Overdue', $pledgeStatusTypes);
630 elseif (array_search('Completed', $allStatus)) {
631 if (count(array_count_values($allStatus)) == 1) {
632 $statusId = array_search('Completed', $pledgeStatusTypes);
635 $statusId = array_search('In Progress', $pledgeStatusTypes);
639 $statusId = array_search('Pending', $pledgeStatusTypes);
646 * Update pledge payment table.
648 * @param int $pledgeId
650 * @param int $paymentStatusId
651 * Payment status id to set.
652 * @param array $paymentIds
653 * Payment ids to be updated.
654 * @param float|int $actualAmount , actual amount being paid
655 * @param int $contributionId
656 * , Id of associated contribution when payment is recorded.
657 * @param bool $isScriptUpdate
658 * , is function being called from bin script?.
661 public static function updatePledgePayments(
666 $contributionId = NULL,
667 $isScriptUpdate = FALSE
669 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
670 $paymentClause = NULL;
671 if (!empty($paymentIds)) {
672 $payments = implode(',', $paymentIds);
673 $paymentClause = " AND civicrm_pledge_payment.id IN ( {$payments} )";
675 elseif ($paymentStatusId == array_search('Cancelled', $allStatus)) {
676 $completedStatus = array_search('Completed', $allStatus);
677 $paymentClause = " AND civicrm_pledge_payment.status_id != {$completedStatus}";
679 $actualAmountClause = NULL;
680 $contributionIdClause = NULL;
681 if (isset($contributionId) && !$isScriptUpdate) {
682 $contributionIdClause = ", civicrm_pledge_payment.contribution_id = {$contributionId}";
683 $actualAmountClause = ", civicrm_pledge_payment.actual_amount = {$actualAmount}";
687 UPDATE civicrm_pledge_payment
688 SET civicrm_pledge_payment.status_id = {$paymentStatusId}
689 {$actualAmountClause} {$contributionIdClause}
690 WHERE civicrm_pledge_payment.pledge_id = %1
695 $params = array(1 => array($pledgeId, 'Integer'));
697 $dao = CRM_Core_DAO
::executeQuery($query, $params);
701 * Update pledge payment table when reminder is sent.
703 * @param int $paymentId
706 public static function updateReminderDetails($paymentId) {
708 UPDATE civicrm_pledge_payment
709 SET civicrm_pledge_payment.reminder_date = CURRENT_TIMESTAMP,
710 civicrm_pledge_payment.reminder_count = civicrm_pledge_payment.reminder_count + 1
711 WHERE civicrm_pledge_payment.id = {$paymentId}
713 $dao = CRM_Core_DAO
::executeQuery($query);
717 * Get oldest pending or in progress pledge payments.
719 * @param int $pledgeID
725 * associated array of pledge details
727 public static function getOldestPledgePayment($pledgeID, $limit = 1) {
728 // get pending / overdue statuses
729 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
730 FALSE, FALSE, FALSE, NULL, 'name'
733 // get pending and overdue payments
734 $status[] = array_search('Pending', $pledgeStatuses);
735 $status[] = array_search('Overdue', $pledgeStatuses);
737 $statusClause = " IN (" . implode(',', $status) . ")";
740 SELECT civicrm_pledge_payment.id id, civicrm_pledge_payment.scheduled_amount amount, civicrm_pledge_payment.currency, civicrm_pledge_payment.scheduled_date,civicrm_pledge.financial_type_id
741 FROM civicrm_pledge, civicrm_pledge_payment
742 WHERE civicrm_pledge.id = civicrm_pledge_payment.pledge_id
743 AND civicrm_pledge_payment.status_id {$statusClause}
744 AND civicrm_pledge.id = %1
745 ORDER BY civicrm_pledge_payment.scheduled_date ASC
749 $params[1] = array($pledgeID, 'Integer');
750 $params[2] = array($limit, 'Integer');
751 $payment = CRM_Core_DAO
::executeQuery($query, $params);
753 $paymentDetails = array();
754 while ($payment->fetch()) {
755 $paymentDetails[] = array(
756 'id' => $payment->id
,
757 'amount' => $payment->amount
,
758 'currency' => $payment->currency
,
759 'schedule_date' => $payment->scheduled_date
,
760 'financial_type_id' => $payment->financial_type_id
,
765 return end($paymentDetails);
769 * @param int $pledgeID
770 * @param $actualAmount
771 * @param $pledgeScheduledAmount
772 * @param int $paymentContributionId
773 * @param int $pPaymentId
774 * @param int $paymentStatusID
776 public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId = NULL, $pPaymentId = NULL, $paymentStatusID = NULL) {
777 $allStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
778 if ($paymentStatusID == array_search('Cancelled', $allStatus) ||
$paymentStatusID == array_search('Refunded', $allStatus)) {
780 SELECT civicrm_pledge_payment.id id
781 FROM civicrm_pledge_payment
782 WHERE civicrm_pledge_payment.contribution_id = {$paymentContributionId}
784 $paymentsAffected = CRM_Core_DAO
::executeQuery($query);
785 $paymentIDs = array();
786 while ($paymentsAffected->fetch()) {
787 $paymentIDs[] = $paymentsAffected->id
;
789 // Reset the affected values by the amount paid more than the scheduled amount
790 foreach ($paymentIDs as $key => $value) {
791 $payment = new CRM_Pledge_DAO_PledgePayment();
792 $payment->id
= $value;
793 if ($payment->find(TRUE)) {
794 $payment->contribution_id
= 'null';
795 $payment->status_id
= array_search('Pending', $allStatus);
796 $payment->scheduled_date
= NULL;
797 $payment->reminder_date
= NULL;
798 $payment->scheduled_amount
= $pledgeScheduledAmount;
799 $payment->actual_amount
= 'null';
804 // Cancel the initial paid amount
805 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', reset($paymentIDs), 'status_id', $paymentStatusID, 'id');
806 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', reset($paymentIDs), 'actual_amount', $actualAmount, 'id');
808 // Add new payment after the last payment for the pledge
809 $allPayments = self
::getPledgePayments($pledgeID);
810 $lastPayment = array_pop($allPayments);
812 $pledgeFrequencyUnit = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_unit', 'id');
813 $pledgeFrequencyInterval = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_interval', 'id');
814 $pledgeScheduledDate = $lastPayment['scheduled_date'];
815 $scheduled_date = CRM_Utils_Date
::processDate($pledgeScheduledDate);
816 $date['year'] = (int) substr($scheduled_date, 0, 4);
817 $date['month'] = (int) substr($scheduled_date, 4, 2);
818 $date['day'] = (int) substr($scheduled_date, 6, 2);
819 $newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
820 $ScheduledDate = CRM_Utils_Date
::format(CRM_Utils_Date
::intervalAdd($pledgeFrequencyUnit, $pledgeFrequencyInterval, $newDate));
821 $pledgeParams = array(
822 'status_id' => array_search('Pending', $allStatus),
823 'pledge_id' => $pledgeID,
824 'scheduled_amount' => $pledgeScheduledAmount,
825 'scheduled_date' => $ScheduledDate,
827 $payment = self
::add($pledgeParams);
830 $oldestPayment = self
::getOldestPledgePayment($pledgeID);
831 if (!$paymentContributionId) {
832 // means we are editing payment scheduled payment, so get the second pending to update.
833 $oldestPayment = self
::getOldestPledgePayment($pledgeID, 2);
834 if (($oldestPayment['count'] != 1) && ($oldestPayment['id'] == $pPaymentId)) {
835 $oldestPayment = self
::getOldestPledgePayment($pledgeID);
839 if ($oldestPayment) {
840 // not the last scheduled payment and the actual amount is less than the expected , add it to oldest pending.
841 if (($actualAmount != $pledgeScheduledAmount) && (($actualAmount < $pledgeScheduledAmount) ||
(($actualAmount - $pledgeScheduledAmount) < $oldestPayment['amount']))) {
842 $oldScheduledAmount = $oldestPayment['amount'];
843 $newScheduledAmount = $oldScheduledAmount +
($pledgeScheduledAmount - $actualAmount);
844 // store new amount in oldest pending payment record.
845 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment',
846 $oldestPayment['id'],
850 if (CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'contribution_id', 'id')) {
851 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment',
852 $oldestPayment['id'],
854 $paymentContributionId
858 elseif (($actualAmount > $pledgeScheduledAmount) && (($actualAmount - $pledgeScheduledAmount) >= $oldestPayment['amount'])) {
859 // here the actual amount is greater than expected and also greater than the next installment amount, so update the next installment as complete and again add it to next subsequent pending payment
860 // set the actual amount of the next pending to '0', set contribution Id to current contribution Id and status as completed
861 $paymentId = array($oldestPayment['id']);
862 self
::updatePledgePayments($pledgeID, array_search('Completed', $allStatus), $paymentId, 0, $paymentContributionId);
863 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'scheduled_amount', 0, 'id');
864 $oldestPayment = self
::getOldestPledgePayment($pledgeID);
865 if (!$paymentContributionId) {
866 // means we are editing payment scheduled payment.
867 $oldestPaymentAmount = self
::getOldestPledgePayment($pledgeID, 2);
869 $newActualAmount = ($actualAmount - $pledgeScheduledAmount);
870 $newPledgeScheduledAmount = $oldestPayment['amount'];
871 if (!$paymentContributionId) {
872 $newActualAmount = ($actualAmount - $pledgeScheduledAmount);
873 $newPledgeScheduledAmount = $oldestPaymentAmount['amount'];
874 // means we are editing payment scheduled payment, so update scheduled amount.
875 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment',
876 $oldestPaymentAmount['id'],
881 if ($newActualAmount > 0) {
882 self
::adjustPledgePayment($pledgeID, $newActualAmount, $newPledgeScheduledAmount, $paymentContributionId);
890 * Override buildOptions to hack out some statuses.
892 * @todo instead of using & hacking the shared optionGroup contribution_status use a separate one.
894 * @param string $fieldName
895 * @param string $context
896 * @param array $props
900 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
901 $result = parent
::buildOptions($fieldName, $context, $props);
902 if ($fieldName == 'status_id') {
903 $result = CRM_Pledge_BAO_Pledge
::buildOptions($fieldName, $context, $props);
904 $result = array_diff($result, array('Failed', 'In Progress'));