3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Pledge_BAO_Pledge
extends CRM_Pledge_DAO_Pledge
{
20 * Static field for all the pledge information that we can potentially export.
24 public static $_exportableFields = NULL;
27 * Retrieve DB object and copy to defaults array.
29 * @param array $params
30 * Array of criteria values.
31 * @param array $defaults
32 * Array to be populated with found values.
35 * The DAO object, if found.
39 public static function retrieve($params, &$defaults) {
40 return self
::commonRetrieve(self
::class, $params, $defaults);
46 * @param array $params
47 * Reference array contains the values submitted by the form.
49 * @return CRM_Pledge_DAO_Pledge
51 public static function add(array $params): CRM_Pledge_DAO_Pledge
{
52 CRM_Core_Error
::deprecatedFunctionWarning('v4 api');
53 $hook = empty($params['id']) ?
'create' : 'edit';
54 CRM_Utils_Hook
::pre($hook, 'Pledge', $params['id'] ??
NULL, $params);
56 $pledge = new CRM_Pledge_DAO_Pledge();
58 // if pledge is complete update end date as current date
59 if ($pledge->status_id
== 1) {
60 $pledge->end_date
= date('Ymd');
63 $pledge->copyValues($params);
65 // set currency for CRM-1496
66 if (!isset($pledge->currency
)) {
67 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
70 $result = $pledge->save();
72 CRM_Utils_Hook
::post($hook, 'Pledge', $pledge->id
, $pledge);
78 * Given the list of params in the params array, fetch the object
79 * and store the values in the values array
81 * @param array $params
82 * Input parameters to find object.
83 * @param array $values
84 * Output values of the object.
85 * @param array $returnProperties
86 * If you want to return specific fields.
89 * associated array of field values
91 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
95 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
100 * Takes an associative array and creates a pledge object.
102 * @param array $params
103 * Assoc array of name/value pairs.
105 * @return CRM_Pledge_DAO_Pledge
106 * @throws \CRM_Core_Exception
108 public static function create(array $params): CRM_Pledge_DAO_Pledge
{
109 $action = empty($params['id']) ?
'create' : 'edit';
110 if ($action === 'create') {
112 'currency' => CRM_Core_Config
::singleton()->defaultCurrency
,
113 'installments' => (int) self
::fields()['installments']['default'],
114 'scheduled_date' => $params['start_date'] ??
date('Ymd'),
116 $params = array_merge($defaults, $params);
119 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
120 $transaction = new CRM_Core_Transaction();
123 if (!empty($params['installment_amount'])) {
124 $params['amount'] = $params['installment_amount'] * $params['installments'];
127 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
128 if (isset($params['contribution_id'])) {
129 if ($params['installments'] > 1) {
130 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
134 if (!empty($params['id'])) {
135 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
138 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
142 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
144 $pledge = self
::writeRecord($params);
146 // skip payment stuff in edit mode
147 if (empty($params['id']) ||
$isRecalculatePledgePayment) {
149 // if pledge is pending delete all payments and recreate.
150 if ($isRecalculatePledgePayment) {
151 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
154 // building payment params
155 $paymentParams['pledge_id'] = $pledge->id
;
163 'frequency_interval',
165 'installment_amount',
168 foreach ($paymentKeys as $key) {
169 $paymentParams[$key] = $params[$key] ??
NULL;
171 CRM_Pledge_BAO_PledgePayment
::createMultiple($paymentParams);
174 $transaction->commit();
176 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
177 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
181 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
182 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
183 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
186 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
187 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
188 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
192 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
193 $title = CRM_Contact_BAO_Contact
::displayName($pledge->contact_id
) . ' - (' . ts('Pledged') . ' ' . CRM_Utils_Money
::format($pledge->amount
, $pledge->currency
) . ' - ' . CRM_Utils_Array
::value($pledge->financial_type_id
, $contributionTypes) . ')';
195 // add the recently created Pledge
196 CRM_Utils_Recent
::add($title,
209 * Is this a change to an existing pending pledge requiring payment schedule
212 * If the pledge is pending the code (slightly lazily) deletes & recreates
215 * If the payment dates or amounts have been manually edited then this can
216 * cause data loss. We can mitigate this to some extent by making sure we
217 * have a change that could potentially affect the schedule (rather than just
218 * a custom data change or similar).
220 * This calculation needs to be performed before update takes place as
221 * previous & new pledges are compared.
223 * @param array $params
227 protected static function isPaymentsRequireRecalculation($params) {
228 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
231 $scheduleChangingParameters = [
234 'frequency_interval',
239 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
240 $existingPledgeDAO->id
= $params['id'];
241 $existingPledgeDAO->find(TRUE);
242 foreach ($scheduleChangingParameters as $parameter) {
243 if ($parameter == 'start_date') {
244 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
248 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
262 public static function deletePledge($id) {
263 CRM_Utils_Hook
::pre('delete', 'Pledge', $id);
265 $transaction = new CRM_Core_Transaction();
267 // check for no Completed Payment records with the pledge
268 $payment = new CRM_Pledge_DAO_PledgePayment();
269 $payment->pledge_id
= $id;
272 while ($payment->fetch()) {
273 // also delete associated contribution.
274 if ($payment->contribution_id
) {
275 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
280 $dao = new CRM_Pledge_DAO_Pledge();
282 $results = $dao->delete();
284 $transaction->commit();
286 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
292 * Get the amount details date wise.
294 * @param string $status
295 * @param string $startDate
296 * @param string $endDate
300 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
302 $select = $from = $queryDate = NULL;
303 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
307 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
314 $where[] = 'status_id = ' . $statusId;
319 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
322 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
325 $whereCond = implode(' AND ', $where);
328 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
330 WHERE $whereCond AND is_test=0
333 $start = substr($startDate, 0, 8);
334 $end = substr($endDate, 0, 8);
337 $dao = CRM_Core_DAO
::executeQuery($query);
338 while ($dao->fetch()) {
339 $pCount +
= $dao->pledge_count
;
340 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
344 'pledge_amount' => implode(', ', $pamount),
345 'pledge_count' => $pCount,
346 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
347 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
354 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
355 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
356 $queryDate = 'receive_date';
357 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
361 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
362 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
363 $queryDate = 'receive_date';
364 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
368 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
369 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
370 $queryDate = 'scheduled_date';
371 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
375 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
376 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
377 $queryDate = 'scheduled_date';
378 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
383 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
386 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
389 $whereCond = implode(' AND ', $where);
392 SELECT $select, cp.currency
398 $dao = CRM_Core_DAO
::executeQuery($query);
402 while ($dao->fetch()) {
403 $count +
= $dao->received_count
;
404 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
408 return array_merge($pledge_amount, [
409 'received_amount' => implode(', ', $amount),
410 'received_count' => $count,
411 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
412 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
418 return $pledge_amount;
424 * Get list of pledges In Honor of contact Ids.
426 * @param int $honorId
427 * In Honor of Contact ID.
430 * return the list of pledge fields
432 public static function getHonorContacts($honorId) {
434 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
435 $honorDAO->contact_id
= $honorId;
439 while ($honorDAO->fetch()) {
440 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
441 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
442 if ($pledgePaymentDAO->find(TRUE)) {
443 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
444 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
445 if ($pledgeDAO->find(TRUE)) {
446 $params[$pledgeDAO->id
] = [
447 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
448 'honorId' => $pledgeDAO->contact_id
,
449 'amount' => $pledgeDAO->amount
,
450 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
451 'create_date' => $pledgeDAO->create_date
,
452 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
453 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
454 $pledgeDAO->financial_type_id
, 'name'
456 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
457 $pledgeDAO->contact_id
, 'display_name'
468 * Send Acknowledgment and create activity.
470 * @param CRM_Core_Form $form
472 * @param array $params
473 * An assoc array of name/value pairs.
475 public static function sendAcknowledgment(&$form, $params) {
476 //handle Acknowledgment.
477 $allPayments = $payments = [];
479 // get All Payments status types.
480 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
481 $returnProperties = [
487 // get all paymnets details.
488 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
490 if (!empty($allPayments)) {
491 foreach ($allPayments as $payID => $values) {
492 $contributionValue = $contributionStatus = [];
493 if (isset($values['contribution_id'])) {
494 $contributionParams = ['id' => $values['contribution_id']];
495 $returnProperties = ['contribution_status_id', 'receive_date'];
496 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
497 $contributionParams, $contributionStatus, $returnProperties
499 $contributionValue = [
500 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
501 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
504 $payments[$payID] = array_merge($contributionValue,
506 'amount' => $values['scheduled_amount'] ??
NULL,
507 'due_date' => $values['scheduled_date'] ??
NULL,
508 'status' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'),
512 // get the first valid payment id.
513 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
514 $paymentStatusTypes[$values['status_id']] == 'Overdue'
517 $form->paymentId
= $values['id'];
522 // assign pledge fields value to template.
525 'total_pledge_amount',
526 'frequency_interval',
533 foreach ($pledgeFields as $field) {
534 if (!empty($params[$field])) {
535 $form->assign($field, $params[$field]);
539 // assign all payments details.
541 $form->assign('payments', $payments);
544 // handle custom data.
546 if (!empty($params['hidden_custom'])) {
547 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
548 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
549 // retrieve custom data
550 foreach ($groupTree as $groupID => $group) {
551 $customFields = $customValues = [];
552 if ($groupID == 'info') {
555 foreach ($group['fields'] as $k => $field) {
556 $field['title'] = $field['label'];
557 $customFields["custom_{$k}"] = $field;
560 // to build array of customgroup & customfields in it
561 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
562 $customGroup[$group['title']] = $customValues;
566 $form->assign('customGroup', $customGroup);
568 // handle acknowledgment email stuff.
569 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
571 // check for online pledge.
572 if (!empty($params['receipt_from_email'])) {
573 $userName = $params['receipt_from_name'] ??
NULL;
574 $userEmail = $params['receipt_from_email'] ??
NULL;
576 elseif (!empty($params['from_email_id'])) {
577 $receiptFrom = $params['from_email_id'];
579 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
580 // check for logged in user.
584 ] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
587 // set the domain values.
588 [$userName, $userEmail] = CRM_Core_BAO_Domain
::getNameAndEmail();
591 if (!isset($receiptFrom)) {
592 $receiptFrom = "$userName <$userEmail>";
595 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
597 'groupName' => 'msg_tpl_workflow_pledge',
598 'valueName' => 'pledge_acknowledge',
599 'contactId' => $params['contact_id'],
600 'from' => $receiptFrom,
601 'toName' => $pledgerDisplayName,
602 'toEmail' => $pledgerEmail,
606 // check if activity record exist for this pledge
607 // Acknowledgment, if exist do not add activity.
608 $activityType = 'Pledge Acknowledgment';
609 $activity = new CRM_Activity_DAO_Activity();
610 $activity->source_record_id
= $params['id'];
611 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
617 $details = 'Total Amount ' . CRM_Utils_Money
::format($params['total_pledge_amount'], CRM_Utils_Array
::value('currency', $params)) . ' To be paid in ' . $params['installments'] . ' installments of ' . CRM_Utils_Money
::format($params['scheduled_amount'], CRM_Utils_Array
::value('currency', $params)) . ' every ' . $params['frequency_interval'] . ' ' . $params['frequency_unit'] . '(s)';
619 if (!$activity->find()) {
621 'subject' => $subject,
622 'source_contact_id' => $params['contact_id'],
623 'source_record_id' => $params['id'],
624 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
628 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
629 'is_test' => $params['is_test'],
631 'details' => $details,
632 'campaign_id' => $params['campaign_id'] ??
NULL,
635 // lets insert assignee record.
636 if (!empty($params['contact_id'])) {
637 $activityParams['assignee_contact_id'] = $params['contact_id'];
640 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
641 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
647 * Combine all the exportable fields from the lower levels object.
649 * @param bool $checkPermission
652 * array of exportable Fields
654 public static function exportableFields($checkPermission = TRUE) {
655 if (!self
::$_exportableFields) {
656 if (!self
::$_exportableFields) {
657 self
::$_exportableFields = [];
660 $fields = CRM_Pledge_DAO_Pledge
::export();
662 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
664 // set title to calculated fields
665 $calculatedFields = [
666 'pledge_total_paid' => ['title' => ts('Total Paid')],
667 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
668 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
669 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
670 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
671 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
672 'pledge_payment_status' => [
673 'title' => ts('Pledge Payment Status'),
674 'name' => 'pledge_payment_status',
675 'data_type' => CRM_Utils_Type
::T_STRING
,
681 'title' => ts('Pledge Status'),
682 'name' => 'pledge_status',
683 'data_type' => CRM_Utils_Type
::T_STRING
,
685 'pledge_frequency_unit' => [
686 'title' => ts('Pledge Frequency Unit'),
687 'name' => 'pledge_frequency_unit',
688 'data_type' => CRM_Utils_Type
::T_ENUM
,
690 'pledge_frequency_interval' => [
691 'title' => ts('Pledge Frequency Interval'),
692 'name' => 'pledge_frequency_interval',
693 'data_type' => CRM_Utils_Type
::T_INT
,
695 'pledge_contribution_page_id' => [
696 'title' => ts('Pledge Contribution Page Id'),
697 'name' => 'pledge_contribution_page_id',
698 'data_type' => CRM_Utils_Type
::T_INT
,
702 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
705 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
706 self
::$_exportableFields = $fields;
709 return self
::$_exportableFields;
713 * Get pending or in progress pledges.
715 * @param int $contactID
719 * associated array of pledge id(s)
721 public static function getContactPledges($contactID) {
723 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
724 FALSE, FALSE, FALSE, NULL, 'name'
729 // get pending and in progress status
730 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
731 if ($statusId = array_search($name, $pledgeStatuses)) {
732 $status[] = $statusId;
735 if (empty($status)) {
736 return $pledgeDetails;
739 $statusClause = " IN (" . implode(',', $status) . ")";
742 SELECT civicrm_pledge.id id
744 WHERE civicrm_pledge.status_id {$statusClause}
745 AND civicrm_pledge.contact_id = %1
748 $params[1] = [$contactID, 'Integer'];
749 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
751 while ($pledge->fetch()) {
752 $pledgeDetails[] = $pledge->id
;
755 return $pledgeDetails;
759 * Get pledge record count for a Contact.
761 * @param int $contactID
764 * count of pledge records
766 public static function getContactPledgeCount($contactID) {
767 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
768 return CRM_Core_DAO
::singleValueQuery($query);
772 * @param array $params
775 * @throws \API_Exception
776 * @throws \CRM_Core_Exception
777 * @throws \CiviCRM_API3_Exception
779 public static function updatePledgeStatus($params): array {
781 $returnMessages = [];
783 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
785 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
786 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
787 TRUE, FALSE, FALSE, NULL, 'name', TRUE
789 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
790 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
792 $statusIds = implode(',', $allStatus);
793 $pledgeStatusIds = implode(',', $allPledgeStatus);
797 SELECT pledge.contact_id as contact_id,
798 pledge.id as pledge_id,
799 pledge.amount as amount,
800 payment.scheduled_date as scheduled_date,
801 pledge.create_date as create_date,
802 payment.id as payment_id,
803 pledge.currency as currency,
804 pledge.contribution_page_id as contribution_page_id,
805 payment.reminder_count as reminder_count,
806 pledge.max_reminders as max_reminders,
807 payment.reminder_date as reminder_date,
808 pledge.initial_reminder_day as initial_reminder_day,
809 pledge.additional_reminder_day as additional_reminder_day,
810 pledge.status_id as pledge_status,
811 payment.status_id as payment_status,
812 pledge.is_test as is_test,
813 pledge.campaign_id as campaign_id,
814 SUM(payment.scheduled_amount) as amount_due,
815 ( SELECT sum(civicrm_pledge_payment.actual_amount)
816 FROM civicrm_pledge_payment
817 WHERE civicrm_pledge_payment.status_id = 1
818 AND civicrm_pledge_payment.pledge_id = pledge.id
820 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
821 WHERE pledge.id = payment.pledge_id
822 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
826 $dao = CRM_Core_DAO
::executeQuery($query);
829 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
830 while ($dao->fetch()) {
831 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
833 $pledgeDetails[$dao->payment_id
] = [
834 'scheduled_date' => $dao->scheduled_date
,
835 'amount_due' => $dao->amount_due
,
836 'amount' => $dao->amount
,
837 'amount_paid' => $dao->amount_paid
,
838 'create_date' => $dao->create_date
,
839 'contact_id' => $dao->contact_id
,
840 'pledge_id' => $dao->pledge_id
,
841 'checksumValue' => $checksumValue,
842 'contribution_page_id' => $dao->contribution_page_id
,
843 'reminder_count' => $dao->reminder_count
,
844 'max_reminders' => $dao->max_reminders
,
845 'reminder_date' => $dao->reminder_date
,
846 'initial_reminder_day' => $dao->initial_reminder_day
,
847 'additional_reminder_day' => $dao->additional_reminder_day
,
848 'pledge_status' => $dao->pledge_status
,
849 'payment_status' => $dao->payment_status
,
850 'is_test' => $dao->is_test
,
851 'currency' => $dao->currency
,
852 'campaign_id' => $dao->campaign_id
,
855 $contactIds[$dao->contact_id
] = $dao->contact_id
;
856 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
858 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
860 ) && $dao->payment_status
!= $allStatus['Overdue']
862 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
865 $allPledgeStatus = array_flip($allPledgeStatus);
867 // process the updating script...
868 foreach ($pledgePayments as $pledgeId => $paymentIds) {
869 // 1. update the pledge /pledge payment status. returns new status when an update happens
870 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
872 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
873 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
875 if ($newStatus != $pledgeStatus[$pledgeId]) {
876 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
881 if ($sendReminders) {
882 // retrieve domain tokens
884 'domain' => ['name', 'phone', 'address', 'email'],
885 'contact' => CRM_Core_SelectValues
::contactTokens(),
888 // retrieve contact tokens
890 // this function does NOT return Deceased contacts since we don't want to send them email
891 $contactDetails = civicrm_api3('Contact', 'get', [
893 'id' => ['IN' => $contactIds],
894 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'],
897 // assign domain values to template
898 $template = CRM_Core_Smarty
::singleton();
901 $receiptFrom = CRM_Core_BAO_Domain
::getNameAndEmail(FALSE, TRUE);
902 $receiptFrom = reset($receiptFrom);
904 foreach ($pledgeDetails as $paymentId => $details) {
905 if (array_key_exists($details['contact_id'], $contactDetails)) {
906 $contactId = $details['contact_id'];
907 $pledgerName = $contactDetails[$contactId]['display_name'];
913 if (empty($details['reminder_date'])) {
914 $nextReminderDate = new DateTime($details['scheduled_date']);
915 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
916 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
917 $nextReminderDate = $nextReminderDate->format("Ymd");
920 $nextReminderDate = new DateTime($details['reminder_date']);
921 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
922 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
923 $nextReminderDate = $nextReminderDate->format("Ymd");
925 if (($details['reminder_count'] < $details['max_reminders'])
926 && ($nextReminderDate <= $now)
929 $toEmail = $doNotEmail = $onHold = NULL;
931 if (!empty($contactDetails[$contactId]['email'])) {
932 $toEmail = $contactDetails[$contactId]['email'];
935 if (!empty($contactDetails[$contactId]['do_not_email'])) {
936 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
939 if (!empty($contactDetails[$contactId]['on_hold'])) {
940 $onHold = $contactDetails[$contactId]['on_hold'];
943 // 2. send acknowledgement mail
944 if ($toEmail && !($doNotEmail ||
$onHold)) {
945 // assign value to template
946 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
947 $template->assign('next_payment', $details['scheduled_date']);
948 $template->assign('amount_due', $details['amount_due']);
949 $template->assign('checksumValue', $details['checksumValue']);
950 $template->assign('contribution_page_id', $details['contribution_page_id']);
951 $template->assign('pledge_id', $details['pledge_id']);
952 $template->assign('scheduled_payment_date', $details['scheduled_date']);
953 $template->assign('amount', $details['amount']);
954 $template->assign('create_date', $details['create_date']);
955 $template->assign('currency', $details['currency']);
961 ] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
963 'groupName' => 'msg_tpl_workflow_pledge',
964 'valueName' => 'pledge_reminder',
965 'contactId' => $contactId,
966 'from' => $receiptFrom,
967 'toName' => $pledgerName,
968 'toEmail' => $toEmail,
972 // 3. update pledge payment details
974 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
975 $activityType = 'Pledge Reminder';
977 'subject' => $subject,
978 'source_contact_id' => $contactId,
979 'source_record_id' => $paymentId,
980 'assignee_contact_id' => $contactId,
981 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
985 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
986 'is_test' => $details['is_test'],
988 'campaign_id' => $details['campaign_id'],
991 civicrm_api3('activity', 'create', $activityParams);
993 catch (CiviCRM_API3_Exception
$e) {
994 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
995 return ['is_error' => 1, 'message' => $returnMessages];
997 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1002 // end foreach on $pledgeDetails
1004 // end if ( $sendReminders )
1005 $returnMessages[] = "{$updateCnt} records updated.";
1007 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1011 * Mark a pledge (and any outstanding payments) as cancelled.
1013 * @param int $pledgeID
1015 public static function cancel($pledgeID) {
1016 $paymentIDs = self
::findCancelablePayments($pledgeID);
1017 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1018 $cancelled = array_search('Cancelled', $status);
1019 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1020 $cancelled, 0, FALSE, TRUE
1025 * Find payments which can be safely canceled.
1027 * @param int $pledgeID
1030 * Array of int (civicrm_pledge_payment.id)
1032 public static function findCancelablePayments($pledgeID) {
1033 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1035 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1036 $paymentDAO->pledge_id
= $pledgeID;
1037 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1038 $statuses['Overdue'],
1039 $statuses['Pending']
1041 $paymentDAO->find();
1044 while ($paymentDAO->fetch()) {
1045 $paymentIDs[] = $paymentDAO->id
;
1051 * Is this pledge free from financial transactions (this is important to know
1052 * as we allow editing when no transactions have taken place - the editing
1053 * process currently involves deleting all pledge payments & contributions
1054 * & recreating so we want to block that if appropriate).
1056 * @param int $pledgeID
1057 * @param int $pledgeStatusID
1060 * do financial transactions exist for this pledge?
1062 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1063 if (empty($pledgeStatusID)) {
1064 // why would this happen? If we can see where it does then we can see if we should look it up.
1065 // but assuming from form code it CAN be empty.
1068 if (self
::isTransactedStatus($pledgeStatusID)) {
1072 return civicrm_api3('pledge_payment', 'getcount', [
1073 'pledge_id' => $pledgeID,
1074 'contribution_id' => ['IS NOT NULL' => TRUE],
1079 * Does this pledge / pledge payment status mean that a financial transaction
1082 * @param int $statusID
1086 * is it a transactional status?
1088 protected static function isTransactedStatus($statusID) {
1089 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1096 * Get array of non transactional statuses.
1099 * non transactional status ids
1101 protected static function getNonTransactionalStatus() {
1102 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1103 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1107 * Create array for recur record for pledge.
1110 * params for recur record
1112 public static function buildRecurParams($params) {
1115 'auto_renew' => TRUE,
1116 'frequency_unit' => $params['pledge_frequency_unit'],
1117 'frequency_interval' => $params['pledge_frequency_interval'],
1118 'installments' => $params['pledge_installments'],
1119 'start_date' => $params['receive_date'],
1121 return $recurParams;
1125 * Get pledge start date.
1130 public static function getPledgeStartDate($date, $pledgeBlock) {
1131 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1132 foreach ($startDate as $field => $value) {
1133 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1140 case 'contribution_date':
1142 $date = date('Ymd');
1146 case 'calendar_date':
1147 $date = date('Ymd', strtotime($date));
1150 case 'calendar_month':
1151 $date = self
::getPaymentDate($date);
1152 $date = date('Ymd', strtotime($date));
1164 * Get first payment date for pledge.
1168 * @return bool|string
1170 public static function getPaymentDate($day) {
1172 // Find out if current month has 31 days, if not, set it to 30 (last day).
1178 $current = date('d');
1180 case ($day == $current):
1181 $date = date('m/d/Y');
1184 case ($day > $current):
1185 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1188 case ($day < $current):
1189 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1200 * Override buildOptions to hack out some statuses.
1202 * @param string $fieldName
1203 * @param string $context
1204 * @param array $props
1206 * @return array|bool
1207 * @todo instead of using & hacking the shared optionGroup
1208 * contribution_status use a separate one.
1211 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1212 $result = parent
::buildOptions($fieldName, $context, $props);
1213 if ($fieldName == 'status_id') {
1214 $result = array_diff($result, ['Failed']);