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;
29 public function __construct() {
30 parent
::__construct();
34 * Retrieve DB object based on input parameters.
36 * It also stores all the retrieved values in the default array.
38 * @param array $params
39 * (reference ) an assoc array of name/value pairs.
40 * @param array $defaults
41 * (reference ) an assoc array to hold the flattened values.
43 * @return CRM_Pledge_BAO_Pledge
45 public static function retrieve(&$params, &$defaults) {
46 $pledge = new CRM_Pledge_DAO_Pledge();
47 $pledge->copyValues($params);
48 if ($pledge->find(TRUE)) {
49 CRM_Core_DAO
::storeValues($pledge, $defaults);
58 * @param array $params
59 * Reference array contains the values submitted by the form.
61 * @return CRM_Pledge_DAO_Pledge
63 public static function add(array $params): CRM_Pledge_DAO_Pledge
{
64 CRM_Core_Error
::deprecatedFunctionWarning('v4 api');
65 $hook = empty($params['id']) ?
'create' : 'edit';
66 CRM_Utils_Hook
::pre($hook, 'Pledge', $params['id'] ??
NULL, $params);
68 $pledge = new CRM_Pledge_DAO_Pledge();
70 // if pledge is complete update end date as current date
71 if ($pledge->status_id
== 1) {
72 $pledge->end_date
= date('Ymd');
75 $pledge->copyValues($params);
77 // set currency for CRM-1496
78 if (!isset($pledge->currency
)) {
79 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
82 $result = $pledge->save();
84 CRM_Utils_Hook
::post($hook, 'Pledge', $pledge->id
, $pledge);
90 * Given the list of params in the params array, fetch the object
91 * and store the values in the values array
93 * @param array $params
94 * Input parameters to find object.
95 * @param array $values
96 * Output values of the object.
97 * @param array $returnProperties
98 * If you want to return specific fields.
101 * associated array of field values
103 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
104 if (empty($params)) {
107 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
112 * Takes an associative array and creates a pledge object.
114 * @param array $params
115 * Assoc array of name/value pairs.
117 * @return CRM_Pledge_DAO_Pledge
118 * @throws \CRM_Core_Exception
120 public static function create(array $params): CRM_Pledge_DAO_Pledge
{
121 $action = empty($params['id']) ?
'create' : 'edit';
122 if ($action === 'create') {
124 'currency' => CRM_Core_Config
::singleton()->defaultCurrency
,
125 'installments' => (int) self
::fields()['installments']['default'],
126 'scheduled_date' => $params['start_date'] ??
date('Ymd'),
128 $params = array_merge($defaults, $params);
131 $transaction = new CRM_Core_Transaction();
134 if (!empty($params['installment_amount'])) {
135 $params['amount'] = $params['installment_amount'] * $params['installments'];
138 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
139 if (isset($params['contribution_id'])) {
140 if ($params['installments'] > 1) {
141 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
145 if (!empty($params['id'])) {
146 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
149 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
153 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
155 CRM_Utils_Hook
::pre($action, 'Pledge', $params['id'] ??
NULL, $params);
156 $pledge = new CRM_Pledge_DAO_Pledge();
158 // if pledge is complete update end date as current date
159 if ($pledge->status_id
== 1) {
160 $pledge->end_date
= date('Ymd');
163 $pledge->copyValues($params);
165 CRM_Utils_Hook
::post($action, 'Pledge', $pledge->id
, $pledge);
167 // handle custom data.
168 if (!empty($params['custom']) &&
169 is_array($params['custom'])
171 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
174 // skip payment stuff in edit mode
175 if (empty($params['id']) || self
::isPaymentsRequireRecalculation($params)) {
177 // if pledge is pending delete all payments and recreate.
178 if (!empty(empty($params['id']))) {
179 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
182 // building payment params
183 $paymentParams['pledge_id'] = $pledge->id
;
191 'frequency_interval',
193 'installment_amount',
196 foreach ($paymentKeys as $key) {
197 $paymentParams[$key] = $params[$key] ??
NULL;
199 CRM_Pledge_BAO_PledgePayment
::createMultiple($paymentParams);
202 $transaction->commit();
204 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
205 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
209 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
210 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
211 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
214 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
215 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
216 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
220 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
221 $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) . ')';
223 // add the recently created Pledge
224 CRM_Utils_Recent
::add($title,
237 * Is this a change to an existing pending pledge requiring payment schedule
240 * If the pledge is pending the code (slightly lazily) deletes & recreates
243 * If the payment dates or amounts have been manually edited then this can
244 * cause data loss. We can mitigate this to some extent by making sure we
245 * have a change that could potentially affect the schedule (rather than just
246 * a custom data change or similar).
248 * This calculation needs to be performed before update takes place as
249 * previous & new pledges are compared.
251 * @param array $params
255 protected static function isPaymentsRequireRecalculation($params) {
256 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
259 $scheduleChangingParameters = [
262 'frequency_interval',
267 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
268 $existingPledgeDAO->id
= $params['id'];
269 $existingPledgeDAO->find(TRUE);
270 foreach ($scheduleChangingParameters as $parameter) {
271 if ($parameter == 'start_date') {
272 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
276 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
290 public static function deletePledge($id) {
291 CRM_Utils_Hook
::pre('delete', 'Pledge', $id);
293 $transaction = new CRM_Core_Transaction();
295 // check for no Completed Payment records with the pledge
296 $payment = new CRM_Pledge_DAO_PledgePayment();
297 $payment->pledge_id
= $id;
300 while ($payment->fetch()) {
301 // also delete associated contribution.
302 if ($payment->contribution_id
) {
303 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
308 $dao = new CRM_Pledge_DAO_Pledge();
310 $results = $dao->delete();
312 $transaction->commit();
314 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
316 // delete the recently created Pledge
321 CRM_Utils_Recent
::del($pledgeRecent);
327 * Get the amount details date wise.
329 * @param string $status
330 * @param string $startDate
331 * @param string $endDate
335 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
337 $select = $from = $queryDate = NULL;
338 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
342 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
349 $where[] = 'status_id = ' . $statusId;
354 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
357 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
360 $whereCond = implode(' AND ', $where);
363 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
365 WHERE $whereCond AND is_test=0
368 $start = substr($startDate, 0, 8);
369 $end = substr($endDate, 0, 8);
372 $dao = CRM_Core_DAO
::executeQuery($query);
373 while ($dao->fetch()) {
374 $pCount +
= $dao->pledge_count
;
375 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
379 'pledge_amount' => implode(', ', $pamount),
380 'pledge_count' => $pCount,
381 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
382 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
389 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
390 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
391 $queryDate = 'receive_date';
392 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
396 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
397 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
398 $queryDate = 'receive_date';
399 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
403 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
404 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
405 $queryDate = 'scheduled_date';
406 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
410 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
411 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
412 $queryDate = 'scheduled_date';
413 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
418 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
421 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
424 $whereCond = implode(' AND ', $where);
427 SELECT $select, cp.currency
433 $dao = CRM_Core_DAO
::executeQuery($query);
437 while ($dao->fetch()) {
438 $count +
= $dao->received_count
;
439 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
443 return array_merge($pledge_amount, [
444 'received_amount' => implode(', ', $amount),
445 'received_count' => $count,
446 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
447 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
453 return $pledge_amount;
459 * Get list of pledges In Honor of contact Ids.
461 * @param int $honorId
462 * In Honor of Contact ID.
465 * return the list of pledge fields
467 public static function getHonorContacts($honorId) {
469 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
470 $honorDAO->contact_id
= $honorId;
474 while ($honorDAO->fetch()) {
475 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
476 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
477 if ($pledgePaymentDAO->find(TRUE)) {
478 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
479 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
480 if ($pledgeDAO->find(TRUE)) {
481 $params[$pledgeDAO->id
] = [
482 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
483 'honorId' => $pledgeDAO->contact_id
,
484 'amount' => $pledgeDAO->amount
,
485 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
486 'create_date' => $pledgeDAO->create_date
,
487 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
488 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
489 $pledgeDAO->financial_type_id
, 'name'
491 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
492 $pledgeDAO->contact_id
, 'display_name'
503 * Send Acknowledgment and create activity.
505 * @param CRM_Core_Form $form
507 * @param array $params
508 * An assoc array of name/value pairs.
510 public static function sendAcknowledgment(&$form, $params) {
511 //handle Acknowledgment.
512 $allPayments = $payments = [];
514 // get All Payments status types.
515 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
516 $returnProperties = [
522 // get all paymnets details.
523 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
525 if (!empty($allPayments)) {
526 foreach ($allPayments as $payID => $values) {
527 $contributionValue = $contributionStatus = [];
528 if (isset($values['contribution_id'])) {
529 $contributionParams = ['id' => $values['contribution_id']];
530 $returnProperties = ['contribution_status_id', 'receive_date'];
531 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
532 $contributionParams, $contributionStatus, $returnProperties
534 $contributionValue = [
535 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
536 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
539 $payments[$payID] = array_merge($contributionValue,
541 'amount' => $values['scheduled_amount'] ??
NULL,
542 'due_date' => $values['scheduled_date'] ??
NULL,
546 // get the first valid payment id.
547 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
548 $paymentStatusTypes[$values['status_id']] == 'Overdue'
551 $form->paymentId
= $values['id'];
556 // assign pledge fields value to template.
559 'total_pledge_amount',
560 'frequency_interval',
567 foreach ($pledgeFields as $field) {
568 if (!empty($params[$field])) {
569 $form->assign($field, $params[$field]);
573 // assign all payments details.
575 $form->assign('payments', $payments);
578 // handle domain token values
579 $domain = CRM_Core_BAO_Domain
::getDomain();
581 'domain' => ['name', 'phone', 'address', 'email'],
582 'contact' => CRM_Core_SelectValues
::contactTokens(),
585 foreach ($tokens['domain'] as $token) {
586 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
588 $form->assign('domain', $domainValues);
590 // handle contact token values.
591 $ids = [$params['contact_id']];
592 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
593 ['display_name', 'checksum', 'contact_id']
595 foreach ($fields as $key => $val) {
596 $returnProperties[$val] = TRUE;
598 [$details] = CRM_Utils_Token
::getTokenDetails($ids,
604 $form->assign('contact', $details[$params['contact_id']]);
606 // handle custom data.
607 if (!empty($params['hidden_custom'])) {
608 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
609 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
611 // retrieve custom data
612 foreach ($groupTree as $groupID => $group) {
613 $customFields = $customValues = [];
614 if ($groupID == 'info') {
617 foreach ($group['fields'] as $k => $field) {
618 $field['title'] = $field['label'];
619 $customFields["custom_{$k}"] = $field;
622 // to build array of customgroup & customfields in it
623 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
624 $customGroup[$group['title']] = $customValues;
627 $form->assign('customGroup', $customGroup);
630 // handle acknowledgment email stuff.
631 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
633 // check for online pledge.
634 if (!empty($params['receipt_from_email'])) {
635 $userName = $params['receipt_from_name'] ??
NULL;
636 $userEmail = $params['receipt_from_email'] ??
NULL;
638 elseif (!empty($params['from_email_id'])) {
639 $receiptFrom = $params['from_email_id'];
641 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
642 // check for logged in user.
646 ] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
649 // set the domain values.
650 $userName = $domainValues['name'] ??
NULL;
651 $userEmail = $domainValues['email'] ??
NULL;
654 if (!isset($receiptFrom)) {
655 $receiptFrom = "$userName <$userEmail>";
658 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
660 'groupName' => 'msg_tpl_workflow_pledge',
661 'valueName' => 'pledge_acknowledge',
662 'contactId' => $params['contact_id'],
663 'from' => $receiptFrom,
664 'toName' => $pledgerDisplayName,
665 'toEmail' => $pledgerEmail,
669 // check if activity record exist for this pledge
670 // Acknowledgment, if exist do not add activity.
671 $activityType = 'Pledge Acknowledgment';
672 $activity = new CRM_Activity_DAO_Activity();
673 $activity->source_record_id
= $params['id'];
674 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
680 $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)';
682 if (!$activity->find()) {
684 'subject' => $subject,
685 'source_contact_id' => $params['contact_id'],
686 'source_record_id' => $params['id'],
687 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
691 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
692 'is_test' => $params['is_test'],
694 'details' => $details,
695 'campaign_id' => $params['campaign_id'] ??
NULL,
698 // lets insert assignee record.
699 if (!empty($params['contact_id'])) {
700 $activityParams['assignee_contact_id'] = $params['contact_id'];
703 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
704 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
710 * Combine all the exportable fields from the lower levels object.
712 * @param bool $checkPermission
715 * array of exportable Fields
717 public static function exportableFields($checkPermission = TRUE) {
718 if (!self
::$_exportableFields) {
719 if (!self
::$_exportableFields) {
720 self
::$_exportableFields = [];
723 $fields = CRM_Pledge_DAO_Pledge
::export();
725 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
727 // set title to calculated fields
728 $calculatedFields = [
729 'pledge_total_paid' => ['title' => ts('Total Paid')],
730 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
731 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
732 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
733 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
734 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
735 'pledge_payment_status' => [
736 'title' => ts('Pledge Payment Status'),
737 'name' => 'pledge_payment_status',
738 'data_type' => CRM_Utils_Type
::T_STRING
,
744 'title' => ts('Pledge Status'),
745 'name' => 'pledge_status',
746 'data_type' => CRM_Utils_Type
::T_STRING
,
748 'pledge_frequency_unit' => [
749 'title' => ts('Pledge Frequency Unit'),
750 'name' => 'pledge_frequency_unit',
751 'data_type' => CRM_Utils_Type
::T_ENUM
,
753 'pledge_frequency_interval' => [
754 'title' => ts('Pledge Frequency Interval'),
755 'name' => 'pledge_frequency_interval',
756 'data_type' => CRM_Utils_Type
::T_INT
,
758 'pledge_contribution_page_id' => [
759 'title' => ts('Pledge Contribution Page Id'),
760 'name' => 'pledge_contribution_page_id',
761 'data_type' => CRM_Utils_Type
::T_INT
,
765 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
768 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
769 self
::$_exportableFields = $fields;
772 return self
::$_exportableFields;
776 * Get pending or in progress pledges.
778 * @param int $contactID
782 * associated array of pledge id(s)
784 public static function getContactPledges($contactID) {
786 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
787 FALSE, FALSE, FALSE, NULL, 'name'
792 // get pending and in progress status
793 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
794 if ($statusId = array_search($name, $pledgeStatuses)) {
795 $status[] = $statusId;
798 if (empty($status)) {
799 return $pledgeDetails;
802 $statusClause = " IN (" . implode(',', $status) . ")";
805 SELECT civicrm_pledge.id id
807 WHERE civicrm_pledge.status_id {$statusClause}
808 AND civicrm_pledge.contact_id = %1
811 $params[1] = [$contactID, 'Integer'];
812 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
814 while ($pledge->fetch()) {
815 $pledgeDetails[] = $pledge->id
;
818 return $pledgeDetails;
822 * Get pledge record count for a Contact.
824 * @param int $contactID
827 * count of pledge records
829 public static function getContactPledgeCount($contactID) {
830 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
831 return CRM_Core_DAO
::singleValueQuery($query);
835 * @param array $params
839 public static function updatePledgeStatus($params) {
841 $returnMessages = [];
843 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
845 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
846 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
847 TRUE, FALSE, FALSE, NULL, 'name', TRUE
849 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
850 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
852 $statusIds = implode(',', $allStatus);
853 $pledgeStatusIds = implode(',', $allPledgeStatus);
857 SELECT pledge.contact_id as contact_id,
858 pledge.id as pledge_id,
859 pledge.amount as amount,
860 payment.scheduled_date as scheduled_date,
861 pledge.create_date as create_date,
862 payment.id as payment_id,
863 pledge.currency as currency,
864 pledge.contribution_page_id as contribution_page_id,
865 payment.reminder_count as reminder_count,
866 pledge.max_reminders as max_reminders,
867 payment.reminder_date as reminder_date,
868 pledge.initial_reminder_day as initial_reminder_day,
869 pledge.additional_reminder_day as additional_reminder_day,
870 pledge.status_id as pledge_status,
871 payment.status_id as payment_status,
872 pledge.is_test as is_test,
873 pledge.campaign_id as campaign_id,
874 SUM(payment.scheduled_amount) as amount_due,
875 ( SELECT sum(civicrm_pledge_payment.actual_amount)
876 FROM civicrm_pledge_payment
877 WHERE civicrm_pledge_payment.status_id = 1
878 AND civicrm_pledge_payment.pledge_id = pledge.id
880 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
881 WHERE pledge.id = payment.pledge_id
882 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
886 $dao = CRM_Core_DAO
::executeQuery($query);
889 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
890 while ($dao->fetch()) {
891 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
893 $pledgeDetails[$dao->payment_id
] = [
894 'scheduled_date' => $dao->scheduled_date
,
895 'amount_due' => $dao->amount_due
,
896 'amount' => $dao->amount
,
897 'amount_paid' => $dao->amount_paid
,
898 'create_date' => $dao->create_date
,
899 'contact_id' => $dao->contact_id
,
900 'pledge_id' => $dao->pledge_id
,
901 'checksumValue' => $checksumValue,
902 'contribution_page_id' => $dao->contribution_page_id
,
903 'reminder_count' => $dao->reminder_count
,
904 'max_reminders' => $dao->max_reminders
,
905 'reminder_date' => $dao->reminder_date
,
906 'initial_reminder_day' => $dao->initial_reminder_day
,
907 'additional_reminder_day' => $dao->additional_reminder_day
,
908 'pledge_status' => $dao->pledge_status
,
909 'payment_status' => $dao->payment_status
,
910 'is_test' => $dao->is_test
,
911 'currency' => $dao->currency
,
912 'campaign_id' => $dao->campaign_id
,
915 $contactIds[$dao->contact_id
] = $dao->contact_id
;
916 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
918 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
920 ) && $dao->payment_status
!= $allStatus['Overdue']
922 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
925 $allPledgeStatus = array_flip($allPledgeStatus);
927 // process the updating script...
928 foreach ($pledgePayments as $pledgeId => $paymentIds) {
929 // 1. update the pledge /pledge payment status. returns new status when an update happens
930 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
932 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
933 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
935 if ($newStatus != $pledgeStatus[$pledgeId]) {
936 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
941 if ($sendReminders) {
942 // retrieve domain tokens
943 $domain = CRM_Core_BAO_Domain
::getDomain();
945 'domain' => ['name', 'phone', 'address', 'email'],
946 'contact' => CRM_Core_SelectValues
::contactTokens(),
950 foreach ($tokens['domain'] as $token) {
951 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
954 // get the domain email address, since we don't carry w/ object.
955 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
956 $domainValues['email'] = $domainValue[1];
958 // retrieve contact tokens
960 // this function does NOT return Deceased contacts since we don't want to send them email
961 [$contactDetails] = CRM_Utils_Token
::getTokenDetails($contactIds,
964 $tokens, 'CRM_UpdatePledgeRecord'
967 // assign domain values to template
968 $template = CRM_Core_Smarty
::singleton();
969 $template->assign('domain', $domainValues);
972 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
974 foreach ($pledgeDetails as $paymentId => $details) {
975 if (array_key_exists($details['contact_id'], $contactDetails)) {
976 $contactId = $details['contact_id'];
977 $pledgerName = $contactDetails[$contactId]['display_name'];
983 if (empty($details['reminder_date'])) {
984 $nextReminderDate = new DateTime($details['scheduled_date']);
985 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
986 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
987 $nextReminderDate = $nextReminderDate->format("Ymd");
990 $nextReminderDate = new DateTime($details['reminder_date']);
991 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
992 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
993 $nextReminderDate = $nextReminderDate->format("Ymd");
995 if (($details['reminder_count'] < $details['max_reminders'])
996 && ($nextReminderDate <= $now)
999 $toEmail = $doNotEmail = $onHold = NULL;
1001 if (!empty($contactDetails[$contactId]['email'])) {
1002 $toEmail = $contactDetails[$contactId]['email'];
1005 if (!empty($contactDetails[$contactId]['do_not_email'])) {
1006 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
1009 if (!empty($contactDetails[$contactId]['on_hold'])) {
1010 $onHold = $contactDetails[$contactId]['on_hold'];
1013 // 2. send acknowledgement mail
1014 if ($toEmail && !($doNotEmail ||
$onHold)) {
1015 // assign value to template
1016 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1017 $template->assign('contact', $contactDetails[$contactId]);
1018 $template->assign('next_payment', $details['scheduled_date']);
1019 $template->assign('amount_due', $details['amount_due']);
1020 $template->assign('checksumValue', $details['checksumValue']);
1021 $template->assign('contribution_page_id', $details['contribution_page_id']);
1022 $template->assign('pledge_id', $details['pledge_id']);
1023 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1024 $template->assign('amount', $details['amount']);
1025 $template->assign('create_date', $details['create_date']);
1026 $template->assign('currency', $details['currency']);
1032 ] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1034 'groupName' => 'msg_tpl_workflow_pledge',
1035 'valueName' => 'pledge_reminder',
1036 'contactId' => $contactId,
1037 'from' => $receiptFrom,
1038 'toName' => $pledgerName,
1039 'toEmail' => $toEmail,
1043 // 3. update pledge payment details
1045 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1046 $activityType = 'Pledge Reminder';
1048 'subject' => $subject,
1049 'source_contact_id' => $contactId,
1050 'source_record_id' => $paymentId,
1051 'assignee_contact_id' => $contactId,
1052 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
1056 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1057 'is_test' => $details['is_test'],
1059 'campaign_id' => $details['campaign_id'],
1062 civicrm_api3('activity', 'create', $activityParams);
1064 catch (CiviCRM_API3_Exception
$e) {
1065 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1066 return ['is_error' => 1, 'message' => $returnMessages];
1068 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1073 // end foreach on $pledgeDetails
1075 // end if ( $sendReminders )
1076 $returnMessages[] = "{$updateCnt} records updated.";
1078 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1082 * Mark a pledge (and any outstanding payments) as cancelled.
1084 * @param int $pledgeID
1086 public static function cancel($pledgeID) {
1087 $paymentIDs = self
::findCancelablePayments($pledgeID);
1088 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1089 $cancelled = array_search('Cancelled', $status);
1090 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1091 $cancelled, 0, FALSE, TRUE
1096 * Find payments which can be safely canceled.
1098 * @param int $pledgeID
1101 * Array of int (civicrm_pledge_payment.id)
1103 public static function findCancelablePayments($pledgeID) {
1104 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1106 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1107 $paymentDAO->pledge_id
= $pledgeID;
1108 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1109 $statuses['Overdue'],
1110 $statuses['Pending']
1112 $paymentDAO->find();
1115 while ($paymentDAO->fetch()) {
1116 $paymentIDs[] = $paymentDAO->id
;
1122 * Is this pledge free from financial transactions (this is important to know
1123 * as we allow editing when no transactions have taken place - the editing
1124 * process currently involves deleting all pledge payments & contributions
1125 * & recreating so we want to block that if appropriate).
1127 * @param int $pledgeID
1128 * @param int $pledgeStatusID
1131 * do financial transactions exist for this pledge?
1133 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1134 if (empty($pledgeStatusID)) {
1135 // why would this happen? If we can see where it does then we can see if we should look it up.
1136 // but assuming from form code it CAN be empty.
1139 if (self
::isTransactedStatus($pledgeStatusID)) {
1143 return civicrm_api3('pledge_payment', 'getcount', [
1144 'pledge_id' => $pledgeID,
1145 'contribution_id' => ['IS NOT NULL' => TRUE],
1150 * Does this pledge / pledge payment status mean that a financial transaction
1153 * @param int $statusID
1157 * is it a transactional status?
1159 protected static function isTransactedStatus($statusID) {
1160 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1167 * Get array of non transactional statuses.
1170 * non transactional status ids
1172 protected static function getNonTransactionalStatus() {
1173 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1174 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1178 * Create array for recur record for pledge.
1181 * params for recur record
1183 public static function buildRecurParams($params) {
1186 'auto_renew' => TRUE,
1187 'frequency_unit' => $params['pledge_frequency_unit'],
1188 'frequency_interval' => $params['pledge_frequency_interval'],
1189 'installments' => $params['pledge_installments'],
1190 'start_date' => $params['receive_date'],
1192 return $recurParams;
1196 * Get pledge start date.
1201 public static function getPledgeStartDate($date, $pledgeBlock) {
1202 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1203 foreach ($startDate as $field => $value) {
1204 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1211 case 'contribution_date':
1213 $date = date('Ymd');
1217 case 'calendar_date':
1218 $date = date('Ymd', strtotime($date));
1221 case 'calendar_month':
1222 $date = self
::getPaymentDate($date);
1223 $date = date('Ymd', strtotime($date));
1235 * Get first payment date for pledge.
1239 * @return bool|string
1241 public static function getPaymentDate($day) {
1243 // Find out if current month has 31 days, if not, set it to 30 (last day).
1249 $current = date('d');
1251 case ($day == $current):
1252 $date = date('m/d/Y');
1255 case ($day > $current):
1256 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1259 case ($day < $current):
1260 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1271 * Override buildOptions to hack out some statuses.
1273 * @param string $fieldName
1274 * @param string $context
1275 * @param array $props
1277 * @return array|bool
1278 * @todo instead of using & hacking the shared optionGroup
1279 * contribution_status use a separate one.
1282 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1283 $result = parent
::buildOptions($fieldName, $context, $props);
1284 if ($fieldName == 'status_id') {
1285 $result = array_diff($result, ['Failed']);