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.
64 public static function add(&$params) {
65 if (!empty($params['id'])) {
66 CRM_Utils_Hook
::pre('edit', 'Pledge', $params['id'], $params);
69 CRM_Utils_Hook
::pre('create', 'Pledge', NULL, $params);
72 $pledge = new CRM_Pledge_DAO_Pledge();
74 // if pledge is complete update end date as current date
75 if ($pledge->status_id
== 1) {
76 $pledge->end_date
= date('Ymd');
79 $pledge->copyValues($params);
81 // set currency for CRM-1496
82 if (!isset($pledge->currency
)) {
83 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
86 $result = $pledge->save();
88 if (!empty($params['id'])) {
89 CRM_Utils_Hook
::post('edit', 'Pledge', $pledge->id
, $pledge);
92 CRM_Utils_Hook
::post('create', 'Pledge', $pledge->id
, $pledge);
99 * Given the list of params in the params array, fetch the object
100 * and store the values in the values array
102 * @param array $params
103 * Input parameters to find object.
104 * @param array $values
105 * Output values of the object.
106 * @param array $returnProperties
107 * If you want to return specific fields.
110 * associated array of field values
112 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
113 if (empty($params)) {
116 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
121 * Takes an associative array and creates a pledge object.
123 * @param array $params
124 * (reference ) an assoc array of name/value pairs.
126 * @return CRM_Pledge_BAO_Pledge
128 public static function create(&$params) {
129 // FIXME: a cludgy hack to fix the dates to MySQL format
130 $dateFields = array('start_date', 'create_date', 'acknowledge_date', 'modified_date', 'cancel_date', 'end_date');
131 foreach ($dateFields as $df) {
132 if (isset($params[$df])) {
133 $params[$df] = CRM_Utils_Date
::isoToMysql($params[$df]);
137 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
138 $transaction = new CRM_Core_Transaction();
141 if (!empty($params['installment_amount'])) {
142 $params['amount'] = $params['installment_amount'] * $params['installments'];
145 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
146 if (isset($params['contribution_id'])) {
147 if ($params['installments'] > 1) {
148 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
152 if (!empty($params['id'])) {
153 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
156 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
160 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
162 $pledge = self
::add($params);
163 if (is_a($pledge, 'CRM_Core_Error')) {
168 // handle custom data.
169 if (!empty($params['custom']) &&
170 is_array($params['custom'])
172 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
175 // skip payment stuff inedit mode
176 if (!isset($params['id']) ||
$isRecalculatePledgePayment) {
178 // if pledge is pending delete all payments and recreate.
179 if ($isRecalculatePledgePayment) {
180 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
183 // building payment params
184 $paymentParams['pledge_id'] = $pledge->id
;
185 $paymentKeys = array(
192 'frequency_interval',
194 'installment_amount',
197 foreach ($paymentKeys as $key) {
198 $paymentParams[$key] = $params[$key] ??
NULL;
200 CRM_Pledge_BAO_PledgePayment
::create($paymentParams);
203 $transaction->commit();
205 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
206 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
210 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
211 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
212 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
215 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
216 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
217 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
221 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
222 $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) . ')';
224 // add the recently created Pledge
225 CRM_Utils_Recent
::add($title,
238 * Is this a change to an existing pending pledge requiring payment schedule changes.
240 * If the pledge is pending the code (slightly lazily) deletes & recreates pledge payments.
242 * If the payment dates or amounts have been manually edited then this can cause data loss. We can mitigate this to
243 * some extent by making sure we have a change that could potentially affect the schedule (rather than just a
244 * custom data change or similar).
246 * This calculation needs to be performed before update takes place as previous & new pledges are compared.
248 * @param array $params
252 protected static function isPaymentsRequireRecalculation($params) {
253 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
256 $scheduleChangingParameters = array(
259 'frequency_interval',
264 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
265 $existingPledgeDAO->id
= $params['id'];
266 $existingPledgeDAO->find(TRUE);
267 foreach ($scheduleChangingParameters as $parameter) {
268 if ($parameter == 'start_date') {
269 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
273 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
287 public static function deletePledge($id) {
288 CRM_Utils_Hook
::pre('delete', 'Pledge', $id, CRM_Core_DAO
::$_nullArray);
290 $transaction = new CRM_Core_Transaction();
292 // check for no Completed Payment records with the pledge
293 $payment = new CRM_Pledge_DAO_PledgePayment();
294 $payment->pledge_id
= $id;
297 while ($payment->fetch()) {
298 // also delete associated contribution.
299 if ($payment->contribution_id
) {
300 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
305 $dao = new CRM_Pledge_DAO_Pledge();
307 $results = $dao->delete();
309 $transaction->commit();
311 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
313 // delete the recently created Pledge
314 $pledgeRecent = array(
318 CRM_Utils_Recent
::del($pledgeRecent);
324 * Get the amount details date wise.
326 * @param string $status
327 * @param string $startDate
328 * @param string $endDate
332 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
334 $select = $from = $queryDate = NULL;
335 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
339 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
346 $where[] = 'status_id = ' . $statusId;
351 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
354 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
357 $whereCond = implode(' AND ', $where);
360 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
362 WHERE $whereCond AND is_test=0
365 $start = substr($startDate, 0, 8);
366 $end = substr($endDate, 0, 8);
369 $dao = CRM_Core_DAO
::executeQuery($query);
370 while ($dao->fetch()) {
371 $pCount +
= $dao->pledge_count
;
372 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
375 $pledge_amount = array(
376 'pledge_amount' => implode(', ', $pamount),
377 'pledge_count' => $pCount,
378 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
379 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
386 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
387 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
388 $queryDate = 'receive_date';
389 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
393 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
394 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
395 $queryDate = 'receive_date';
396 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
400 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
401 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
402 $queryDate = 'scheduled_date';
403 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
407 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
408 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
409 $queryDate = 'scheduled_date';
410 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
415 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
418 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
421 $whereCond = implode(' AND ', $where);
424 SELECT $select, cp.currency
430 $dao = CRM_Core_DAO
::executeQuery($query);
434 while ($dao->fetch()) {
435 $count +
= $dao->received_count
;
436 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
440 return array_merge($pledge_amount, array(
441 'received_amount' => implode(', ', $amount),
442 'received_count' => $count,
443 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
444 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
450 return $pledge_amount;
456 * Get list of pledges In Honor of contact Ids.
458 * @param int $honorId
459 * In Honor of Contact ID.
462 * return the list of pledge fields
464 public static function getHonorContacts($honorId) {
466 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
467 $honorDAO->contact_id
= $honorId;
471 while ($honorDAO->fetch()) {
472 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
473 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
474 if ($pledgePaymentDAO->find(TRUE)) {
475 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
476 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
477 if ($pledgeDAO->find(TRUE)) {
478 $params[$pledgeDAO->id
] = array(
479 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
480 'honorId' => $pledgeDAO->contact_id
,
481 'amount' => $pledgeDAO->amount
,
482 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
483 'create_date' => $pledgeDAO->create_date
,
484 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
485 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
486 $pledgeDAO->financial_type_id
, 'name'
488 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
489 $pledgeDAO->contact_id
, 'display_name'
500 * Send Acknowledgment and create activity.
502 * @param CRM_Core_Form $form
504 * @param array $params
505 * An assoc array of name/value pairs.
507 public static function sendAcknowledgment(&$form, $params) {
508 //handle Acknowledgment.
509 $allPayments = $payments = [];
511 // get All Payments status types.
512 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
513 $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
514 // get all paymnets details.
515 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
517 if (!empty($allPayments)) {
518 foreach ($allPayments as $payID => $values) {
519 $contributionValue = $contributionStatus = [];
520 if (isset($values['contribution_id'])) {
521 $contributionParams = array('id' => $values['contribution_id']);
522 $returnProperties = array('contribution_status_id', 'receive_date');
523 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
524 $contributionParams, $contributionStatus, $returnProperties
526 $contributionValue = array(
527 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
528 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
531 $payments[$payID] = array_merge($contributionValue,
533 'amount' => $values['scheduled_amount'] ??
NULL,
534 'due_date' => $values['scheduled_date'] ??
NULL,
538 // get the first valid payment id.
539 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
540 $paymentStatusTypes[$values['status_id']] == 'Overdue'
543 $form->paymentId
= $values['id'];
548 // assign pledge fields value to template.
549 $pledgeFields = array(
551 'total_pledge_amount',
552 'frequency_interval',
559 foreach ($pledgeFields as $field) {
560 if (!empty($params[$field])) {
561 $form->assign($field, $params[$field]);
565 // assign all payments details.
567 $form->assign('payments', $payments);
570 // handle domain token values
571 $domain = CRM_Core_BAO_Domain
::getDomain();
573 'domain' => array('name', 'phone', 'address', 'email'),
574 'contact' => CRM_Core_SelectValues
::contactTokens(),
577 foreach ($tokens['domain'] as $token) {
578 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
580 $form->assign('domain', $domainValues);
582 // handle contact token values.
583 $ids = array($params['contact_id']);
584 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::importableFields()),
585 array('display_name', 'checksum', 'contact_id')
587 foreach ($fields as $key => $val) {
588 $returnProperties[$val] = TRUE;
590 $details = CRM_Utils_Token
::getTokenDetails($ids,
596 $form->assign('contact', $details[0][$params['contact_id']]);
598 // handle custom data.
599 if (!empty($params['hidden_custom'])) {
600 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
601 $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
603 // retrieve custom data
604 foreach ($groupTree as $groupID => $group) {
605 $customFields = $customValues = [];
606 if ($groupID == 'info') {
609 foreach ($group['fields'] as $k => $field) {
610 $field['title'] = $field['label'];
611 $customFields["custom_{$k}"] = $field;
614 // to build array of customgroup & customfields in it
615 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
616 $customGroup[$group['title']] = $customValues;
619 $form->assign('customGroup', $customGroup);
622 // handle acknowledgment email stuff.
623 list($pledgerDisplayName,
625 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
627 // check for online pledge.
628 if (!empty($params['receipt_from_email'])) {
629 $userName = $params['receipt_from_name'] ??
NULL;
630 $userEmail = $params['receipt_from_email'] ??
NULL;
632 elseif (!empty($params['from_email_id'])) {
633 $receiptFrom = $params['from_email_id'];
635 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
636 // check for logged in user.
637 list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
640 // set the domain values.
641 $userName = $domainValues['name'] ??
NULL;
642 $userEmail = $domainValues['email'] ??
NULL;
645 if (!isset($receiptFrom)) {
646 $receiptFrom = "$userName <$userEmail>";
649 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
651 'groupName' => 'msg_tpl_workflow_pledge',
652 'valueName' => 'pledge_acknowledge',
653 'contactId' => $params['contact_id'],
654 'from' => $receiptFrom,
655 'toName' => $pledgerDisplayName,
656 'toEmail' => $pledgerEmail,
660 // check if activity record exist for this pledge
661 // Acknowledgment, if exist do not add activity.
662 $activityType = 'Pledge Acknowledgment';
663 $activity = new CRM_Activity_DAO_Activity();
664 $activity->source_record_id
= $params['id'];
665 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
671 $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)';
673 if (!$activity->find()) {
674 $activityParams = array(
675 'subject' => $subject,
676 'source_contact_id' => $params['contact_id'],
677 'source_record_id' => $params['id'],
678 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
682 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
683 'is_test' => $params['is_test'],
685 'details' => $details,
686 'campaign_id' => $params['campaign_id'] ??
NULL,
689 // lets insert assignee record.
690 if (!empty($params['contact_id'])) {
691 $activityParams['assignee_contact_id'] = $params['contact_id'];
694 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
695 CRM_Core_Error
::fatal("Failed creating Activity for acknowledgment");
701 * Combine all the exportable fields from the lower levels object.
703 * @param bool $checkPermission
706 * array of exportable Fields
708 public static function exportableFields($checkPermission = TRUE) {
709 if (!self
::$_exportableFields) {
710 if (!self
::$_exportableFields) {
711 self
::$_exportableFields = [];
714 $fields = CRM_Pledge_DAO_Pledge
::export();
716 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
718 // set title to calculated fields
719 $calculatedFields = array(
720 'pledge_total_paid' => array('title' => ts('Total Paid')),
721 'pledge_balance_amount' => array('title' => ts('Balance Amount')),
722 'pledge_next_pay_date' => array('title' => ts('Next Payment Date')),
723 'pledge_next_pay_amount' => array('title' => ts('Next Payment Amount')),
724 'pledge_payment_paid_amount' => array('title' => ts('Paid Amount')),
725 'pledge_payment_paid_date' => array('title' => ts('Paid Date')),
726 'pledge_payment_status' => array(
727 'title' => ts('Pledge Payment Status'),
728 'name' => 'pledge_payment_status',
729 'data_type' => CRM_Utils_Type
::T_STRING
,
733 $pledgeFields = array(
734 'pledge_status' => array(
735 'title' => ts('Pledge Status'),
736 'name' => 'pledge_status',
737 'data_type' => CRM_Utils_Type
::T_STRING
,
739 'pledge_frequency_unit' => array(
740 'title' => ts('Pledge Frequency Unit'),
741 'name' => 'pledge_frequency_unit',
742 'data_type' => CRM_Utils_Type
::T_ENUM
,
744 'pledge_frequency_interval' => array(
745 'title' => ts('Pledge Frequency Interval'),
746 'name' => 'pledge_frequency_interval',
747 'data_type' => CRM_Utils_Type
::T_INT
,
749 'pledge_contribution_page_id' => array(
750 'title' => ts('Pledge Contribution Page Id'),
751 'name' => 'pledge_contribution_page_id',
752 'data_type' => CRM_Utils_Type
::T_INT
,
756 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
759 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
760 self
::$_exportableFields = $fields;
763 return self
::$_exportableFields;
767 * Get pending or in progress pledges.
769 * @param int $contactID
773 * associated array of pledge id(s)
775 public static function getContactPledges($contactID) {
777 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
778 FALSE, FALSE, FALSE, NULL, 'name'
783 // get pending and in progress status
789 if ($statusId = array_search($name, $pledgeStatuses)) {
790 $status[] = $statusId;
793 if (empty($status)) {
794 return $pledgeDetails;
797 $statusClause = " IN (" . implode(',', $status) . ")";
800 SELECT civicrm_pledge.id id
802 WHERE civicrm_pledge.status_id {$statusClause}
803 AND civicrm_pledge.contact_id = %1
806 $params[1] = array($contactID, 'Integer');
807 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
809 while ($pledge->fetch()) {
810 $pledgeDetails[] = $pledge->id
;
813 return $pledgeDetails;
817 * Get pledge record count for a Contact.
819 * @param int $contactID
822 * count of pledge records
824 public static function getContactPledgeCount($contactID) {
825 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
826 return CRM_Core_DAO
::singleValueQuery($query);
830 * @param array $params
834 public static function updatePledgeStatus($params) {
836 $returnMessages = [];
838 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
840 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
841 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
842 TRUE, FALSE, FALSE, NULL, 'name', TRUE
844 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
845 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
847 $statusIds = implode(',', $allStatus);
848 $pledgeStatusIds = implode(',', $allPledgeStatus);
852 SELECT pledge.contact_id as contact_id,
853 pledge.id as pledge_id,
854 pledge.amount as amount,
855 payment.scheduled_date as scheduled_date,
856 pledge.create_date as create_date,
857 payment.id as payment_id,
858 pledge.currency as currency,
859 pledge.contribution_page_id as contribution_page_id,
860 payment.reminder_count as reminder_count,
861 pledge.max_reminders as max_reminders,
862 payment.reminder_date as reminder_date,
863 pledge.initial_reminder_day as initial_reminder_day,
864 pledge.additional_reminder_day as additional_reminder_day,
865 pledge.status_id as pledge_status,
866 payment.status_id as payment_status,
867 pledge.is_test as is_test,
868 pledge.campaign_id as campaign_id,
869 SUM(payment.scheduled_amount) as amount_due,
870 ( SELECT sum(civicrm_pledge_payment.actual_amount)
871 FROM civicrm_pledge_payment
872 WHERE civicrm_pledge_payment.status_id = 1
873 AND civicrm_pledge_payment.pledge_id = pledge.id
875 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
876 WHERE pledge.id = payment.pledge_id
877 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
881 $dao = CRM_Core_DAO
::executeQuery($query);
884 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
885 while ($dao->fetch()) {
886 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
888 $pledgeDetails[$dao->payment_id
] = array(
889 'scheduled_date' => $dao->scheduled_date
,
890 'amount_due' => $dao->amount_due
,
891 'amount' => $dao->amount
,
892 'amount_paid' => $dao->amount_paid
,
893 'create_date' => $dao->create_date
,
894 'contact_id' => $dao->contact_id
,
895 'pledge_id' => $dao->pledge_id
,
896 'checksumValue' => $checksumValue,
897 'contribution_page_id' => $dao->contribution_page_id
,
898 'reminder_count' => $dao->reminder_count
,
899 'max_reminders' => $dao->max_reminders
,
900 'reminder_date' => $dao->reminder_date
,
901 'initial_reminder_day' => $dao->initial_reminder_day
,
902 'additional_reminder_day' => $dao->additional_reminder_day
,
903 'pledge_status' => $dao->pledge_status
,
904 'payment_status' => $dao->payment_status
,
905 'is_test' => $dao->is_test
,
906 'currency' => $dao->currency
,
907 'campaign_id' => $dao->campaign_id
,
910 $contactIds[$dao->contact_id
] = $dao->contact_id
;
911 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
913 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
915 ) && $dao->payment_status
!= $allStatus['Overdue']
917 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
920 $allPledgeStatus = array_flip($allPledgeStatus);
922 // process the updating script...
923 foreach ($pledgePayments as $pledgeId => $paymentIds) {
924 // 1. update the pledge /pledge payment status. returns new status when an update happens
925 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
927 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
928 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
930 if ($newStatus != $pledgeStatus[$pledgeId]) {
931 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
936 if ($sendReminders) {
937 // retrieve domain tokens
938 $domain = CRM_Core_BAO_Domain
::getDomain();
940 'domain' => array('name', 'phone', 'address', 'email'),
941 'contact' => CRM_Core_SelectValues
::contactTokens(),
945 foreach ($tokens['domain'] as $token) {
946 $domainValues[$token] = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain);
949 // get the domain email address, since we don't carry w/ object.
950 $domainValue = CRM_Core_BAO_Domain
::getNameAndEmail();
951 $domainValues['email'] = $domainValue[1];
953 // retrieve contact tokens
955 // this function does NOT return Deceased contacts since we don't want to send them email
956 list($contactDetails) = CRM_Utils_Token
::getTokenDetails($contactIds,
959 $tokens, 'CRM_UpdatePledgeRecord'
962 // assign domain values to template
963 $template = CRM_Core_Smarty
::singleton();
964 $template->assign('domain', $domainValues);
967 $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
969 foreach ($pledgeDetails as $paymentId => $details) {
970 if (array_key_exists($details['contact_id'], $contactDetails)) {
971 $contactId = $details['contact_id'];
972 $pledgerName = $contactDetails[$contactId]['display_name'];
978 if (empty($details['reminder_date'])) {
979 $nextReminderDate = new DateTime($details['scheduled_date']);
980 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
981 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
982 $nextReminderDate = $nextReminderDate->format("Ymd");
985 $nextReminderDate = new DateTime($details['reminder_date']);
986 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
987 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
988 $nextReminderDate = $nextReminderDate->format("Ymd");
990 if (($details['reminder_count'] < $details['max_reminders'])
991 && ($nextReminderDate <= $now)
994 $toEmail = $doNotEmail = $onHold = NULL;
996 if (!empty($contactDetails[$contactId]['email'])) {
997 $toEmail = $contactDetails[$contactId]['email'];
1000 if (!empty($contactDetails[$contactId]['do_not_email'])) {
1001 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
1004 if (!empty($contactDetails[$contactId]['on_hold'])) {
1005 $onHold = $contactDetails[$contactId]['on_hold'];
1008 // 2. send acknowledgement mail
1009 if ($toEmail && !($doNotEmail ||
$onHold)) {
1010 // assign value to template
1011 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
1012 $template->assign('contact', $contactDetails[$contactId]);
1013 $template->assign('next_payment', $details['scheduled_date']);
1014 $template->assign('amount_due', $details['amount_due']);
1015 $template->assign('checksumValue', $details['checksumValue']);
1016 $template->assign('contribution_page_id', $details['contribution_page_id']);
1017 $template->assign('pledge_id', $details['pledge_id']);
1018 $template->assign('scheduled_payment_date', $details['scheduled_date']);
1019 $template->assign('amount', $details['amount']);
1020 $template->assign('create_date', $details['create_date']);
1021 $template->assign('currency', $details['currency']);
1022 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1024 'groupName' => 'msg_tpl_workflow_pledge',
1025 'valueName' => 'pledge_reminder',
1026 'contactId' => $contactId,
1027 'from' => $receiptFrom,
1028 'toName' => $pledgerName,
1029 'toEmail' => $toEmail,
1033 // 3. update pledge payment details
1035 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
1036 $activityType = 'Pledge Reminder';
1037 $activityParams = array(
1038 'subject' => $subject,
1039 'source_contact_id' => $contactId,
1040 'source_record_id' => $paymentId,
1041 'assignee_contact_id' => $contactId,
1042 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
1046 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1047 'is_test' => $details['is_test'],
1049 'campaign_id' => $details['campaign_id'],
1052 civicrm_api3('activity', 'create', $activityParams);
1054 catch (CiviCRM_API3_Exception
$e) {
1055 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1056 return array('is_error' => 1, 'message' => $returnMessages);
1058 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1063 // end foreach on $pledgeDetails
1065 // end if ( $sendReminders )
1066 $returnMessages[] = "{$updateCnt} records updated.";
1068 return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
1072 * Mark a pledge (and any outstanding payments) as cancelled.
1074 * @param int $pledgeID
1076 public static function cancel($pledgeID) {
1077 $paymentIDs = self
::findCancelablePayments($pledgeID);
1078 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1079 $cancelled = array_search('Cancelled', $status);
1080 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1081 $cancelled, 0, FALSE, TRUE
1086 * Find payments which can be safely canceled.
1088 * @param int $pledgeID
1090 * Array of int (civicrm_pledge_payment.id)
1092 public static function findCancelablePayments($pledgeID) {
1093 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1095 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1096 $paymentDAO->pledge_id
= $pledgeID;
1097 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1098 $statuses['Overdue'],
1099 $statuses['Pending']
1101 $paymentDAO->find();
1104 while ($paymentDAO->fetch()) {
1105 $paymentIDs[] = $paymentDAO->id
;
1111 * Is this pledge free from financial transactions (this is important to know as we allow editing
1112 * when no transactions have taken place - the editing process currently involves deleting all pledge payments & contributions
1113 * & recreating so we want to block that if appropriate).
1115 * @param int $pledgeID
1116 * @param int $pledgeStatusID
1118 * do financial transactions exist for this pledge?
1120 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1121 if (empty($pledgeStatusID)) {
1122 // why would this happen? If we can see where it does then we can see if we should look it up.
1123 // but assuming from form code it CAN be empty.
1126 if (self
::isTransactedStatus($pledgeStatusID)) {
1130 return civicrm_api3('pledge_payment', 'getcount', array(
1131 'pledge_id' => $pledgeID,
1132 'contribution_id' => array('IS NOT NULL' => TRUE),
1137 * Does this pledge / pledge payment status mean that a financial transaction has taken place?
1138 * @param int $statusID
1142 * is it a transactional status?
1144 protected static function isTransactedStatus($statusID) {
1145 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1152 * Get array of non transactional statuses.
1154 * non transactional status ids
1156 protected static function getNonTransactionalStatus() {
1157 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1158 return array_flip(array_intersect($paymentStatus, array('Overdue', 'Pending')));
1162 * Create array for recur record for pledge.
1164 * params for recur record
1166 public static function buildRecurParams($params) {
1167 $recurParams = array(
1169 'auto_renew' => TRUE,
1170 'frequency_unit' => $params['pledge_frequency_unit'],
1171 'frequency_interval' => $params['pledge_frequency_interval'],
1172 'installments' => $params['pledge_installments'],
1173 'start_date' => $params['receive_date'],
1175 return $recurParams;
1179 * Get pledge start date.
1184 public static function getPledgeStartDate($date, $pledgeBlock) {
1185 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1186 foreach ($startDate as $field => $value) {
1187 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1194 case 'contribution_date':
1196 $date = date('Ymd');
1200 case 'calendar_date':
1201 $date = date('Ymd', strtotime($date));
1204 case 'calendar_month':
1205 $date = self
::getPaymentDate($date);
1206 $date = date('Ymd', strtotime($date));
1218 * Get first payment date for pledge.
1222 * @return bool|string
1224 public static function getPaymentDate($day) {
1226 // Find out if current month has 31 days, if not, set it to 30 (last day).
1232 $current = date('d');
1234 case ($day == $current):
1235 $date = date('m/d/Y');
1238 case ($day > $current):
1239 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1242 case ($day < $current):
1243 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1254 * Override buildOptions to hack out some statuses.
1256 * @todo instead of using & hacking the shared optionGroup contribution_status use a separate one.
1258 * @param string $fieldName
1259 * @param string $context
1260 * @param array $props
1262 * @return array|bool
1264 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1265 $result = parent
::buildOptions($fieldName, $context, $props);
1266 if ($fieldName == 'status_id') {
1267 $result = array_diff($result, array('Failed'));