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 based on input parameters.
29 * It also stores all the retrieved values in the default array.
31 * @param array $params
32 * (reference ) an assoc array of name/value pairs.
33 * @param array $defaults
34 * (reference ) an assoc array to hold the flattened values.
36 * @return CRM_Pledge_BAO_Pledge
38 public static function retrieve(&$params, &$defaults) {
39 $pledge = new CRM_Pledge_DAO_Pledge();
40 $pledge->copyValues($params);
41 if ($pledge->find(TRUE)) {
42 CRM_Core_DAO
::storeValues($pledge, $defaults);
51 * @param array $params
52 * Reference array contains the values submitted by the form.
54 * @return CRM_Pledge_DAO_Pledge
56 public static function add(array $params): CRM_Pledge_DAO_Pledge
{
57 CRM_Core_Error
::deprecatedFunctionWarning('v4 api');
58 $hook = empty($params['id']) ?
'create' : 'edit';
59 CRM_Utils_Hook
::pre($hook, 'Pledge', $params['id'] ??
NULL, $params);
61 $pledge = new CRM_Pledge_DAO_Pledge();
63 // if pledge is complete update end date as current date
64 if ($pledge->status_id
== 1) {
65 $pledge->end_date
= date('Ymd');
68 $pledge->copyValues($params);
70 // set currency for CRM-1496
71 if (!isset($pledge->currency
)) {
72 $pledge->currency
= CRM_Core_Config
::singleton()->defaultCurrency
;
75 $result = $pledge->save();
77 CRM_Utils_Hook
::post($hook, 'Pledge', $pledge->id
, $pledge);
83 * Given the list of params in the params array, fetch the object
84 * and store the values in the values array
86 * @param array $params
87 * Input parameters to find object.
88 * @param array $values
89 * Output values of the object.
90 * @param array $returnProperties
91 * If you want to return specific fields.
94 * associated array of field values
96 public static function &getValues(&$params, &$values, $returnProperties = NULL) {
100 CRM_Core_DAO
::commonRetrieve('CRM_Pledge_BAO_Pledge', $params, $values, $returnProperties);
105 * Takes an associative array and creates a pledge object.
107 * @param array $params
108 * Assoc array of name/value pairs.
110 * @return CRM_Pledge_DAO_Pledge
111 * @throws \CRM_Core_Exception
113 public static function create(array $params): CRM_Pledge_DAO_Pledge
{
114 $action = empty($params['id']) ?
'create' : 'edit';
115 if ($action === 'create') {
117 'currency' => CRM_Core_Config
::singleton()->defaultCurrency
,
118 'installments' => (int) self
::fields()['installments']['default'],
119 'scheduled_date' => $params['start_date'] ??
date('Ymd'),
121 $params = array_merge($defaults, $params);
124 $isRecalculatePledgePayment = self
::isPaymentsRequireRecalculation($params);
125 $transaction = new CRM_Core_Transaction();
128 if (!empty($params['installment_amount'])) {
129 $params['amount'] = $params['installment_amount'] * $params['installments'];
132 if (!isset($params['pledge_status_id']) && !isset($params['status_id'])) {
133 if (isset($params['contribution_id'])) {
134 if ($params['installments'] > 1) {
135 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'In Progress');
139 if (!empty($params['id'])) {
140 $params['status_id'] = CRM_Pledge_BAO_PledgePayment
::calculatePledgeStatus($params['id']);
143 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Pending');
147 $paymentParams['status_id'] = $params['status_id'] ??
NULL;
149 CRM_Utils_Hook
::pre($action, 'Pledge', $params['id'] ??
NULL, $params);
150 $pledge = new CRM_Pledge_DAO_Pledge();
152 // if pledge is complete update end date as current date
153 if ($pledge->status_id
== 1) {
154 $pledge->end_date
= date('Ymd');
157 $pledge->copyValues($params);
159 CRM_Utils_Hook
::post($action, 'Pledge', $pledge->id
, $pledge);
161 // handle custom data.
162 if (!empty($params['custom']) &&
163 is_array($params['custom'])
165 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_pledge', $pledge->id
);
168 // skip payment stuff in edit mode
169 if (empty($params['id']) ||
$isRecalculatePledgePayment) {
171 // if pledge is pending delete all payments and recreate.
172 if ($isRecalculatePledgePayment) {
173 CRM_Pledge_BAO_PledgePayment
::deletePayments($pledge->id
);
176 // building payment params
177 $paymentParams['pledge_id'] = $pledge->id
;
185 'frequency_interval',
187 'installment_amount',
190 foreach ($paymentKeys as $key) {
191 $paymentParams[$key] = $params[$key] ??
NULL;
193 CRM_Pledge_BAO_PledgePayment
::createMultiple($paymentParams);
196 $transaction->commit();
198 $url = CRM_Utils_System
::url('civicrm/contact/view/pledge',
199 "action=view&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
203 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::UPDATE
)) {
204 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
205 "action=update&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
208 if (CRM_Core_Permission
::checkActionPermission('CiviPledge', CRM_Core_Action
::DELETE
)) {
209 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/pledge',
210 "action=delete&reset=1&id={$pledge->id}&cid={$pledge->contact_id}&context=home"
214 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
215 $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) . ')';
217 // add the recently created Pledge
218 CRM_Utils_Recent
::add($title,
231 * Is this a change to an existing pending pledge requiring payment schedule
234 * If the pledge is pending the code (slightly lazily) deletes & recreates
237 * If the payment dates or amounts have been manually edited then this can
238 * cause data loss. We can mitigate this to some extent by making sure we
239 * have a change that could potentially affect the schedule (rather than just
240 * a custom data change or similar).
242 * This calculation needs to be performed before update takes place as
243 * previous & new pledges are compared.
245 * @param array $params
249 protected static function isPaymentsRequireRecalculation($params) {
250 if (empty($params['is_pledge_pending']) ||
empty($params['id'])) {
253 $scheduleChangingParameters = [
256 'frequency_interval',
261 $existingPledgeDAO = new CRM_Pledge_BAO_Pledge();
262 $existingPledgeDAO->id
= $params['id'];
263 $existingPledgeDAO->find(TRUE);
264 foreach ($scheduleChangingParameters as $parameter) {
265 if ($parameter == 'start_date') {
266 if (strtotime($params[$parameter]) != strtotime($existingPledgeDAO->$parameter)) {
270 elseif ($params[$parameter] != $existingPledgeDAO->$parameter) {
284 public static function deletePledge($id) {
285 CRM_Utils_Hook
::pre('delete', 'Pledge', $id);
287 $transaction = new CRM_Core_Transaction();
289 // check for no Completed Payment records with the pledge
290 $payment = new CRM_Pledge_DAO_PledgePayment();
291 $payment->pledge_id
= $id;
294 while ($payment->fetch()) {
295 // also delete associated contribution.
296 if ($payment->contribution_id
) {
297 CRM_Contribute_BAO_Contribution
::deleteContribution($payment->contribution_id
);
302 $dao = new CRM_Pledge_DAO_Pledge();
304 $results = $dao->delete();
306 $transaction->commit();
308 CRM_Utils_Hook
::post('delete', 'Pledge', $dao->id
, $dao);
314 * Get the amount details date wise.
316 * @param string $status
317 * @param string $startDate
318 * @param string $endDate
322 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
324 $select = $from = $queryDate = NULL;
325 $statusId = CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', $status);
329 $where[] = 'status_id != ' . CRM_Core_PseudoConstant
::getKey('CRM_Pledge_BAO_Pledge', 'status_id', 'Cancelled');
336 $where[] = 'status_id = ' . $statusId;
341 $where[] = "create_date >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
344 $where[] = "create_date <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
347 $whereCond = implode(' AND ', $where);
350 SELECT sum( amount ) as pledge_amount, count( id ) as pledge_count, currency
352 WHERE $whereCond AND is_test=0
355 $start = substr($startDate, 0, 8);
356 $end = substr($endDate, 0, 8);
359 $dao = CRM_Core_DAO
::executeQuery($query);
360 while ($dao->fetch()) {
361 $pCount +
= $dao->pledge_count
;
362 $pamount[] = CRM_Utils_Money
::format($dao->pledge_amount
, $dao->currency
);
366 'pledge_amount' => implode(', ', $pamount),
367 'pledge_count' => $pCount,
368 'purl' => CRM_Utils_System
::url('civicrm/pledge/search',
369 "reset=1&force=1&pstatus={$statusId}&pstart={$start}&pend={$end}&test=0"
376 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
377 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
378 $queryDate = 'receive_date';
379 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
383 $select = 'sum( total_amount ) as received_pledge , count( cd.id ) as received_count';
384 $where[] = 'cp.status_id = ' . $statusId . ' AND cp.contribution_id = cd.id AND cd.is_test=0';
385 $queryDate = 'receive_date';
386 $from = ' civicrm_contribution cd, civicrm_pledge_payment cp';
390 $select = 'sum( scheduled_amount )as received_pledge , count( cp.id ) as received_count';
391 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
392 $queryDate = 'scheduled_date';
393 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
397 $select = 'sum( scheduled_amount ) as received_pledge , count( cp.id ) as received_count';
398 $where[] = 'cp.status_id = ' . $statusId . ' AND pledge.is_test=0';
399 $queryDate = 'scheduled_date';
400 $from = ' civicrm_pledge_payment cp INNER JOIN civicrm_pledge pledge on cp.pledge_id = pledge.id';
405 $where[] = " $queryDate >= '" . CRM_Utils_Type
::escape($startDate, 'Timestamp') . "'";
408 $where[] = " $queryDate <= '" . CRM_Utils_Type
::escape($endDate, 'Timestamp') . "'";
411 $whereCond = implode(' AND ', $where);
414 SELECT $select, cp.currency
420 $dao = CRM_Core_DAO
::executeQuery($query);
424 while ($dao->fetch()) {
425 $count +
= $dao->received_count
;
426 $amount[] = CRM_Utils_Money
::format($dao->received_pledge
, $dao->currency
);
430 return array_merge($pledge_amount, [
431 'received_amount' => implode(', ', $amount),
432 'received_count' => $count,
433 'url' => CRM_Utils_System
::url('civicrm/pledge/search',
434 "reset=1&force=1&status={$statusId}&start={$start}&end={$end}&test=0"
440 return $pledge_amount;
446 * Get list of pledges In Honor of contact Ids.
448 * @param int $honorId
449 * In Honor of Contact ID.
452 * return the list of pledge fields
454 public static function getHonorContacts($honorId) {
456 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
457 $honorDAO->contact_id
= $honorId;
461 while ($honorDAO->fetch()) {
462 $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment();
463 $pledgePaymentDAO->contribution_id
= $honorDAO->contribution_id
;
464 if ($pledgePaymentDAO->find(TRUE)) {
465 $pledgeDAO = new CRM_Pledge_DAO_Pledge();
466 $pledgeDAO->id
= $pledgePaymentDAO->pledge_id
;
467 if ($pledgeDAO->find(TRUE)) {
468 $params[$pledgeDAO->id
] = [
469 'honor_type' => CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id
),
470 'honorId' => $pledgeDAO->contact_id
,
471 'amount' => $pledgeDAO->amount
,
472 'status' => CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $pledgeDAO->status_id
),
473 'create_date' => $pledgeDAO->create_date
,
474 'acknowledge_date' => $pledgeDAO->acknowledge_date
,
475 'type' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
476 $pledgeDAO->financial_type_id
, 'name'
478 'display_name' => CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
479 $pledgeDAO->contact_id
, 'display_name'
490 * Send Acknowledgment and create activity.
492 * @param CRM_Core_Form $form
494 * @param array $params
495 * An assoc array of name/value pairs.
497 public static function sendAcknowledgment(&$form, $params) {
498 //handle Acknowledgment.
499 $allPayments = $payments = [];
501 // get All Payments status types.
502 $paymentStatusTypes = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
503 $returnProperties = [
509 // get all paymnets details.
510 CRM_Core_DAO
::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
512 if (!empty($allPayments)) {
513 foreach ($allPayments as $payID => $values) {
514 $contributionValue = $contributionStatus = [];
515 if (isset($values['contribution_id'])) {
516 $contributionParams = ['id' => $values['contribution_id']];
517 $returnProperties = ['contribution_status_id', 'receive_date'];
518 CRM_Core_DAO
::commonRetrieve('CRM_Contribute_DAO_Contribution',
519 $contributionParams, $contributionStatus, $returnProperties
521 $contributionValue = [
522 'status' => $contributionStatus['contribution_status_id'] ??
NULL,
523 'receive_date' => $contributionStatus['receive_date'] ??
NULL,
526 $payments[$payID] = array_merge($contributionValue,
528 'amount' => $values['scheduled_amount'] ??
NULL,
529 'due_date' => $values['scheduled_date'] ??
NULL,
530 'status' => CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'),
534 // get the first valid payment id.
535 if (!isset($form->paymentId
) && ($paymentStatusTypes[$values['status_id']] == 'Pending' ||
536 $paymentStatusTypes[$values['status_id']] == 'Overdue'
539 $form->paymentId
= $values['id'];
544 // assign pledge fields value to template.
547 'total_pledge_amount',
548 'frequency_interval',
555 foreach ($pledgeFields as $field) {
556 if (!empty($params[$field])) {
557 $form->assign($field, $params[$field]);
561 // assign all payments details.
563 $form->assign('payments', $payments);
566 // handle custom data.
568 if (!empty($params['hidden_custom'])) {
569 $groupTree = CRM_Core_BAO_CustomGroup
::getTree('Pledge', NULL, $params['id']);
570 $pledgeParams = [['pledge_id', '=', $params['id'], 0, 0]];
571 // retrieve custom data
572 foreach ($groupTree as $groupID => $group) {
573 $customFields = $customValues = [];
574 if ($groupID == 'info') {
577 foreach ($group['fields'] as $k => $field) {
578 $field['title'] = $field['label'];
579 $customFields["custom_{$k}"] = $field;
582 // to build array of customgroup & customfields in it
583 CRM_Core_BAO_UFGroup
::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
584 $customGroup[$group['title']] = $customValues;
588 $form->assign('customGroup', $customGroup);
590 // handle acknowledgment email stuff.
591 [$pledgerDisplayName, $pledgerEmail] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($params['contact_id']);
593 // check for online pledge.
594 if (!empty($params['receipt_from_email'])) {
595 $userName = $params['receipt_from_name'] ??
NULL;
596 $userEmail = $params['receipt_from_email'] ??
NULL;
598 elseif (!empty($params['from_email_id'])) {
599 $receiptFrom = $params['from_email_id'];
601 elseif ($userID = CRM_Core_Session
::singleton()->get('userID')) {
602 // check for logged in user.
606 ] = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
609 // set the domain values.
610 [$userName, $userEmail] = CRM_Core_BAO_Domain
::getNameAndEmail();
613 if (!isset($receiptFrom)) {
614 $receiptFrom = "$userName <$userEmail>";
617 [$sent, $subject, $message, $html] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
619 'groupName' => 'msg_tpl_workflow_pledge',
620 'valueName' => 'pledge_acknowledge',
621 'contactId' => $params['contact_id'],
622 'from' => $receiptFrom,
623 'toName' => $pledgerDisplayName,
624 'toEmail' => $pledgerEmail,
628 // check if activity record exist for this pledge
629 // Acknowledgment, if exist do not add activity.
630 $activityType = 'Pledge Acknowledgment';
631 $activity = new CRM_Activity_DAO_Activity();
632 $activity->source_record_id
= $params['id'];
633 $activity->activity_type_id
= CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
639 $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)';
641 if (!$activity->find()) {
643 'subject' => $subject,
644 'source_contact_id' => $params['contact_id'],
645 'source_record_id' => $params['id'],
646 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
650 'activity_date_time' => CRM_Utils_Date
::isoToMysql($params['acknowledge_date']),
651 'is_test' => $params['is_test'],
653 'details' => $details,
654 'campaign_id' => $params['campaign_id'] ??
NULL,
657 // lets insert assignee record.
658 if (!empty($params['contact_id'])) {
659 $activityParams['assignee_contact_id'] = $params['contact_id'];
662 if (is_a(CRM_Activity_BAO_Activity
::create($activityParams), 'CRM_Core_Error')) {
663 throw new CRM_Core_Exception('Failed creating Activity for acknowledgment');
669 * Combine all the exportable fields from the lower levels object.
671 * @param bool $checkPermission
674 * array of exportable Fields
676 public static function exportableFields($checkPermission = TRUE) {
677 if (!self
::$_exportableFields) {
678 if (!self
::$_exportableFields) {
679 self
::$_exportableFields = [];
682 $fields = CRM_Pledge_DAO_Pledge
::export();
684 $fields = array_merge($fields, CRM_Pledge_DAO_PledgePayment
::export());
686 // set title to calculated fields
687 $calculatedFields = [
688 'pledge_total_paid' => ['title' => ts('Total Paid')],
689 'pledge_balance_amount' => ['title' => ts('Balance Amount')],
690 'pledge_next_pay_date' => ['title' => ts('Next Payment Date')],
691 'pledge_next_pay_amount' => ['title' => ts('Next Payment Amount')],
692 'pledge_payment_paid_amount' => ['title' => ts('Paid Amount')],
693 'pledge_payment_paid_date' => ['title' => ts('Paid Date')],
694 'pledge_payment_status' => [
695 'title' => ts('Pledge Payment Status'),
696 'name' => 'pledge_payment_status',
697 'data_type' => CRM_Utils_Type
::T_STRING
,
703 'title' => ts('Pledge Status'),
704 'name' => 'pledge_status',
705 'data_type' => CRM_Utils_Type
::T_STRING
,
707 'pledge_frequency_unit' => [
708 'title' => ts('Pledge Frequency Unit'),
709 'name' => 'pledge_frequency_unit',
710 'data_type' => CRM_Utils_Type
::T_ENUM
,
712 'pledge_frequency_interval' => [
713 'title' => ts('Pledge Frequency Interval'),
714 'name' => 'pledge_frequency_interval',
715 'data_type' => CRM_Utils_Type
::T_INT
,
717 'pledge_contribution_page_id' => [
718 'title' => ts('Pledge Contribution Page Id'),
719 'name' => 'pledge_contribution_page_id',
720 'data_type' => CRM_Utils_Type
::T_INT
,
724 $fields = array_merge($fields, $pledgeFields, $calculatedFields);
727 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Pledge', FALSE, FALSE, FALSE, $checkPermission));
728 self
::$_exportableFields = $fields;
731 return self
::$_exportableFields;
735 * Get pending or in progress pledges.
737 * @param int $contactID
741 * associated array of pledge id(s)
743 public static function getContactPledges($contactID) {
745 $pledgeStatuses = CRM_Core_OptionGroup
::values('pledge_status',
746 FALSE, FALSE, FALSE, NULL, 'name'
751 // get pending and in progress status
752 foreach (['Pending', 'In Progress', 'Overdue'] as $name) {
753 if ($statusId = array_search($name, $pledgeStatuses)) {
754 $status[] = $statusId;
757 if (empty($status)) {
758 return $pledgeDetails;
761 $statusClause = " IN (" . implode(',', $status) . ")";
764 SELECT civicrm_pledge.id id
766 WHERE civicrm_pledge.status_id {$statusClause}
767 AND civicrm_pledge.contact_id = %1
770 $params[1] = [$contactID, 'Integer'];
771 $pledge = CRM_Core_DAO
::executeQuery($query, $params);
773 while ($pledge->fetch()) {
774 $pledgeDetails[] = $pledge->id
;
777 return $pledgeDetails;
781 * Get pledge record count for a Contact.
783 * @param int $contactID
786 * count of pledge records
788 public static function getContactPledgeCount($contactID) {
789 $query = "SELECT count(*) FROM civicrm_pledge WHERE civicrm_pledge.contact_id = {$contactID} AND civicrm_pledge.is_test = 0";
790 return CRM_Core_DAO
::singleValueQuery($query);
794 * @param array $params
797 * @throws \API_Exception
798 * @throws \CRM_Core_Exception
799 * @throws \CiviCRM_API3_Exception
801 public static function updatePledgeStatus($params): array {
803 $returnMessages = [];
805 $sendReminders = CRM_Utils_Array
::value('send_reminders', $params, FALSE);
807 $allStatus = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'));
808 $allPledgeStatus = CRM_Core_OptionGroup
::values('pledge_status',
809 TRUE, FALSE, FALSE, NULL, 'name', TRUE
811 unset($allPledgeStatus['Completed'], $allPledgeStatus['Cancelled']);
812 unset($allStatus['Completed'], $allStatus['Cancelled'], $allStatus['Failed']);
814 $statusIds = implode(',', $allStatus);
815 $pledgeStatusIds = implode(',', $allPledgeStatus);
819 SELECT pledge.contact_id as contact_id,
820 pledge.id as pledge_id,
821 pledge.amount as amount,
822 payment.scheduled_date as scheduled_date,
823 pledge.create_date as create_date,
824 payment.id as payment_id,
825 pledge.currency as currency,
826 pledge.contribution_page_id as contribution_page_id,
827 payment.reminder_count as reminder_count,
828 pledge.max_reminders as max_reminders,
829 payment.reminder_date as reminder_date,
830 pledge.initial_reminder_day as initial_reminder_day,
831 pledge.additional_reminder_day as additional_reminder_day,
832 pledge.status_id as pledge_status,
833 payment.status_id as payment_status,
834 pledge.is_test as is_test,
835 pledge.campaign_id as campaign_id,
836 SUM(payment.scheduled_amount) as amount_due,
837 ( SELECT sum(civicrm_pledge_payment.actual_amount)
838 FROM civicrm_pledge_payment
839 WHERE civicrm_pledge_payment.status_id = 1
840 AND civicrm_pledge_payment.pledge_id = pledge.id
842 FROM civicrm_pledge pledge, civicrm_pledge_payment payment
843 WHERE pledge.id = payment.pledge_id
844 AND payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$pledgeStatusIds} )
848 $dao = CRM_Core_DAO
::executeQuery($query);
851 $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = [];
852 while ($dao->fetch()) {
853 $checksumValue = CRM_Contact_BAO_Contact_Utils
::generateChecksum($dao->contact_id
);
855 $pledgeDetails[$dao->payment_id
] = [
856 'scheduled_date' => $dao->scheduled_date
,
857 'amount_due' => $dao->amount_due
,
858 'amount' => $dao->amount
,
859 'amount_paid' => $dao->amount_paid
,
860 'create_date' => $dao->create_date
,
861 'contact_id' => $dao->contact_id
,
862 'pledge_id' => $dao->pledge_id
,
863 'checksumValue' => $checksumValue,
864 'contribution_page_id' => $dao->contribution_page_id
,
865 'reminder_count' => $dao->reminder_count
,
866 'max_reminders' => $dao->max_reminders
,
867 'reminder_date' => $dao->reminder_date
,
868 'initial_reminder_day' => $dao->initial_reminder_day
,
869 'additional_reminder_day' => $dao->additional_reminder_day
,
870 'pledge_status' => $dao->pledge_status
,
871 'payment_status' => $dao->payment_status
,
872 'is_test' => $dao->is_test
,
873 'currency' => $dao->currency
,
874 'campaign_id' => $dao->campaign_id
,
877 $contactIds[$dao->contact_id
] = $dao->contact_id
;
878 $pledgeStatus[$dao->pledge_id
] = $dao->pledge_status
;
880 if (CRM_Utils_Date
::overdue(CRM_Utils_Date
::customFormat($dao->scheduled_date
, '%Y%m%d'),
882 ) && $dao->payment_status
!= $allStatus['Overdue']
884 $pledgePayments[$dao->pledge_id
][$dao->payment_id
] = $dao->payment_id
;
887 $allPledgeStatus = array_flip($allPledgeStatus);
889 // process the updating script...
890 foreach ($pledgePayments as $pledgeId => $paymentIds) {
891 // 1. update the pledge /pledge payment status. returns new status when an update happens
892 $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allPledgeStatus[$pledgeStatus[$pledgeId]]})";
894 $newStatus = CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeId, $paymentIds,
895 $allStatus['Overdue'], NULL, 0, FALSE, TRUE
897 if ($newStatus != $pledgeStatus[$pledgeId]) {
898 $returnMessages[] = "- status updated to: {$allPledgeStatus[$newStatus]}";
903 if ($sendReminders) {
904 // retrieve domain tokens
906 'domain' => ['name', 'phone', 'address', 'email'],
907 'contact' => CRM_Core_SelectValues
::contactTokens(),
910 // retrieve contact tokens
912 // this function does NOT return Deceased contacts since we don't want to send them email
913 $contactDetails = civicrm_api3('Contact', 'get', [
915 'id' => ['IN' => $contactIds],
916 'return' => ['id', 'display_name', 'email', 'do_not_email', 'email', 'on_hold'],
919 // assign domain values to template
920 $template = CRM_Core_Smarty
::singleton();
923 $receiptFrom = CRM_Core_BAO_Domain
::getNameAndEmail(FALSE, TRUE);
924 $receiptFrom = reset($receiptFrom);
926 foreach ($pledgeDetails as $paymentId => $details) {
927 if (array_key_exists($details['contact_id'], $contactDetails)) {
928 $contactId = $details['contact_id'];
929 $pledgerName = $contactDetails[$contactId]['display_name'];
935 if (empty($details['reminder_date'])) {
936 $nextReminderDate = new DateTime($details['scheduled_date']);
937 $details['initial_reminder_day'] = empty($details['initial_reminder_day']) ?
0 : $details['initial_reminder_day'];
938 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
939 $nextReminderDate = $nextReminderDate->format("Ymd");
942 $nextReminderDate = new DateTime($details['reminder_date']);
943 $details['additional_reminder_day'] = empty($details['additional_reminder_day']) ?
0 : $details['additional_reminder_day'];
944 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
945 $nextReminderDate = $nextReminderDate->format("Ymd");
947 if (($details['reminder_count'] < $details['max_reminders'])
948 && ($nextReminderDate <= $now)
951 $toEmail = $doNotEmail = $onHold = NULL;
953 if (!empty($contactDetails[$contactId]['email'])) {
954 $toEmail = $contactDetails[$contactId]['email'];
957 if (!empty($contactDetails[$contactId]['do_not_email'])) {
958 $doNotEmail = $contactDetails[$contactId]['do_not_email'];
961 if (!empty($contactDetails[$contactId]['on_hold'])) {
962 $onHold = $contactDetails[$contactId]['on_hold'];
965 // 2. send acknowledgement mail
966 if ($toEmail && !($doNotEmail ||
$onHold)) {
967 // assign value to template
968 $template->assign('amount_paid', $details['amount_paid'] ?
$details['amount_paid'] : 0);
969 $template->assign('next_payment', $details['scheduled_date']);
970 $template->assign('amount_due', $details['amount_due']);
971 $template->assign('checksumValue', $details['checksumValue']);
972 $template->assign('contribution_page_id', $details['contribution_page_id']);
973 $template->assign('pledge_id', $details['pledge_id']);
974 $template->assign('scheduled_payment_date', $details['scheduled_date']);
975 $template->assign('amount', $details['amount']);
976 $template->assign('create_date', $details['create_date']);
977 $template->assign('currency', $details['currency']);
983 ] = CRM_Core_BAO_MessageTemplate
::sendTemplate(
985 'groupName' => 'msg_tpl_workflow_pledge',
986 'valueName' => 'pledge_reminder',
987 'contactId' => $contactId,
988 'from' => $receiptFrom,
989 'toName' => $pledgerName,
990 'toEmail' => $toEmail,
994 // 3. update pledge payment details
996 CRM_Pledge_BAO_PledgePayment
::updateReminderDetails($paymentId);
997 $activityType = 'Pledge Reminder';
999 'subject' => $subject,
1000 'source_contact_id' => $contactId,
1001 'source_record_id' => $paymentId,
1002 'assignee_contact_id' => $contactId,
1003 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity',
1007 'due_date_time' => CRM_Utils_Date
::isoToMysql($details['scheduled_date']),
1008 'is_test' => $details['is_test'],
1010 'campaign_id' => $details['campaign_id'],
1013 civicrm_api3('activity', 'create', $activityParams);
1015 catch (CiviCRM_API3_Exception
$e) {
1016 $returnMessages[] = "Failed creating Activity for Pledge Reminder: " . $e->getMessage();
1017 return ['is_error' => 1, 'message' => $returnMessages];
1019 $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
1024 // end foreach on $pledgeDetails
1026 // end if ( $sendReminders )
1027 $returnMessages[] = "{$updateCnt} records updated.";
1029 return ['is_error' => 0, 'messages' => implode("\n\r", $returnMessages)];
1033 * Mark a pledge (and any outstanding payments) as cancelled.
1035 * @param int $pledgeID
1037 public static function cancel($pledgeID) {
1038 $paymentIDs = self
::findCancelablePayments($pledgeID);
1039 $status = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1040 $cancelled = array_search('Cancelled', $status);
1041 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL,
1042 $cancelled, 0, FALSE, TRUE
1047 * Find payments which can be safely canceled.
1049 * @param int $pledgeID
1052 * Array of int (civicrm_pledge_payment.id)
1054 public static function findCancelablePayments($pledgeID) {
1055 $statuses = array_flip(CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'label'));
1057 $paymentDAO = new CRM_Pledge_DAO_PledgePayment();
1058 $paymentDAO->pledge_id
= $pledgeID;
1059 $paymentDAO->whereAdd(sprintf("status_id IN (%d,%d)",
1060 $statuses['Overdue'],
1061 $statuses['Pending']
1063 $paymentDAO->find();
1066 while ($paymentDAO->fetch()) {
1067 $paymentIDs[] = $paymentDAO->id
;
1073 * Is this pledge free from financial transactions (this is important to know
1074 * as we allow editing when no transactions have taken place - the editing
1075 * process currently involves deleting all pledge payments & contributions
1076 * & recreating so we want to block that if appropriate).
1078 * @param int $pledgeID
1079 * @param int $pledgeStatusID
1082 * do financial transactions exist for this pledge?
1084 public static function pledgeHasFinancialTransactions($pledgeID, $pledgeStatusID) {
1085 if (empty($pledgeStatusID)) {
1086 // why would this happen? If we can see where it does then we can see if we should look it up.
1087 // but assuming from form code it CAN be empty.
1090 if (self
::isTransactedStatus($pledgeStatusID)) {
1094 return civicrm_api3('pledge_payment', 'getcount', [
1095 'pledge_id' => $pledgeID,
1096 'contribution_id' => ['IS NOT NULL' => TRUE],
1101 * Does this pledge / pledge payment status mean that a financial transaction
1104 * @param int $statusID
1108 * is it a transactional status?
1110 protected static function isTransactedStatus($statusID) {
1111 if (!in_array($statusID, self
::getNonTransactionalStatus())) {
1118 * Get array of non transactional statuses.
1121 * non transactional status ids
1123 protected static function getNonTransactionalStatus() {
1124 $paymentStatus = CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name');
1125 return array_flip(array_intersect($paymentStatus, ['Overdue', 'Pending']));
1129 * Create array for recur record for pledge.
1132 * params for recur record
1134 public static function buildRecurParams($params) {
1137 'auto_renew' => TRUE,
1138 'frequency_unit' => $params['pledge_frequency_unit'],
1139 'frequency_interval' => $params['pledge_frequency_interval'],
1140 'installments' => $params['pledge_installments'],
1141 'start_date' => $params['receive_date'],
1143 return $recurParams;
1147 * Get pledge start date.
1152 public static function getPledgeStartDate($date, $pledgeBlock) {
1153 $startDate = (array) json_decode($pledgeBlock['pledge_start_date']);
1154 foreach ($startDate as $field => $value) {
1155 if (!empty($date) && empty($pledgeBlock['is_pledge_start_date_editable'])) {
1162 case 'contribution_date':
1164 $date = date('Ymd');
1168 case 'calendar_date':
1169 $date = date('Ymd', strtotime($date));
1172 case 'calendar_month':
1173 $date = self
::getPaymentDate($date);
1174 $date = date('Ymd', strtotime($date));
1186 * Get first payment date for pledge.
1190 * @return bool|string
1192 public static function getPaymentDate($day) {
1194 // Find out if current month has 31 days, if not, set it to 30 (last day).
1200 $current = date('d');
1202 case ($day == $current):
1203 $date = date('m/d/Y');
1206 case ($day > $current):
1207 $date = date('m/d/Y', mktime(0, 0, 0, date('m'), $day, date('Y')));
1210 case ($day < $current):
1211 $date = date('m/d/Y', mktime(0, 0, 0, date('m', strtotime("+1 month")), $day, date('Y')));
1222 * Override buildOptions to hack out some statuses.
1224 * @param string $fieldName
1225 * @param string $context
1226 * @param array $props
1228 * @return array|bool
1229 * @todo instead of using & hacking the shared optionGroup
1230 * contribution_status use a separate one.
1233 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1234 $result = parent
::buildOptions($fieldName, $context, $props);
1235 if ($fieldName == 'status_id') {
1236 $result = array_diff($result, ['Failed']);